-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSystrayLauncher.c
More file actions
executable file
·1774 lines (1530 loc) · 63.5 KB
/
SystrayLauncher.c
File metadata and controls
executable file
·1774 lines (1530 loc) · 63.5 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
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <math.h>
#include <assert.h>
// WebView2 headers required from SDK
#include "WebView2.h"
#include "resource.h"
#define WINDOW_SIZE_PERCENTAGE 0.9
#define RESOLUTION_CHANGE_DEBOUNCE_MS 1000
#define CONFIG_FILENAME L"config.ini"
#define APP_NAME L"SystrayLauncher"
#define MUTEX_NAME L"SystrayLauncher_SingleInstance_Mutex_9F8A7B6C"
#define TRAY_ICON_ID 100
#define WM_TRAYICON (WM_APP + 1)
#define ID_TRAY_MENU_REFRESH 1
#define ID_TRAY_MENU_CLEAR_CACHE 2
#define ID_TRAY_MENU_OPEN 3
#define ID_TRAY_MENU_CONFIGURE 5
#define ID_TRAY_MENU_EXIT 4
// Registry settings
#define REG_COMPANY L"JPIT"
#define REG_APPNAME L"SystrayLauncher"
#define REG_KEY_PATH L"SOFTWARE\\JPIT\\SystrayLauncher"
#define REG_VALUE_URL L"URL"
#define REG_VALUE_TITLE L"WindowTitle"
#define REG_VALUE_ONHIDEJS L"OnHideJS"
#define REG_VALUE_ONSHOWJS L"OnShowJS"
#define REG_VALUE_CONFIGURED L"Configured"
#define ID_TIMER_INITIAL_HIDE_JS 2
#define INITIAL_HIDE_JS_DELAY_MS 2000
#define ID_TIMER_VISIBILITY_CHECK 3
#define VISIBILITY_CHECK_INTERVAL_MS 250
#define ID_TIMER_CFG_SHOW_FALLBACK 4
#define CFG_SHOW_FALLBACK_DELAY_MS 350
typedef struct {
wchar_t url[2048];
wchar_t windowTitle[256];
wchar_t onHideJs[4096];
wchar_t onShowJs[4096];
} Configuration;
typedef enum {
JS_VISIBILITY_UNKNOWN = -1,
JS_VISIBILITY_HIDDEN = 0,
JS_VISIBILITY_SHOWN = 1
} JsVisibility;
// Globals
static Configuration g_config;
static HWND g_hwnd = NULL;
static HWND g_hwndOwner = NULL; // Invisible owner window to prevent taskbar appearance
static ICoreWebView2Controller* g_webViewController = NULL;
static ICoreWebView2* g_webView = NULL;
static NOTIFYICONDATAW g_nid = {0};
static UINT g_WM_TASKBARCREATED = 0;
static HANDLE g_hMutex = NULL;
static wchar_t g_iniPath[MAX_PATH];
static wchar_t g_initialUrl[2048];
static UINT_PTR g_timerId = 0;
static int g_lastScreenWidth = 0;
static int g_lastScreenHeight = 0;
static float g_lastDpiX = 0.0f;
static float g_lastDpiY = 0.0f;
static volatile LONG g_isInitialized = FALSE;
static HINSTANCE g_hInstance;
static JsVisibility g_jsVisibility = JS_VISIBILITY_UNKNOWN;
static wchar_t g_webView2Version[128] = L"Unknown";
// Config dialog WebView2 globals
static HWND g_cfgHwnd = NULL;
static ICoreWebView2Environment* g_cfgEnv = NULL;
static ICoreWebView2Controller* g_cfgController = NULL;
static ICoreWebView2* g_cfgWebView = NULL;
static BOOL g_cfgSaved = FALSE;
static BOOL g_cfgWindowShown = FALSE;
// Dynamic WebView2 loading
static WCHAR g_extractedDllPath[MAX_PATH] = {0};
typedef HRESULT (STDAPICALLTYPE *PFN_CreateCoreWebView2EnvironmentWithOptions)(
LPCWSTR, LPCWSTR, void*,
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
static PFN_CreateCoreWebView2EnvironmentWithOptions fnCreateEnvironment = NULL;
// Forward declarations
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void LoadConfiguration(const wchar_t* iniPath, Configuration* config);
void CreateDefaultIni(const wchar_t* iniPath);
void ParseConfigLine(wchar_t* line, Configuration* config);
void ShowMainWindow(void);
void HideMainWindow(void);
void CreateTrayIcon(HWND hwnd);
void ShowContextMenu(HWND hwnd);
void RefreshTrayIcon(void);
void CaptureDisplaySettings(void);
BOOL HasDisplaySettingsChanged(void);
void DebugPrint(const wchar_t* format, ...);
void SetSpellCheckLanguages(ICoreWebView2* webview, const wchar_t* languages);
void ReloadTargetPage(void);
void ClearWebViewCacheAndReload(void);
void ExecuteJavaScript(const wchar_t* js);
static BOOL IsWebViewReady(void);
static BOOL IsWindowActuallyVisible(HWND hwnd);
static void UpdateJsVisibilityState(HWND hwnd);
static void StartVisibilityTimer(HWND hwnd);
static void StopVisibilityTimer(HWND hwnd);
// Registry and config dialog functions
static BOOL LoadConfigFromRegistry(Configuration* config);
static BOOL SaveConfigToRegistry(const Configuration* config);
static BOOL IsFirstLaunch(void);
static void MarkAsConfigured(void);
static void ApplyConfiguration(void);
static BOOL load_webview2_loader(void);
static void ShowConfigWebViewDialog(void);
// WebView2 Callbacks
HRESULT STDMETHODCALLTYPE EnvCompletedHandler_QueryInterface(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* This,
REFIID riid, void** ppvObject);
ULONG STDMETHODCALLTYPE EnvCompletedHandler_AddRef(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* This);
ULONG STDMETHODCALLTYPE EnvCompletedHandler_Release(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* This);
HRESULT STDMETHODCALLTYPE EnvCompletedHandler_Invoke(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* This,
HRESULT result, ICoreWebView2Environment* environment);
typedef struct {
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandlerVtbl* lpVtbl;
LONG refCount;
HWND hwnd;
wchar_t* userDataPath;
} EnvCompletedHandler;
HRESULT STDMETHODCALLTYPE ControllerCompletedHandler_QueryInterface(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler* This,
REFIID riid, void** ppvObject);
ULONG STDMETHODCALLTYPE ControllerCompletedHandler_AddRef(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler* This);
ULONG STDMETHODCALLTYPE ControllerCompletedHandler_Release(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler* This);
HRESULT STDMETHODCALLTYPE ControllerCompletedHandler_Invoke(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler* This,
HRESULT result, ICoreWebView2Controller* controller);
typedef struct {
ICoreWebView2CreateCoreWebView2ControllerCompletedHandlerVtbl* lpVtbl;
LONG refCount;
HWND hwnd;
} ControllerCompletedHandler;
HRESULT STDMETHODCALLTYPE ClearBrowsingDataCompletedHandler_QueryInterface(
ICoreWebView2ClearBrowsingDataCompletedHandler* This,
REFIID riid, void** ppvObject);
ULONG STDMETHODCALLTYPE ClearBrowsingDataCompletedHandler_AddRef(
ICoreWebView2ClearBrowsingDataCompletedHandler* This);
ULONG STDMETHODCALLTYPE ClearBrowsingDataCompletedHandler_Release(
ICoreWebView2ClearBrowsingDataCompletedHandler* This);
HRESULT STDMETHODCALLTYPE ClearBrowsingDataCompletedHandler_Invoke(
ICoreWebView2ClearBrowsingDataCompletedHandler* This,
HRESULT errorCode);
typedef struct {
ICoreWebView2ClearBrowsingDataCompletedHandlerVtbl* lpVtbl;
LONG refCount;
} ClearBrowsingDataCompletedHandler;
// ExecuteScript completion handler (fire-and-forget)
HRESULT STDMETHODCALLTYPE ExecuteScriptCompletedHandler_QueryInterface(
ICoreWebView2ExecuteScriptCompletedHandler* This,
REFIID riid, void** ppvObject);
ULONG STDMETHODCALLTYPE ExecuteScriptCompletedHandler_AddRef(
ICoreWebView2ExecuteScriptCompletedHandler* This);
ULONG STDMETHODCALLTYPE ExecuteScriptCompletedHandler_Release(
ICoreWebView2ExecuteScriptCompletedHandler* This);
HRESULT STDMETHODCALLTYPE ExecuteScriptCompletedHandler_Invoke(
ICoreWebView2ExecuteScriptCompletedHandler* This,
HRESULT errorCode, LPCWSTR resultObjectAsJson);
typedef struct {
ICoreWebView2ExecuteScriptCompletedHandlerVtbl* lpVtbl;
LONG refCount;
} ExecuteScriptCompletedHandler;
// Configuration functions
void LoadConfiguration(const wchar_t* iniPath, Configuration* config) {
wcscpy_s(config->url, 2048, L"https://www.google.com/");
wcscpy_s(config->windowTitle, 256, L"Systray Launcher");
config->onHideJs[0] = L'\0';
config->onShowJs[0] = L'\0';
if (!PathFileExistsW(iniPath)) {
CreateDefaultIni(iniPath);
return;
}
FILE* file = NULL;
if (_wfopen_s(&file, iniPath, L"r, ccs=UTF-8") != 0 || !file) {
// Fallback: try ANSI
char pathA[MAX_PATH];
wcstombs(pathA, iniPath, MAX_PATH);
FILE* fileA = NULL;
if (fopen_s(&fileA, pathA, "r") == 0 && fileA) {
char lineA[4096];
while (fgets(lineA, sizeof(lineA), fileA)) {
wchar_t lineW[4096];
MultiByteToWideChar(CP_ACP, 0, lineA, -1, lineW, 4096);
ParseConfigLine(lineW, config);
}
fclose(fileA);
}
return;
}
wchar_t line[4096];
while (fgetws(line, sizeof(line)/sizeof(wchar_t), file)) {
ParseConfigLine(line, config);
}
fclose(file);
}
void ParseConfigLine(wchar_t* line, Configuration* config) {
while (iswspace(*line)) line++;
if (line[0] == L'#' || line[0] == L';' || line[0] == L'\0' || line[0] == L'\n') return;
wchar_t* equals = wcschr(line, L'=');
if (!equals) return;
*equals = L'\0';
wchar_t* key = line;
wchar_t* value = equals + 1;
// Trim key
while (iswspace(*key)) key++;
size_t keyLen = wcslen(key);
while (keyLen > 0 && iswspace(key[keyLen - 1])) key[--keyLen] = L'\0';
for (wchar_t* p = key; *p; ++p) *p = towlower(*p);
// Trim value
while (iswspace(*value)) value++;
size_t valLen = wcslen(value);
while (valLen > 0 && iswspace(value[valLen - 1])) value[--valLen] = L'\0';
if (valLen > 0 && value[valLen-1] == L'\n') value[--valLen] = L'\0';
if (valLen > 0 && value[valLen-1] == L'\r') value[--valLen] = L'\0';
if (wcscmp(key, L"url") == 0) {
wcscpy_s(config->url, 2048, value);
} else if (wcscmp(key, L"windowtitle") == 0) {
wcscpy_s(config->windowTitle, 256, value);
} else if (wcscmp(key, L"onhidejs") == 0) {
wcscpy_s(config->onHideJs, 4096, value);
} else if (wcscmp(key, L"onshowjs") == 0) {
wcscpy_s(config->onShowJs, 4096, value);
}
}
void CreateDefaultIni(const wchar_t* iniPath) {
const wchar_t* content = L"# SystrayLauncher Configuration File\n"
L"# Lines starting with # or ; are comments\n\n"
L"url=https://www.google.com/\n\n"
L"windowtitle=Systray Launcher\n";
FILE* file = NULL;
_wfopen_s(&file, iniPath, L"w, ccs=UTF-8");
if (file) {
fputws(content, file);
fclose(file);
}
}
// Registry functions
static BOOL LoadConfigFromRegistry(Configuration* config) {
HKEY hKey;
LONG result = RegOpenKeyExW(HKEY_CURRENT_USER, REG_KEY_PATH, 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS) {
return FALSE;
}
DWORD dataSize;
DWORD dataType;
// Load URL
dataSize = sizeof(config->url);
if (RegQueryValueExW(hKey, REG_VALUE_URL, NULL, &dataType, (LPBYTE)config->url, &dataSize) != ERROR_SUCCESS) {
wcscpy_s(config->url, 2048, L"https://www.google.com/");
}
// Load Window Title
dataSize = sizeof(config->windowTitle);
if (RegQueryValueExW(hKey, REG_VALUE_TITLE, NULL, &dataType, (LPBYTE)config->windowTitle, &dataSize) != ERROR_SUCCESS) {
wcscpy_s(config->windowTitle, 256, L"Systray Launcher");
}
// Load OnHideJS
dataSize = sizeof(config->onHideJs);
if (RegQueryValueExW(hKey, REG_VALUE_ONHIDEJS, NULL, &dataType, (LPBYTE)config->onHideJs, &dataSize) != ERROR_SUCCESS) {
config->onHideJs[0] = L'\0';
}
// Load OnShowJS
dataSize = sizeof(config->onShowJs);
if (RegQueryValueExW(hKey, REG_VALUE_ONSHOWJS, NULL, &dataType, (LPBYTE)config->onShowJs, &dataSize) != ERROR_SUCCESS) {
config->onShowJs[0] = L'\0';
}
RegCloseKey(hKey);
return TRUE;
}
static BOOL SaveConfigToRegistry(const Configuration* config) {
HKEY hKey;
DWORD disposition;
LONG result = RegCreateKeyExW(HKEY_CURRENT_USER, REG_KEY_PATH, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &disposition);
if (result != ERROR_SUCCESS) {
return FALSE;
}
// Save URL
RegSetValueExW(hKey, REG_VALUE_URL, 0, REG_SZ,
(const BYTE*)config->url, (DWORD)((wcslen(config->url) + 1) * sizeof(wchar_t)));
// Save Window Title
RegSetValueExW(hKey, REG_VALUE_TITLE, 0, REG_SZ,
(const BYTE*)config->windowTitle, (DWORD)((wcslen(config->windowTitle) + 1) * sizeof(wchar_t)));
// Save OnHideJS
RegSetValueExW(hKey, REG_VALUE_ONHIDEJS, 0, REG_SZ,
(const BYTE*)config->onHideJs, (DWORD)((wcslen(config->onHideJs) + 1) * sizeof(wchar_t)));
// Save OnShowJS
RegSetValueExW(hKey, REG_VALUE_ONSHOWJS, 0, REG_SZ,
(const BYTE*)config->onShowJs, (DWORD)((wcslen(config->onShowJs) + 1) * sizeof(wchar_t)));
RegCloseKey(hKey);
return TRUE;
}
static BOOL IsFirstLaunch(void) {
HKEY hKey;
LONG result = RegOpenKeyExW(HKEY_CURRENT_USER, REG_KEY_PATH, 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS) {
return TRUE; // Key doesn't exist = first launch
}
DWORD configured = 0;
DWORD dataSize = sizeof(configured);
result = RegQueryValueExW(hKey, REG_VALUE_CONFIGURED, NULL, NULL, (LPBYTE)&configured, &dataSize);
RegCloseKey(hKey);
return (result != ERROR_SUCCESS || configured == 0);
}
static void MarkAsConfigured(void) {
HKEY hKey;
DWORD disposition;
LONG result = RegCreateKeyExW(HKEY_CURRENT_USER, REG_KEY_PATH, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &disposition);
if (result == ERROR_SUCCESS) {
DWORD configured = 1;
RegSetValueExW(hKey, REG_VALUE_CONFIGURED, 0, REG_DWORD, (const BYTE*)&configured, sizeof(configured));
RegCloseKey(hKey);
}
}
static void ApplyConfiguration(void) {
// Update initial URL
wcscpy_s(g_initialUrl, 2048, g_config.url);
// Update window title
if (g_hwnd) {
SetWindowTextW(g_hwnd, g_config.windowTitle);
}
// Update tray icon tooltip
if (g_nid.hWnd) {
wcscpy_s(g_nid.szTip, sizeof(g_nid.szTip)/sizeof(wchar_t), g_config.windowTitle);
Shell_NotifyIconW(NIM_MODIFY, &g_nid);
}
// Navigate to the new URL only if the main window is visible
if (g_webView && g_hwnd && IsWindowVisible(g_hwnd)) {
g_webView->lpVtbl->Navigate(g_webView, g_config.url);
}
}
// Dynamic WebView2 loader extraction
static BOOL load_webview2_loader(void) {
HRSRC hRes = FindResource(NULL, MAKEINTRESOURCE(IDR_WEBVIEW2_DLL), RT_RCDATA);
if (hRes) {
HGLOBAL hData = LoadResource(NULL, hRes);
DWORD dllSize = SizeofResource(NULL, hRes);
const void *dllBytes = LockResource(hData);
if (dllBytes && dllSize > 0) {
WCHAR tempDir[MAX_PATH];
DWORD tempLen = GetTempPathW(MAX_PATH, tempDir);
if (tempLen > 0 && tempLen < MAX_PATH - 30) {
swprintf(g_extractedDllPath, MAX_PATH, L"%sWebView2Loader.dll", tempDir);
HANDLE hFile = CreateFileW(g_extractedDllPath, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
DWORD written = 0;
WriteFile(hFile, dllBytes, dllSize, &written, NULL);
CloseHandle(hFile);
if (written == dllSize) {
HMODULE hMod = LoadLibraryW(g_extractedDllPath);
if (hMod) {
fnCreateEnvironment = (PFN_CreateCoreWebView2EnvironmentWithOptions)
GetProcAddress(hMod, "CreateCoreWebView2EnvironmentWithOptions");
if (fnCreateEnvironment) return TRUE;
}
}
}
}
}
}
return FALSE;
}
// JSON helpers
static BOOL json_get_string(const char *json, const char *key, char *out, size_t outLen) {
char search[128];
snprintf(search, sizeof(search), "\"%s\"", key);
const char *p = strstr(json, search);
if (!p) return FALSE;
p += strlen(search);
while (*p == ' ' || *p == ':') p++;
if (*p != '"') return FALSE;
p++;
size_t i = 0;
while (*p && i < outLen - 1) {
if (*p == '"') break;
if (*p == '\\' && *(p + 1)) {
p++;
switch (*p) {
case '"': out[i++] = '"'; break;
case '\\': out[i++] = '\\'; break;
case 'n': out[i++] = '\n'; break;
case 'r': out[i++] = '\r'; break;
case 't': out[i++] = '\t'; break;
default: out[i++] = *p; break;
}
} else {
out[i++] = *p;
}
p++;
}
out[i] = '\0';
return TRUE;
}
static void json_escape_wstring(const wchar_t *in, wchar_t *out, size_t outLen) {
size_t j = 0;
for (size_t i = 0; in[i] && j < outLen - 2; i++) {
wchar_t c = in[i];
if (c == L'"' || c == L'\\') {
if (j + 2 >= outLen) break;
out[j++] = L'\\';
out[j++] = c;
} else if (c == L'\n') {
if (j + 2 >= outLen) break;
out[j++] = L'\\';
out[j++] = L'n';
} else if (c == L'\r') {
if (j + 2 >= outLen) break;
out[j++] = L'\\';
out[j++] = L'r';
} else if (c == L'\t') {
if (j + 2 >= outLen) break;
out[j++] = L'\\';
out[j++] = L't';
} else {
out[j++] = c;
}
}
out[j] = L'\0';
}
// Config dialog WebView2 helpers
static void webview_cfg_execute_script(const wchar_t* script) {
if (!g_cfgWebView || !script) return;
ExecuteScriptCompletedHandler* handler =
(ExecuteScriptCompletedHandler*)calloc(1, sizeof(ExecuteScriptCompletedHandler));
if (!handler) return;
static ICoreWebView2ExecuteScriptCompletedHandlerVtbl vtbl = {
ExecuteScriptCompletedHandler_QueryInterface,
ExecuteScriptCompletedHandler_AddRef,
ExecuteScriptCompletedHandler_Release,
ExecuteScriptCompletedHandler_Invoke
};
handler->lpVtbl = &vtbl;
handler->refCount = 1;
g_cfgWebView->lpVtbl->ExecuteScript(g_cfgWebView, script,
(ICoreWebView2ExecuteScriptCompletedHandler*)handler);
handler->lpVtbl->Release((ICoreWebView2ExecuteScriptCompletedHandler*)handler);
}
static void cfg_sync_controller_bounds(void) {
if (!g_cfgController || !g_cfgHwnd) return;
RECT bounds;
GetClientRect(g_cfgHwnd, &bounds);
g_cfgController->lpVtbl->put_Bounds(g_cfgController, bounds);
g_cfgController->lpVtbl->put_IsVisible(g_cfgController, TRUE);
}
static void webview_push_init_config(void) {
wchar_t eUrl[4096], eTitle[512], eHide[8192], eShow[8192];
json_escape_wstring(g_config.url, eUrl, 4096);
json_escape_wstring(g_config.windowTitle, eTitle, 512);
json_escape_wstring(g_config.onHideJs, eHide, 8192);
json_escape_wstring(g_config.onShowJs, eShow, 8192);
wchar_t script[16384];
swprintf(script, 16384,
L"window.onInit({\"config\":{\"url\":\"%s\",\"windowTitle\":\"%s\",\"onHideJs\":\"%s\",\"onShowJs\":\"%s\"}})",
eUrl, eTitle, eHide, eShow);
webview_cfg_execute_script(script);
}
// Minimal COM handler struct for config dialog (shared by all cfg handlers)
typedef struct {
void* lpVtbl;
LONG refCount;
} CfgHandler;
// Config dialog COM handlers — simplified pattern
static HRESULT STDMETHODCALLTYPE CfgHandler_QueryInterface(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler *This, REFIID riid, void **ppv) {
(void)riid;
*ppv = This;
((CfgHandler*)This)->refCount++;
return S_OK;
}
static ULONG STDMETHODCALLTYPE CfgHandler_AddRef(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler *This) {
return ++((CfgHandler*)This)->refCount;
}
static ULONG STDMETHODCALLTYPE CfgHandler_Release(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler *This) {
ULONG rc = --((CfgHandler*)This)->refCount;
if (rc == 0) free(This);
return rc;
}
static HRESULT STDMETHODCALLTYPE CfgCtrlCompleted_Invoke(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*, HRESULT, ICoreWebView2Controller*);
static HRESULT STDMETHODCALLTYPE CfgMsgReceived_Invoke(
ICoreWebView2WebMessageReceivedEventHandler*, ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs*);
static HRESULT STDMETHODCALLTYPE CfgEnvCompleted_Invoke(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler *This,
HRESULT result, ICoreWebView2Environment *env) {
(void)This;
if (FAILED(result) || !env) return result;
g_cfgEnv = env;
env->lpVtbl->AddRef(env);
static ICoreWebView2CreateCoreWebView2ControllerCompletedHandlerVtbl ctrlVtbl = {0};
static BOOL init = FALSE;
if (!init) {
ctrlVtbl.QueryInterface = (HRESULT (STDMETHODCALLTYPE*)(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*, REFIID, void**))CfgHandler_QueryInterface;
ctrlVtbl.AddRef = (ULONG (STDMETHODCALLTYPE*)(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*))CfgHandler_AddRef;
ctrlVtbl.Release = (ULONG (STDMETHODCALLTYPE*)(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*))CfgHandler_Release;
ctrlVtbl.Invoke = CfgCtrlCompleted_Invoke;
init = TRUE;
}
CfgHandler *handler = (CfgHandler*)malloc(sizeof(CfgHandler));
handler->lpVtbl = &ctrlVtbl;
handler->refCount = 1;
env->lpVtbl->CreateCoreWebView2Controller(env, g_cfgHwnd,
(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*)handler);
((ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*)handler)->lpVtbl->Release(
(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*)handler);
return S_OK;
}
static ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandlerVtbl g_cfgEnvVtbl = {
CfgHandler_QueryInterface,
CfgHandler_AddRef,
CfgHandler_Release,
CfgEnvCompleted_Invoke
};
static HRESULT STDMETHODCALLTYPE CfgCtrlCompleted_Invoke(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler *This,
HRESULT result, ICoreWebView2Controller *controller) {
(void)This;
if (FAILED(result) || !controller) return result;
g_cfgController = controller;
controller->lpVtbl->AddRef(controller);
RECT bounds;
GetClientRect(g_cfgHwnd, &bounds);
controller->lpVtbl->put_Bounds(controller, bounds);
controller->lpVtbl->put_IsVisible(controller, TRUE);
ICoreWebView2 *webview = NULL;
controller->lpVtbl->get_CoreWebView2(controller, &webview);
if (!webview) return E_FAIL;
g_cfgWebView = webview;
ICoreWebView2Settings *settings = NULL;
webview->lpVtbl->get_Settings(webview, &settings);
if (settings) {
settings->lpVtbl->put_AreDefaultContextMenusEnabled(settings, FALSE);
settings->lpVtbl->put_AreDevToolsEnabled(settings, FALSE);
settings->lpVtbl->put_IsStatusBarEnabled(settings, FALSE);
settings->lpVtbl->put_IsZoomControlEnabled(settings, FALSE);
settings->lpVtbl->Release(settings);
}
// Register message handler
static ICoreWebView2WebMessageReceivedEventHandlerVtbl msgVtbl = {0};
static BOOL msgInit = FALSE;
if (!msgInit) {
msgVtbl.QueryInterface = (HRESULT (STDMETHODCALLTYPE*)(ICoreWebView2WebMessageReceivedEventHandler*, REFIID, void**))CfgHandler_QueryInterface;
msgVtbl.AddRef = (ULONG (STDMETHODCALLTYPE*)(ICoreWebView2WebMessageReceivedEventHandler*))CfgHandler_AddRef;
msgVtbl.Release = (ULONG (STDMETHODCALLTYPE*)(ICoreWebView2WebMessageReceivedEventHandler*))CfgHandler_Release;
msgVtbl.Invoke = CfgMsgReceived_Invoke;
msgInit = TRUE;
}
CfgHandler *msgHandler = (CfgHandler*)malloc(sizeof(CfgHandler));
msgHandler->lpVtbl = &msgVtbl;
msgHandler->refCount = 1;
EventRegistrationToken token;
webview->lpVtbl->add_WebMessageReceived(webview, (ICoreWebView2WebMessageReceivedEventHandler*)msgHandler, &token);
((ICoreWebView2WebMessageReceivedEventHandler*)msgHandler)->lpVtbl->Release(
(ICoreWebView2WebMessageReceivedEventHandler*)msgHandler);
// Load embedded HTML from resources
HRSRC hRes = FindResource(NULL, MAKEINTRESOURCE(IDR_HTML_UI), RT_RCDATA);
if (hRes) {
HGLOBAL hData = LoadResource(NULL, hRes);
if (hData) {
DWORD htmlSize = SizeofResource(NULL, hRes);
const char *htmlUtf8 = (const char *)LockResource(hData);
if (htmlUtf8 && htmlSize > 0) {
int wLen = MultiByteToWideChar(CP_UTF8, 0, htmlUtf8, (int)htmlSize, NULL, 0);
wchar_t *wHtml = malloc((wLen + 1) * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, htmlUtf8, (int)htmlSize, wHtml, wLen);
wHtml[wLen] = L'\0';
webview->lpVtbl->NavigateToString(webview, wHtml);
free(wHtml);
}
}
}
return S_OK;
}
static HRESULT STDMETHODCALLTYPE CfgMsgReceived_Invoke(
ICoreWebView2WebMessageReceivedEventHandler *This,
ICoreWebView2 *sender,
ICoreWebView2WebMessageReceivedEventArgs *args) {
(void)This; (void)sender;
LPWSTR wMsg = NULL;
args->lpVtbl->TryGetWebMessageAsString(args, &wMsg);
if (!wMsg) return S_OK;
int len = WideCharToMultiByte(CP_UTF8, 0, wMsg, -1, NULL, 0, NULL, NULL);
char *msg = malloc(len);
WideCharToMultiByte(CP_UTF8, 0, wMsg, -1, msg, len, NULL, NULL);
CoTaskMemFree(wMsg);
char action[64] = {0};
json_get_string(msg, "action", action, sizeof(action));
if (strcmp(action, "getInit") == 0) {
webview_push_init_config();
} else if (strcmp(action, "saveSettings") == 0) {
char url[4096] = {0}, title[512] = {0}, hideJs[8192] = {0}, showJs[8192] = {0};
json_get_string(msg, "url", url, sizeof(url));
json_get_string(msg, "windowTitle", title, sizeof(title));
json_get_string(msg, "onHideJs", hideJs, sizeof(hideJs));
json_get_string(msg, "onShowJs", showJs, sizeof(showJs));
MultiByteToWideChar(CP_UTF8, 0, url, -1, g_config.url, 2048);
MultiByteToWideChar(CP_UTF8, 0, title, -1, g_config.windowTitle, 256);
MultiByteToWideChar(CP_UTF8, 0, hideJs, -1, g_config.onHideJs, 4096);
MultiByteToWideChar(CP_UTF8, 0, showJs, -1, g_config.onShowJs, 4096);
SaveConfigToRegistry(&g_config);
MarkAsConfigured();
ApplyConfiguration();
g_cfgSaved = TRUE;
PostMessage(g_cfgHwnd, WM_CLOSE, 0, 0);
} else if (strcmp(action, "close") == 0) {
PostMessage(g_cfgHwnd, WM_CLOSE, 0, 0);
} else if (strcmp(action, "resize") == 0) {
char hStr[32] = {0};
json_get_string(msg, "height", hStr, sizeof(hStr));
int contentHeight = atoi(hStr);
if (contentHeight <= 0) {
// Try parsing as bare number (not quoted)
const char *hp = strstr(msg, "\"height\"");
if (hp) {
hp += 8;
while (*hp == ' ' || *hp == ':') hp++;
contentHeight = atoi(hp);
}
}
if (contentHeight > 0 && g_cfgHwnd) {
RECT clientRect = {0}, windowRect = {0};
GetClientRect(g_cfgHwnd, &clientRect);
GetWindowRect(g_cfgHwnd, &windowRect);
int chromeH = (windowRect.bottom - windowRect.top) - (clientRect.bottom - clientRect.top);
int newWindowH = contentHeight + chromeH;
int windowW = windowRect.right - windowRect.left;
UINT flags = SWP_NOMOVE | SWP_NOZORDER;
if (g_cfgWindowShown) {
flags |= SWP_NOACTIVATE;
} else {
flags |= SWP_SHOWWINDOW;
KillTimer(g_cfgHwnd, ID_TIMER_CFG_SHOW_FALLBACK);
}
SetWindowPos(g_cfgHwnd, NULL, 0, 0, windowW, newWindowH, flags);
g_cfgWindowShown = TRUE;
cfg_sync_controller_bounds();
}
}
free(msg);
return S_OK;
}
// Config dialog window procedure
static LRESULT CALLBACK CfgWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_SIZE:
cfg_sync_controller_bounds();
return 0;
case WM_TIMER:
if (wParam == ID_TIMER_CFG_SHOW_FALLBACK) {
KillTimer(hwnd, ID_TIMER_CFG_SHOW_FALLBACK);
if (!g_cfgWindowShown) {
ShowWindow(hwnd, SW_SHOWNOACTIVATE);
UpdateWindow(hwnd);
g_cfgWindowShown = TRUE;
cfg_sync_controller_bounds();
}
return 0;
}
break;
case WM_CLOSE:
g_cfgWindowShown = FALSE;
KillTimer(hwnd, ID_TIMER_CFG_SHOW_FALLBACK);
if (g_cfgController) {
g_cfgController->lpVtbl->Close(g_cfgController);
g_cfgController->lpVtbl->Release(g_cfgController);
g_cfgController = NULL;
}
if (g_cfgWebView) {
g_cfgWebView->lpVtbl->Release(g_cfgWebView);
g_cfgWebView = NULL;
}
if (g_cfgEnv) {
g_cfgEnv->lpVtbl->Release(g_cfgEnv);
g_cfgEnv = NULL;
}
DestroyWindow(hwnd);
return 0;
case WM_DESTROY:
g_cfgHwnd = NULL;
g_cfgWindowShown = FALSE;
KillTimer(hwnd, ID_TIMER_CFG_SHOW_FALLBACK);
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
static void ShowConfigWebViewDialog(void) {
if (g_cfgHwnd != NULL) {
SetForegroundWindow(g_cfgHwnd);
return;
}
if (!fnCreateEnvironment && !load_webview2_loader()) {
MessageBoxW(NULL,
L"Failed to load WebView2.\n\n"
L"Please ensure the Microsoft Edge WebView2 Runtime is installed.\n"
L"Download from: https://developer.microsoft.com/en-us/microsoft-edge/webview2/",
L"SystrayLauncher", MB_ICONERROR | MB_OK);
return;
}
// Register window class (once)
static BOOL classRegistered = FALSE;
if (!classRegistered) {
WNDCLASSEXW wc = {0};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = CfgWndProc;
wc.hInstance = g_hInstance;
wc.hIcon = LoadIconW(g_hInstance, MAKEINTRESOURCEW(IDI_TRAYICON));
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = L"SystrayLauncherCfgWnd";
wc.hIconSm = LoadIconW(g_hInstance, MAKEINTRESOURCEW(IDI_TRAYICON));
RegisterClassExW(&wc);
classRegistered = TRUE;
}
int screenW = GetSystemMetrics(SM_CXSCREEN);
int screenH = GetSystemMetrics(SM_CYSCREEN);
int width = 480, height = 380;
int posX = (screenW - width) / 2;
int posY = (screenH - height) / 2;
g_cfgHwnd = CreateWindowExW(0, L"SystrayLauncherCfgWnd", L"Configuration",
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
posX, posY, width, height,
NULL, NULL, g_hInstance, NULL);
if (!g_cfgHwnd) return;
g_cfgWindowShown = FALSE;
SetTimer(g_cfgHwnd, ID_TIMER_CFG_SHOW_FALLBACK, CFG_SHOW_FALLBACK_DELAY_MS, NULL);
// Build user data folder path
WCHAR userDataFolder[MAX_PATH];
DWORD tempLen = GetTempPathW(MAX_PATH, userDataFolder);
if (tempLen > 0 && tempLen < MAX_PATH - 30) {
wcscat(userDataFolder, L"SystrayLauncher.WebView2");
} else {
wcscpy(userDataFolder, L"");
}
CfgHandler *envHandler = (CfgHandler*)malloc(sizeof(CfgHandler));
envHandler->lpVtbl = &g_cfgEnvVtbl;
envHandler->refCount = 1;
HRESULT hr = fnCreateEnvironment(NULL, userDataFolder[0] ? userDataFolder : NULL, NULL,
(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*)envHandler);
((ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*)envHandler)->lpVtbl->Release(
(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*)envHandler);
if (FAILED(hr)) {
MessageBoxW(NULL,
L"Failed to initialize WebView2.\n\n"
L"Please ensure the Microsoft Edge WebView2 Runtime is installed.",
L"SystrayLauncher", MB_ICONERROR | MB_OK);
DestroyWindow(g_cfgHwnd);
g_cfgHwnd = NULL;
}
}
// Function to enable spell checking via settings
void SetSpellCheckLanguages(ICoreWebView2* webview, const wchar_t* languages) {
if (!webview || !languages) return;
// Get settings
ICoreWebView2Settings* settings = NULL;
HRESULT hr = webview->lpVtbl->get_Settings(webview, &settings);
if (SUCCEEDED(hr) && settings) {
// Enable context menus (required for spell check suggestions to appear)
hr = settings->lpVtbl->put_AreDefaultContextMenusEnabled(settings, TRUE);
if (SUCCEEDED(hr)) {
DebugPrint(L"[INFO] Context menus enabled for spell checking\n");
} else {
DebugPrint(L"[WARNING] Failed to enable context menus. HRESULT: 0x%08X\n", hr);
}
DebugPrint(L"[INFO] Spell check will use languages configured in Edge (edge://settings/languages)\n");
DebugPrint(L"[INFO] Configured languages: %s\n", languages);
settings->lpVtbl->Release(settings);
} else {
DebugPrint(L"[WARNING] Failed to get WebView2 settings. HRESULT: 0x%08X\n", hr);
}
}
// WebView2 Handler Implementations
HRESULT STDMETHODCALLTYPE EnvCompletedHandler_QueryInterface(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* This,
REFIID riid, void** ppvObject) {
if (IsEqualIID(riid, &IID_IUnknown) ||
IsEqualIID(riid, &IID_ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler)) {
*ppvObject = This;
This->lpVtbl->AddRef(This);
return S_OK;
}
*ppvObject = NULL;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE EnvCompletedHandler_AddRef(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* This) {
EnvCompletedHandler* handler = (EnvCompletedHandler*)This;
return InterlockedIncrement(&handler->refCount);
}
ULONG STDMETHODCALLTYPE EnvCompletedHandler_Release(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* This) {
EnvCompletedHandler* handler = (EnvCompletedHandler*)This;
ULONG refCount = InterlockedDecrement(&handler->refCount);
if (refCount == 0) {
free(handler->userDataPath);
free(handler);
}
return refCount;
}
HRESULT STDMETHODCALLTYPE EnvCompletedHandler_Invoke(
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* This,
HRESULT result, ICoreWebView2Environment* environment) {
if (FAILED(result)) {
MessageBoxW(NULL, L"WebView2 environment creation failed", L"Error", MB_OK | MB_ICONERROR);
return result;
}
// Get WebView2 browser version string
LPWSTR versionString = NULL;
if (SUCCEEDED(environment->lpVtbl->get_BrowserVersionString(environment, &versionString)) && versionString) {
wcscpy_s(g_webView2Version, 128, versionString);
CoTaskMemFree(versionString);
}
EnvCompletedHandler* handler = (EnvCompletedHandler*)This;
HWND hwnd = handler->hwnd;
ControllerCompletedHandler* controllerHandler = (ControllerCompletedHandler*)calloc(1, sizeof(ControllerCompletedHandler));
if (!controllerHandler) return E_OUTOFMEMORY;
static ICoreWebView2CreateCoreWebView2ControllerCompletedHandlerVtbl controllerVtbl = {
ControllerCompletedHandler_QueryInterface,
ControllerCompletedHandler_AddRef,
ControllerCompletedHandler_Release,
ControllerCompletedHandler_Invoke
};
controllerHandler->lpVtbl = &controllerVtbl;
controllerHandler->refCount = 1;
controllerHandler->hwnd = hwnd;
environment->lpVtbl->CreateCoreWebView2Controller(environment, hwnd,
(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*)controllerHandler);
controllerHandler->lpVtbl->Release((ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*)controllerHandler);
return S_OK;
}
HRESULT STDMETHODCALLTYPE ControllerCompletedHandler_QueryInterface(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler* This,
REFIID riid, void** ppvObject) {
if (IsEqualIID(riid, &IID_IUnknown) ||
IsEqualIID(riid, &IID_ICoreWebView2CreateCoreWebView2ControllerCompletedHandler)) {
*ppvObject = This;
This->lpVtbl->AddRef(This);
return S_OK;
}
*ppvObject = NULL;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE ControllerCompletedHandler_AddRef(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler* This) {
ControllerCompletedHandler* handler = (ControllerCompletedHandler*)This;
return InterlockedIncrement(&handler->refCount);
}
ULONG STDMETHODCALLTYPE ControllerCompletedHandler_Release(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler* This) {
ControllerCompletedHandler* handler = (ControllerCompletedHandler*)This;
ULONG refCount = InterlockedDecrement(&handler->refCount);
if (refCount == 0) {
free(handler);
}
return refCount;
}
HRESULT STDMETHODCALLTYPE ControllerCompletedHandler_Invoke(
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler* This,
HRESULT result, ICoreWebView2Controller* controller) {
if (FAILED(result)) {
MessageBoxW(NULL, L"WebView2 controller creation failed", L"Error", MB_OK | MB_ICONERROR);
return result;
}