-
Notifications
You must be signed in to change notification settings - Fork 0
/
toggle.c
1343 lines (1192 loc) · 39.3 KB
/
toggle.c
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
// Toggle Dark/Light Mode -- icon in the taskbar notification area
// Dan Jackson, 2021-2024.
#define _WIN32_WINNT 0x0601
#define _CRT_SECURE_NO_WARNINGS // TODO: Use more secure versions
#include <windows.h>
#include <tchar.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <stdbool.h>
#include <time.h>
#include <io.h>
#include <rpc.h>
#include <dbt.h>
// commctrl v6 for LoadIconMetric()
#include <commctrl.h>
// Notify icons
#include <shellapi.h>
// Internet (update check)
#include <WinInet.h>
// MSC-Specific Pragmas
#ifdef _MSC_VER
// Moved to external .manifest file linked through .rc file
//#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#pragma comment(lib, "comctl32.lib") // InitCommonControlsEx(), LoadIconMetric()
#pragma comment(lib, "shell32.lib") // Shell_NotifyIcon()
#pragma comment(lib, "advapi32.lib") // RegOpenKeyEx(), RegSetValueEx(), RegGetValue(), RegDeleteValue(), RegCloseKey()
#pragma comment(lib, "Comdlg32.lib") // GetSaveFileName()
#pragma comment(lib, "Version.lib") // GetFileVersionInfoSize(), GetFileVersionInfo(), VerQueryValue()
#pragma comment(lib, "gdi32.lib") // CreateFontIndirect()
#pragma comment(lib, "User32.lib") // Windows
#pragma comment(lib, "ole32.lib") // CoInitialize(), etc.
#pragma comment (lib, "wininet.lib") // WinInet functions: InternetOpenW / InternetConnectW / HttpOpenRequestW / HttpSendRequestW / InternetReadFile / InternetCloseHandle
// #pragma comment(lib, "psapi.lib") // GetModuleFileName() // -lpsapi
#endif
// Defines
#define COPYRIGHT_NAME "Daniel Jackson"
#define COPYRIGHT_YEAR "2021-2024"
#define TITLE TEXT("Toggle Dark/Light Mode")
#define TITLE_SAFE TEXT("Toggle Dark-Light Mode")
#define USER_AGENT_BASE TEXT("toggle-dark-light")
#define UPDATE_URL TEXT("https://api.github.com/repos/danielgjackson/toggle-dark-light/releases?per_page=1")
#define RELEASES_URL TEXT("https://github.com/danielgjackson/toggle-dark-light/releases/latest")
#define HOT_KEY_ID 0x0000
#define WMAPP_NOTIFYCALLBACK (WM_APP + 1)
#define IDM_TOGGLE 101
#define IDM_AUTOSTART 102
#define IDM_DEBUG 103
#define IDM_ABOUT 104
#define IDM_EXIT 105
// Hacky global state
HINSTANCE ghInstance = NULL;
HWND ghWndMain = NULL;
UINT idMinimizeIcon = 1;
BOOL gbHasNotifyIcon = FALSE;
BOOL gbAutoStart = FALSE;
BOOL gbNotify = TRUE;
BOOL gbPortable = FALSE;
BOOL gbAllowDuplicate = FALSE;
BOOL gbSubsystemWindows = FALSE;
BOOL gbHasConsole = FALSE;
BOOL gbImmediatelyExit = FALSE; // Quit right away (mainly for testing)
BOOL gbSetDark = FALSE;
BOOL gbSetLight = FALSE;
BOOL gbQuery = FALSE;
BOOL gbExiting = FALSE;
HANDLE ghStartEvent = NULL; // Event for single instance
TCHAR gUserAgent[128] = USER_AGENT_BASE;
int gVersion[4] = { 0, 0, 0, 0 };
NOTIFYICONDATA nid = {0};
// Redirect standard I/O to a console
static BOOL RedirectIOToConsole(BOOL tryAttach, BOOL createIfRequired)
{
BOOL hasConsole = FALSE;
if (tryAttach && AttachConsole(ATTACH_PARENT_PROCESS))
{
hasConsole = TRUE;
}
if (createIfRequired && !hasConsole)
{
AllocConsole();
AttachConsole(GetCurrentProcessId());
hasConsole = TRUE;
}
if (hasConsole)
{
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
return hasConsole;
}
int HttpGet(const TCHAR *url, const TCHAR *headers, char **response, size_t *responseSize)
{
// Initialize WinInet
HINTERNET hInternet = InternetOpen(gUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (hInternet == NULL)
{
_ftprintf(stderr, TEXT("GET: InternetOpen() failed (%d)\n"), GetLastError());
return -1;
}
// Open the URL
HINTERNET hResource = InternetOpenUrl(hInternet, url, headers, (DWORD)-1, INTERNET_FLAG_NO_UI | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)NULL);
if (hResource == NULL)
{
_ftprintf(stderr, TEXT("GET: InternetOpenUrl() failed (%d)\n"), GetLastError());
InternetCloseHandle(hInternet);
return -1;
}
// Read response
char *buffer = NULL;
size_t bufferSize = 0, bufferCapacity = 0;
DWORD bytesRead;
do
{
const size_t chunkSize = 4096;
if (bufferSize + chunkSize > bufferCapacity) {
bufferCapacity += chunkSize;
buffer = (char *)realloc(buffer, bufferCapacity + 1); // null terminated for easier handling of string responses
if (buffer == NULL)
{
_ftprintf(stderr, TEXT("GET: Memory allocation failed\n"));
InternetCloseHandle(hResource);
InternetCloseHandle(hInternet);
return -1;
}
}
bytesRead = 0;
if (!InternetReadFile(hResource, (LPVOID)(buffer + bufferSize), bufferCapacity - bufferSize, &bytesRead))
{
_ftprintf(stderr, TEXT("GET: InternetReadFile() failed (%d)\n"), GetLastError());
free(buffer);
InternetCloseHandle(hResource);
InternetCloseHandle(hInternet);
return -1;
}
bufferSize += bytesRead;
} while (bytesRead > 0);
buffer[bufferSize] = '\0';
//_ftprintf(stderr, TEXT("GET: InternetReadFile() total read: %u\n"), (unsigned int)bufferSize);
// Clean up
InternetCloseHandle(hResource);
InternetCloseHandle(hInternet);
// Assign return values
if (response)
{
*response = buffer;
} else {
free(buffer);
}
if (responseSize)
{
*responseSize = bufferSize;
}
return 0;
}
bool FindOnlineVersion(char *version, size_t versionSize)
{
sprintf(version, "");
// Check for updates
const TCHAR *url = UPDATE_URL;
const TCHAR *headers = NULL; // TEXT("Accept: application/json");
char *response = NULL;
size_t responseSize = 0;
int result = HttpGet(url, headers, &response, &responseSize);
if (result < 0)
{
_ftprintf(stderr, TEXT("FindOnlineVersion() failed: %d\n"), result);
return false;
}
if (responseSize < 2 || response[0] != '[' || response[1] != '{')
{
_ftprintf(stderr, TEXT("FindOnlineVersion() failed: unexpected response\n"));
free(response);
return false;
}
// Dump response
//_ftprintf(stderr, TEXT("---\n%S\n---\n"), response);
// Hackily Locate tag_name ("tag_name":"1.0.##")
const char *prefix = "\"tag_name\":\"";
const char *suffix = "\"";
bool located = false;
char *tagStart = strstr(response, prefix);
if (tagStart)
{
tagStart += strlen(prefix);
char *tagEnd = strstr(tagStart, suffix);
if (tagEnd)
{
// Copy version string
size_t tagLength = tagEnd - tagStart;
if (tagLength < versionSize - 1)
{
memcpy(version, tagStart, tagLength);
version[tagLength] = '\0';
located = true;
}
}
}
if (!located)
{
_ftprintf(stderr, TEXT("FindOnlineVersion() failed: tag_name not found in response\n"));
free(response);
return false;
}
//_ftprintf(stderr, TEXT("FindOnlineVersion() found version: %s\n"), version);
return true;
}
const char *CheckForUpdatedVersion() {
char currentVersion[32] = {0};
sprintf(currentVersion, "%u.%u.%u", (unsigned int)gVersion[0], (unsigned int)gVersion[1], (unsigned int)gVersion[2]);
_ftprintf(stderr, TEXT("UPDATE: Inline version update check... (current=%S)\n"), currentVersion);
// Caution: static buffer
static char onlineVersion[32] = {0};
if (!FindOnlineVersion(onlineVersion, sizeof(onlineVersion) / sizeof(onlineVersion[0])))
{
_ftprintf(stderr, TEXT("UPDATE: Online version check failed.\n"));
return NULL;
}
else
{
_ftprintf(stderr, TEXT("UPDATE: Online version: %S\n"), onlineVersion);
if (strcmp(currentVersion, onlineVersion) != 0)
{
_ftprintf(stderr, TEXT("UPDATE: A newer version is available online.\n"));
return onlineVersion;
}
else
{
// Online version is the same as the current version
sprintf(onlineVersion, "");
return onlineVersion;
}
}
return NULL;
}
/*
TODO: Check for updates: only in non-portable mode, at start-up, if auto-update enabled,
if "last fetch attempt" time (from registry) is at least one day ago, store "last fetch attempt" time and
spawn thread to attempt to fetch `https://api.github.com/repos/danielgjackson/toggle-dark-light/releases?per_page=1`,
take online version as `[0].tag_name`. If successfully parsed online version, if different to "last prompted version"
(from registry) and different to current software version information then prompt user with new version number and to
visit releases page, and store as "last prompted version".
*/
// (From About dialog) Immediately check the online version, and prompt the user as necessary.
void QueryUpdate()
{
char currentVersion[32] = {0};
sprintf(currentVersion, "%u.%u.%u", (unsigned int)gVersion[0], (unsigned int)gVersion[1], (unsigned int)gVersion[2]);
// Caution: blocking online check for new version
HCURSOR hPreviousCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
const char *updatedVersion = CheckForUpdatedVersion();
SetCursor(hPreviousCursor);
if (updatedVersion != NULL && updatedVersion[0] == '\0')
{
MessageBox(NULL, TEXT("You are using the latest version."), TEXT("Updates"), MB_OK | MB_ICONINFORMATION);
}
else if (updatedVersion == NULL)
{
int result = MessageBox(NULL, TEXT("Unable to check for updates - visit the releases page?"), TEXT("Updates"), MB_OKCANCEL | MB_ICONERROR);
if (result == IDOK)
{
ShellExecute(ghWndMain, TEXT("open"), RELEASES_URL, NULL, NULL, SW_SHOW);
}
}
else
{
TCHAR szMessage[256] = TEXT("");
_sntprintf(szMessage, sizeof(szMessage) / sizeof(szMessage[0]), TEXT("You are on version %S, but a different version is available online: %S\nVisit the releases page?"), currentVersion, updatedVersion);
int result = MessageBox(NULL, szMessage, TEXT("Updates"), MB_OKCANCEL | MB_ICONINFORMATION);
if (result == IDOK)
{
ShellExecute(ghWndMain, TEXT("open"), RELEASES_URL, NULL, NULL, SW_SHOW);
}
}
}
void DeleteNotificationIcon(void)
{
if (gbHasNotifyIcon)
{
nid.uFlags = 0;
memset(&nid.guidItem, 0, sizeof(nid.guidItem));
nid.uID = idMinimizeIcon;
Shell_NotifyIcon(NIM_DELETE, &nid);
gbHasNotifyIcon = FALSE;
}
}
BOOL AddNotificationIcon(HWND hwnd)
{
DeleteNotificationIcon();
memset(&nid, 0, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = hwnd;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP;
nid.uFlags |= NIS_HIDDEN;
nid.dwStateMask = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP;
if (gbNotify)
{
nid.uFlags |= NIF_INFO | NIF_REALTIME;
_tcscpy(nid.szInfoTitle, TITLE);
_tcscpy(nid.szInfo, TEXT("Running in notification area."));
nid.dwInfoFlags = NIIF_INFO | NIIF_NOSOUND;
nid.hBalloonIcon = LoadIcon(ghInstance, TEXT("MAINICON"));
nid.dwInfoFlags |= NIIF_LARGE_ICON | NIIF_USER;
}
memset(&nid.guidItem, 0, sizeof(nid.guidItem));
nid.uID = idMinimizeIcon;
nid.uCallbackMessage = WMAPP_NOTIFYCALLBACK;
nid.hIcon = NULL;
LoadIconMetric(ghInstance, L"MAINICON", LIM_SMALL, &nid.hIcon); // MAKEINTRESOURCE(IDI_APPLICATION)
_tcscpy(nid.szTip, TITLE);
Shell_NotifyIcon(NIM_ADD, &nid);
nid.uVersion = NOTIFYICON_VERSION_4;
Shell_NotifyIcon(NIM_SETVERSION, &nid);
gbHasNotifyIcon = TRUE;
return gbHasNotifyIcon;
}
BOOL Notify(TCHAR *message)
{
if (!gbHasNotifyIcon) return FALSE;
nid.uFlags |= NIF_INFO | NIF_REALTIME;
_tcscpy(nid.szInfoTitle, TITLE);
_tcscpy(nid.szInfo, message);
nid.dwInfoFlags = NIIF_INFO | NIIF_NOSOUND;
nid.hBalloonIcon = LoadIcon(ghInstance, TEXT("MAINICON"));
nid.dwInfoFlags |= NIIF_LARGE_ICON | NIIF_USER;
Shell_NotifyIcon(NIM_MODIFY, &nid);
return TRUE;
}
bool AutoStart(bool change, bool startup)
{
bool retVal = false;
HKEY hKeyMain = HKEY_CURRENT_USER;
TCHAR *subKey = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
TCHAR *value = TITLE_SAFE;
TCHAR szModuleFileName[MAX_PATH];
GetModuleFileName(NULL, szModuleFileName, sizeof(szModuleFileName) / sizeof(szModuleFileName[0]));
TCHAR szQuotedFileName[MAX_PATH + 2];
_sntprintf(szQuotedFileName, sizeof(szQuotedFileName) / sizeof(szQuotedFileName[0]), TEXT("\"%Ts\""), szModuleFileName);
TCHAR szAutoStartValue[MAX_PATH + 32];
_sntprintf(szAutoStartValue, sizeof(szAutoStartValue) / sizeof(szAutoStartValue[0]), TEXT("%Ts /AUTOSTART"), szQuotedFileName);
if (change)
{
// Set the key
HKEY hKey = NULL;
LSTATUS lErrorCode = RegOpenKeyEx(hKeyMain, subKey, 0, KEY_SET_VALUE, &hKey);
if (lErrorCode == ERROR_SUCCESS)
{
if (startup)
{
// Setting to auto-start
lErrorCode = RegSetValueEx(hKey, value, 0, REG_SZ, (const BYTE *)szAutoStartValue, (DWORD)((_tcslen(szAutoStartValue) + 1) * sizeof(TCHAR)));
if (lErrorCode == ERROR_SUCCESS)
{
retVal = true;
}
}
else
{
// Setting to not auto-start
lErrorCode = RegDeleteValue(hKey, value);
if (lErrorCode == ERROR_SUCCESS)
{
retVal = true;
}
}
RegCloseKey(hKey);
}
}
else
{
// Query that the key is set and has the correct value prefix
TCHAR szData[MAX_PATH];
DWORD cbData = sizeof(szData);
LSTATUS lErrorCode = RegGetValue(hKeyMain, subKey, value, RRF_RT_REG_SZ, NULL, &szData, &cbData);
if (lErrorCode == ERROR_SUCCESS && _tcsncmp(szData, szQuotedFileName, _tcslen(szQuotedFileName)) == 0) {
retVal = true;
}
}
return retVal;
}
void ShowContextMenu(HWND hwnd, POINT pt)
{
UINT autoStartFlags;
// Don't touch the registry if running as a portable app
if (!gbPortable) {
autoStartFlags = AutoStart(false, false) ? MF_CHECKED : MF_UNCHECKED;
} else {
autoStartFlags = MF_UNCHECKED | MF_GRAYED;
}
HMENU hMenu = CreatePopupMenu();
AppendMenu(hMenu, MF_STRING, IDM_TOGGLE, TEXT("&Toggle Dark/Light Mode\tWin+Shift+D"));
AppendMenu(hMenu, MF_SEPARATOR, 0, TEXT("Separator"));
AppendMenu(hMenu, MF_STRING | autoStartFlags, IDM_AUTOSTART, TEXT("Auto-&Start"));
AppendMenu(hMenu, MF_STRING, IDM_DEBUG, TEXT("Save &Debug Info..."));
AppendMenu(hMenu, MF_STRING, IDM_ABOUT, TEXT("&About"));
AppendMenu(hMenu, MF_SEPARATOR, 0, TEXT("Separator"));
AppendMenu(hMenu, MF_STRING, IDM_EXIT, TEXT("E&xit"));
SetMenuDefaultItem(hMenu, IDM_TOGGLE, FALSE);
SetForegroundWindow(hwnd);
UINT uFlags = TPM_RIGHTBUTTON;
if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0)
{
uFlags |= TPM_RIGHTALIGN;
}
else
{
uFlags |= TPM_LEFTALIGN;
}
SetForegroundWindow(hwnd); // for correct popup tracking
TrackPopupMenuEx(hMenu, uFlags, pt.x, pt.y, hwnd, NULL);
DestroyMenu(hMenu);
}
BOOL HasExistingInstance(void)
{
if (ghStartEvent)
{
CloseHandle(ghStartEvent);
ghStartEvent = NULL;
}
ghStartEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("Local\\toggle")); // Session namespace is ok (does not need to be Global)
DWORD lastError = GetLastError();
if (ghStartEvent && !lastError)
{
// We are the first instance (hold on to the event, it will only be released when the process ends)
_ftprintf(stderr, TEXT("INSTANCE: No other instance found.\n"));
return FALSE;
}
else if (ghStartEvent && lastError == ERROR_ALREADY_EXISTS)
{
// There is another instance running
_ftprintf(stderr, TEXT("INSTANCE: Another instance found.\n"));
//CloseHandle(ghStartEvent);
//ghStartEvent = NULL;
return TRUE;
}
else
{
// Otherwise, fail safe and assume not already running
_ftprintf(stderr, TEXT("INSTANCE: Problem finding instance.\n"));
return FALSE;
}
}
HFONT hDlgFont = NULL;
bool windowOpen = false;
void PositionWindow(int x, int y)
{
RECT rect = {0};
GetWindowRect(ghWndMain, &rect);
SIZE windowSize;
windowSize.cx = rect.right - rect.left;
windowSize.cy = rect.bottom - rect.top;
// Fallback to (0,0)
RECT rectSpace = {0};
// Prefer desktop window
GetWindowRect(GetDesktopWindow(), &rectSpace);
// Prefer the work area
SystemParametersInfo(SPI_GETWORKAREA, 0, &rectSpace, 0);
// Default to the lower-right corner
rect.left = 0;
rect.top = 0;
if (rectSpace.right - rectSpace.left > 0) rect.left = rectSpace.right - windowSize.cx;
if (rectSpace.bottom - rectSpace.top > 0) rect.top = rectSpace.bottom - windowSize.cy;
rect.top = rectSpace.bottom - windowSize.cy;
rect.right = rect.left + windowSize.cx;
rect.bottom = rect.top + windowSize.cy;
// Prefer a calculated position
POINT anchorPoint;
anchorPoint.x = x;
anchorPoint.y = y;
CalculatePopupWindowPosition(&anchorPoint, &windowSize, TPM_CENTERALIGN | TPM_BOTTOMALIGN | TPM_VERTICAL | TPM_WORKAREA, NULL, &rect);
AdjustWindowRect(&rect, GetWindowLong(ghWndMain, GWL_STYLE), FALSE);
SetWindowPos(ghWndMain, 0, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOACTIVATE);
}
void OpenWindow(int x, int y)
{
// PositionWindow(x, y);
// ShowWindow(ghWndMain, SW_SHOW);
// SetForegroundWindow(ghWndMain);
// windowOpen = true;
}
void HideWindow(void)
{
ShowWindow(ghWndMain, SW_HIDE);
windowOpen = false;
}
void StartExit(void)
{
gbExiting = TRUE;
if (ghStartEvent)
{
CloseHandle(ghStartEvent);
ghStartEvent = NULL;
}
PostMessage(ghWndMain, WM_CLOSE, 0, 0);
}
void Startup(HWND hWnd)
{
_tprintf(TEXT("Startup...\n"));
ghWndMain = hWnd;
BOOL duplicateInstance = FALSE;
int response = 0;
if (!gbAllowDuplicate)
{
do
{
if (gbImmediatelyExit) break; // Allow duplicates if immediately exiting
duplicateInstance = HasExistingInstance();
if (!duplicateInstance) break;
response = MessageBox(NULL, TEXT("Toggle Dark/Light Mode is already running in the notification area.\r\nContinue with a new instance?"), TITLE, MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON1);
if (response == IDCANCEL)
{
gbNotify = FALSE;
gbImmediatelyExit = TRUE;
}
if (response == IDCONTINUE)
{
gbAllowDuplicate = TRUE;
break;
}
} while (response == IDTRYAGAIN || response == IDCONTINUE);
}
if (response != IDCANCEL)
{
if (!gbImmediatelyExit)
{
AddNotificationIcon(ghWndMain);
}
}
if (gbImmediatelyExit) StartExit();
}
void Shutdown(void)
{
_tprintf(TEXT("Shutdown()...\n"));
DeleteNotificationIcon();
_tprintf(TEXT("...END: Shutdown()\n"));
}
int IsLight(void)
{
HKEY hKeyMain = HKEY_CURRENT_USER;
const TCHAR *subKey = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize");
const TCHAR *value = TEXT("SystemUsesLightTheme");
DWORD dwData = (DWORD)-1;
HKEY hKey = NULL;
LSTATUS lErrorCode = RegOpenKeyEx(hKeyMain, subKey, 0, KEY_NOTIFY, &hKey);
if (lErrorCode != ERROR_SUCCESS)
{
_tprintf(TEXT("ERROR: RegOpenKeyEx() failed (%d): %ls\n"), lErrorCode, subKey);
return -1;
}
// Query current value
DWORD dwFlags = RRF_RT_REG_DWORD;
DWORD cbData = sizeof(dwData);
lErrorCode = RegGetValue(hKeyMain, subKey, value, dwFlags, NULL, &dwData, &cbData);
RegCloseKey(hKey);
if (lErrorCode != ERROR_SUCCESS)
{
_tprintf(TEXT("ERROR: RegGetValue() failed (%d): %ls\n"), lErrorCode, subKey);
return (DWORD)-1;
}
if (dwData == 0 || dwData == 1) return dwData; // 1=light, 0=dark
return -1; // error
}
// Data for sending messages to specific windows
typedef struct {
UINT msg;
WPARAM wParam;
LPARAM lParam;
TCHAR *className;
TCHAR *classNameAlt;
UINT count;
} send_message_t;
BOOL CALLBACK SendEnumWindowsProc(HWND hWnd, LPARAM lParam)
{
send_message_t *msgData = (send_message_t *)lParam;
if (!hWnd) return TRUE;
// Filter by class name
if (msgData->className != NULL || msgData->classNameAlt != NULL)
{
TCHAR szClassName[256];
GetClassName(hWnd, szClassName, sizeof(szClassName) / sizeof(szClassName[0]));
BOOL match = false;
if (msgData->className != NULL && _tcscmp(szClassName, msgData->className) == 0) match = true;
if (msgData->classNameAlt != NULL && _tcscmp(szClassName, msgData->classNameAlt) == 0) match = true;
if (!match) return TRUE;
}
SendMessage(hWnd, msgData->msg, msgData->wParam, msgData->lParam);
//PostMessage(hWnd, msgData->msg, msgData->wParam, msgData->lParam);
msgData->count++;
return TRUE;
}
// Send a message just to non-primary display taskbars (which seem a bit troublesome...)
UINT SendToTaskbar(UINT msg, WPARAM wParam, LPARAM lParam)
{
send_message_t msgData = {0};
msgData.msg = msg;
msgData.wParam = wParam;
msgData.lParam = lParam;
msgData.className = (TCHAR *)&TEXT("Shell_TrayWnd");
msgData.classNameAlt = (TCHAR *)&TEXT("Shell_SecondaryTrayWnd");
msgData.count = 0;
BOOL result = EnumWindows(SendEnumWindowsProc, (LPARAM)&msgData);
if (!result) return 0;
return (UINT)msgData.count;
}
BOOL SetLightDark(DWORD light)
{
HKEY hKeyMain = HKEY_CURRENT_USER;
const TCHAR *subKey = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize");
const TCHAR *valueSystem = TEXT("SystemUsesLightTheme");
const TCHAR *valueApps = TEXT("AppsUseLightTheme");
const TCHAR *valueColorPrevalence = TEXT("ColorPrevalence");
HKEY hKey = NULL;
LSTATUS lErrorCode = RegOpenKeyEx(hKeyMain, subKey, 0, KEY_SET_VALUE, &hKey);
if (lErrorCode != ERROR_SUCCESS)
{
_tprintf(TEXT("ERROR: RegOpenKeyEx() failed (%d): %ls\n"), lErrorCode, subKey);
return FALSE;
}
// Set the system key
lErrorCode = RegSetValueEx(hKey, valueSystem, 0, REG_DWORD, (const BYTE *)&light, sizeof(light));
if (lErrorCode != ERROR_SUCCESS)
{
_tprintf(TEXT("ERROR: RegSetValueEx() failed (%d): %ls - %ls\n"), lErrorCode, subKey, valueSystem);
RegCloseKey(hKey);
return FALSE;
}
// Set the apps key
lErrorCode = RegSetValueEx(hKey, valueApps, 0, REG_DWORD, (const BYTE *)&light, sizeof(light));
if (lErrorCode != ERROR_SUCCESS)
{
_tprintf(TEXT("ERROR: RegSetValueEx() failed (%d): %ls - %ls\n"), lErrorCode, subKey, valueApps);
RegCloseKey(hKey);
return FALSE;
}
// Set the ColorPrevalence key
DWORD colorPrevalence = 0; // HACK: Force off for now as we don't know the previous state (TODO: Option to set this value in dark mode)
if (light) colorPrevalence = 0; // Always off in light mode?
lErrorCode = RegSetValueEx(hKey, valueColorPrevalence, 0, REG_DWORD, (const BYTE *)&colorPrevalence, sizeof(colorPrevalence));
if (lErrorCode != ERROR_SUCCESS)
{
_tprintf(TEXT("ERROR: RegSetValueEx() failed (%d): %ls - %ls\n"), lErrorCode, subKey, valueColorPrevalence);
RegCloseKey(hKey);
return FALSE;
}
RegCloseKey(hKey);
// Delay -- this may to help update taskbars on other displays?
//Sleep(500);
// Send WM_SETTINGCHANGE message directly to primary and secondary taskbars
UINT countSC = SendToTaskbar(WM_SETTINGCHANGE, 0, (LPARAM)TEXT("ImmersiveColorSet"));
_tprintf(TEXT("SendToTaskbar(WM_SETTINGCHANGE): %d\n"), countSC);
// Broadcast WM_SETTINGCHANGE using SendMessageTimeout with lParam set to "ImmersiveColorSet" -- required by some apps such as explorer.exe (File Explorer)
{
HWND hWnd = HWND_BROADCAST;
UINT msg = WM_SETTINGCHANGE;
WPARAM wParam = 0;
LPARAM lParam = (LPARAM)TEXT("ImmersiveColorSet");
SendMessageTimeout(hWnd, msg, wParam, lParam, SMTO_ABORTIFHUNG, 5000, NULL);
}
// Broadcast a second WM_SETTINGCHANGE using SendMessageTimeout with lParam set to "ImmersiveColorSet" -- this second broadcast fixes Task Manager
{
HWND hWnd = HWND_BROADCAST;
UINT msg = WM_SETTINGCHANGE;
WPARAM wParam = 0;
LPARAM lParam = (LPARAM)TEXT("ImmersiveColorSet");
SendMessageTimeout(hWnd, msg, wParam, lParam, SMTO_ABORTIFHUNG, 5000, NULL);
}
// // Broadcast WM_THEMECHANGED
// {
// HWND hWnd = HWND_BROADCAST;
// UINT msg = WM_THEMECHANGED;
// WPARAM wParam = 0;
// LPARAM lParam = 0;
// SendMessageTimeout(hWnd, msg, wParam, lParam, SMTO_ABORTIFHUNG, 5000, NULL);
// }
// // Broadcast WM_SYSCOLORCHANGE
// {
// HWND hWnd = HWND_BROADCAST;
// UINT msg = WM_SYSCOLORCHANGE;
// WPARAM wParam = 0;
// LPARAM lParam = 0;
// SendMessageTimeout(hWnd, msg, wParam, lParam, SMTO_ABORTIFHUNG, 5000, NULL);
// }
// WM_DWMCOMPOSITIONCHANGED
// TODO: If occasional File Explorer glitches remain, consider these:
// #include <shlobj.h>
// SHCNE_ASSOCCHANGED (SHCNF_IDLIST=0x00000000)
//SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
// SHCNE_ALLEVENTS
//SHChangeNotify(SHCNE_ALLEVENTS, 0, NULL, NULL);
// // Broadcast WM_PAINT
// {
// long res = BroadcastSystemMessageEx(BSF_POSTMESSAGE, NULL, WM_PAINT, 0, 0, NULL); // BSF_POSTMESSAGE / BSF_SENDNOTIFYMESSAGE
// if (res <= 0) {
// _tprintf(TEXT("ERROR: BroadcastSystemMessageEx() WM_PAINT failed (0x%x / 0x%x)\n"), res, GetLastError());
// }
// }
return TRUE;
}
void ToggleDarkLight(BOOL notify)
{
_tprintf(TEXT("ToggleDarkLight()...\n"));
int isLight = IsLight();
if (isLight == 0) // dark
{
_tprintf(TEXT("...isLight=FALSE, setting: light\n"));
if (notify) Notify(TEXT("Toggle to light mode."));
SetLightDark(1);
}
else if (isLight == 1) // light
{
_tprintf(TEXT("...isLight=TRUE, setting: dark\n"));
if (notify) Notify(TEXT("Toggle to dark mode."));
SetLightDark(0);
}
else
{
_tprintf(TEXT("...isLight=error\n"));
}
_tprintf(TEXT("...END: ToggleDarkLight()\n"));
}
void DumpDebug(FILE *file)
{
_ftprintf(file, TEXT("IsLight=%d\n"), IsLight());
}
// Open hyperlink from TaskDialog
HRESULT CALLBACK TaskDialogCallback(HWND hwnd, UINT uNotification, WPARAM wParam, LPARAM lParam, LONG_PTR dwRefData)
{
if (uNotification == TDN_HYPERLINK_CLICKED)
{
ShellExecute(hwnd, TEXT("open"), (TCHAR *)lParam, NULL, NULL, SW_SHOW);
}
return 0;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
Startup(hwnd);
break;
case WM_ACTIVATE:
{
if (wParam == WA_INACTIVE)
{
HideWindow();
}
}
break;
// Handled pre-translate message
// case WM_KEYDOWN:
// if (wParam == VK_ESCAPE)
// {
// HideWindow();
// }
// break;
case WM_CTLCOLORSTATIC:
{
//HDC hdcStatic = (HDC)wParam;
//SetTextColor(hdcStatic, RGB(255,255,255));
//SetBkColor(hdcStatic, RGB(0,0,0));
return (INT_PTR)GetSysColorBrush(COLOR_WINDOW); // CreateSolidBrush(RGB(0,0,0));
}
break;
case WM_HOTKEY:
{
if (wParam == HOT_KEY_ID)
{
ToggleDarkLight(TRUE);
// Remove any repeated WM_HOTKEY messages from the window queue
MSG m;
while (PeekMessage(&m, hwnd, WM_HOTKEY, WM_HOTKEY, PM_REMOVE)) { ; }
return 0;
}
}
case WM_COMMAND:
{
int const wmId = LOWORD(wParam);
switch (wmId)
{
case IDM_TOGGLE:
{
// POINT mouse;
// GetCursorPos(&mouse);
// OpenWindow(mouse.x, mouse.y);
ToggleDarkLight(TRUE);
}
break;
case IDM_AUTOSTART:
if (AutoStart(false, false))
{
// Is auto-starting, remove
AutoStart(true, false);
}
else
{
// Is not auto-starting, add
AutoStart(true, true);
}
break;
case IDM_DEBUG:
{
// Initial filename from local date/time
TCHAR szFileName[MAX_PATH] = TEXT("");
time_t now;
time(&now);
struct tm *local = localtime(&now);
_sntprintf(szFileName, sizeof(szFileName) / sizeof(szFileName[0]), TEXT("" TITLE_SAFE "_%04d-%02d-%02d_%02d-%02d-%02d.txt"), local->tm_year + 1900, local->tm_mon + 1, local->tm_mday, local->tm_hour, local->tm_min, local->tm_sec);
OPENFILENAME openFilename = {0};
openFilename.lStructSize = sizeof(openFilename);
openFilename.hwndOwner = hwnd;
openFilename.lpstrFilter = TEXT("Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0");
openFilename.lpstrFile = szFileName;
openFilename.nMaxFile = sizeof(szFileName) / sizeof(*szFileName);
openFilename.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT;
openFilename.lpstrDefExt = (LPCWSTR)L"txt";
openFilename.lpstrTitle = TITLE;
// Write file to temp folder
TCHAR szInitialDir[MAX_PATH] = TEXT("");
GetTempPath(sizeof(szInitialDir), szInitialDir);
openFilename.lpstrInitialDir = szInitialDir[0] ? szInitialDir : NULL;
if (GetSaveFileName(&openFilename))
{
FILE *file = _tfopen(openFilename.lpstrFile, TEXT("w"));
if (file)
{
DumpDebug(file);
fclose(file);
ShellExecute(NULL, TEXT("open"), openFilename.lpstrFile, NULL, NULL, SW_SHOW);
}
}
}
break;
case IDM_ABOUT:
{
TCHAR *szTitle = TEXT("About " TITLE);
TCHAR szHeader[128] = TEXT("");
_sntprintf(szHeader, sizeof(szHeader) / sizeof(szHeader[0]), TEXT("%s V%d.%d.%d"), TITLE, gVersion[0], gVersion[1], gVersion[2]);
TCHAR *szContent = TEXT("Toggle dark/light mode.\nKeyboard shortcut: Win+Shift+D");
//TCHAR *szExtraInfo = TEXT("...");
TCHAR *szFooter = TEXT("Open source under <a href=\"https://github.com/danielgjackson/toggle-dark-light/blob/master/LICENSE.txt\">MIT License</a>, \u00A9" COPYRIGHT_YEAR " " COPYRIGHT_NAME ".");
TASKDIALOG_BUTTON aCustomButtons[] = {
{ 1001, L"Project page\ngit.luolix.top/danielgjackson/toggle-dark-light" },
{ 1002, L"Check for updates" },
};
TASKDIALOGCONFIG tdc = {0};
tdc.cbSize = sizeof(tdc);
tdc.hwndParent = ghWndMain;
tdc.dwFlags = TDF_USE_HICON_MAIN | TDF_USE_COMMAND_LINKS | TDF_ENABLE_HYPERLINKS | TDF_EXPANDED_BY_DEFAULT | TDF_EXPAND_FOOTER_AREA | TDF_ALLOW_DIALOG_CANCELLATION;
tdc.pButtons = aCustomButtons;
tdc.cButtons = sizeof(aCustomButtons) / sizeof(aCustomButtons[0]);
tdc.pszWindowTitle = szTitle;
tdc.nDefaultButton = IDOK;
tdc.hMainIcon = LoadIcon(ghInstance, TEXT("MAINICON"));
tdc.pszMainInstruction = szHeader;
tdc.pszContent = szContent;
//tdc.pszExpandedInformation = szExtraInfo;
tdc.pszFooter = szFooter;
tdc.pszFooterIcon = TD_INFORMATION_ICON;
tdc.dwCommonButtons = TDCBF_OK_BUTTON;
tdc.pfCallback = TaskDialogCallback;
tdc.lpCallbackData = (LONG_PTR)NULL; // no context needed
int nClickedBtn;
HRESULT hr = TaskDialogIndirect(&tdc, &nClickedBtn, NULL, NULL); // nClickedBtn == IDOK
if (SUCCEEDED(hr))
{
if (nClickedBtn == 1001)
{
ShellExecute(hwnd, TEXT("open"), TEXT("https://github.com/danielgjackson/toggle-dark-light/#readme"), NULL, NULL, SW_SHOW);
}
else if (nClickedBtn == 1002)
{
QueryUpdate();
}
}
}
break;
case IDM_EXIT:
StartExit();
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
}
break;
case WMAPP_NOTIFYCALLBACK:
switch (LOWORD(lParam))
{
case NIN_SELECT:
{
// POINT mouse;
// mouse.x = LOWORD(wParam);
// mouse.y = HIWORD(wParam);