-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTithify.cpp
More file actions
3941 lines (3409 loc) · 155 KB
/
Copy pathTithify.cpp
File metadata and controls
3941 lines (3409 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <winhttp.h>
#include <gdiplus.h>
#include <ctime>
#include <string>
#include <vector>
#include <stdint.h>
#include <stdio.h>
#include <shlobj.h>
#include <commdlg.h>
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "winhttp.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "comdlg32.lib")
using namespace Gdiplus;
// ── App Version ──────────────────────────────────────────────────────────────
#define APP_VERSION L"3.6.3"
#define GITHUB_REPO_API L"/repos/aayushlbef/Tithify/releases/latest"
#define GITHUB_RELEASE_URL L"https://github.com/aayushlbef/Tithify/releases/tag/"
#define WM_UPDATE_AVAILABLE (WM_USER + 2)
#define WM_UPDATE_NOT_FOUND (WM_USER + 3)
#define WM_UPDATE_ERROR (WM_USER + 4)
#define WM_HOLIDAYS_LOADED (WM_USER + 5)
#define WM_HOLIDAYS_FAILED (WM_USER + 6)
#define WM_UPDATE_DOWNLOADING (WM_USER + 7)
#define WM_UPDATE_INSTALL_FAILED (WM_USER + 8)
// ── Global State ─────────────────────────────────────────────────────────────
ULONG_PTR g_gdiplusToken;
HWND g_hWnd = NULL;
extern HWND g_hCalWnd;
extern bool g_isCalendarOpen;
bool g_setupMode = true;
int g_xPos = 500, g_yPos = 1000;
POINT g_dragStart = { 0, 0 };
bool g_isDragging = false;
bool g_isMenuOpen = false;
bool g_showDay = true;
// DPI scale factor (1.0 = 96 DPI, 1.25 = 120 DPI, 1.5 = 144 DPI, etc.)
float g_dpiScale = 1.0f;
bool g_hiddenForFullscreen = false;
bool g_hiddenForTaskbar = false;
bool g_isOnTaskbar = true;
int g_currentShiftX = 0;
int g_currentShiftY = 0;
// ── Background Customization State ───────────────────────────────────────────
int g_bgPresetMode = 0; // 0 = Transparent (Default), 1 = Custom Color, 2 = Dark Glass, 3 = Light Glass, 4 = Solid Black, 5 = Solid White, 6 = Red Accent, 7 = Blue Accent
COLORREF g_bgColorRGB = RGB(31, 31, 31);
int g_bgOpacity = 200; // Opacity level (0..255)
// ── Custom Menu State ────────────────────────────────────────────────────────
HWND g_hMenuWnd = NULL;
int g_menuXPos = 0, g_menuYPos = 0;
int g_menuHoverIndex = -1;
// ── Theme Detection ──────────────────────────────────────────────────────────
bool g_isLightTheme = false; // true = Windows light theme, false = dark
wchar_t g_latestVersion[64] = {0}; // Filled by update-check thread
bool DetectWindowsTheme() {
// Returns true if Windows is using a light taskbar/system theme
HKEY hKey;
if (RegOpenKeyExW(HKEY_CURRENT_USER,
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
DWORD value = 0, size = sizeof(DWORD), type = REG_DWORD;
// SystemUsesLightTheme controls the taskbar/system chrome color
if (RegQueryValueExW(hKey, L"SystemUsesLightTheme", NULL, &type,
(LPBYTE)&value, &size) == ERROR_SUCCESS) {
RegCloseKey(hKey);
return (value != 0);
}
RegCloseKey(hKey);
}
return false; // Default to dark theme if registry read fails
}
// ── Update Checker ───────────────────────────────────────────────────────────
// Compare "3.3.0" vs "3.4.0" style version strings
bool IsVersionNewer(const wchar_t* current, const wchar_t* latest) {
int cMaj = 0, cMin = 0, cPat = 0;
int lMaj = 0, lMin = 0, lPat = 0;
const wchar_t* c = current;
const wchar_t* l = latest;
if (*c == L'v' || *c == L'V') c++;
if (*l == L'v' || *l == L'V') l++;
swscanf(c, L"%d.%d.%d", &cMaj, &cMin, &cPat);
swscanf(l, L"%d.%d.%d", &lMaj, &lMin, &lPat);
if (lMaj != cMaj) return lMaj > cMaj;
if (lMin != cMin) return lMin > cMin;
return lPat > cPat;
}
// Minimal JSON extractor: finds "key":"value" and writes value into out[]
bool ExtractJsonString(const char* json, const char* key, wchar_t* out, int outLen) {
char needle[128];
snprintf(needle, sizeof(needle), "\"%s\"", key);
const char* p = strstr(json, needle);
if (!p) return false;
p += strlen(needle);
while (*p == ' ' || *p == ':' || *p == '\t' || *p == '\n' || *p == '\r') p++;
if (*p != '"') return false;
p++; // skip opening quote
int i = 0;
while (*p && *p != '"' && i < outLen - 1) {
out[i++] = (wchar_t)(*p++);
}
out[i] = 0;
return i > 0;
}
DWORD WINAPI CheckForUpdateThread(LPVOID lpParam) {
bool isManual = (bool)(INT_PTR)lpParam;
HINTERNET hSession = WinHttpOpen(L"Tithify/" APP_VERSION,
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) {
if (isManual) PostMessage(g_hWnd, WM_UPDATE_ERROR, 0, 0);
return 0;
}
HINTERNET hConnect = WinHttpConnect(hSession, L"api.github.com",
INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) {
WinHttpCloseHandle(hSession);
if (isManual) PostMessage(g_hWnd, WM_UPDATE_ERROR, 0, 0);
return 0;
}
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", GITHUB_REPO_API,
NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!hRequest) {
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
if (isManual) PostMessage(g_hWnd, WM_UPDATE_ERROR, 0, 0);
return 0;
}
if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0, 0, 0) ||
!WinHttpReceiveResponse(hRequest, NULL)) {
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
if (isManual) PostMessage(g_hWnd, WM_UPDATE_ERROR, 0, 0);
return 0;
}
// Read the full response body
std::string response;
char buf[4096];
DWORD bytesRead = 0;
while (WinHttpReadData(hRequest, buf, sizeof(buf) - 1, &bytesRead) && bytesRead > 0) {
buf[bytesRead] = 0;
response += buf;
bytesRead = 0;
}
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
// Extract tag_name from the JSON response
wchar_t tagName[64] = {0};
if (ExtractJsonString(response.c_str(), "tag_name", tagName, 64)) {
if (IsVersionNewer(APP_VERSION, tagName)) {
wcscpy_s(g_latestVersion, tagName);
PostMessage(g_hWnd, WM_UPDATE_AVAILABLE, 0, 0);
} else {
if (isManual) PostMessage(g_hWnd, WM_UPDATE_NOT_FOUND, 0, 0);
}
} else {
if (isManual) PostMessage(g_hWnd, WM_UPDATE_ERROR, 0, 0);
}
return 0;
}
// ── Auto-Updater: Visible Console Window ─────────────────────────────────────
// Writes a PowerShell script to %TEMP% and opens it in a visible console
// window so the user can watch the download progress and installation steps.
static void LaunchUpdaterConsole(const wchar_t* version) {
// ── Build the temp .ps1 path ──────────────────────────────────────────────
wchar_t tempDir[MAX_PATH] = {0};
GetTempPathW(MAX_PATH, tempDir);
wchar_t ps1Path[MAX_PATH] = {0};
swprintf(ps1Path, MAX_PATH, L"%sTithify_Updater.ps1", tempDir);
// Convert version to narrow for snprintf
char versionA[64] = {0};
WideCharToMultiByte(CP_UTF8, 0, version, -1, versionA, sizeof(versionA), NULL, NULL);
// ── Build the PowerShell script content ──────────────────────────────────
char script[4096] = {0};
snprintf(script, sizeof(script),
"$ErrorActionPreference = 'Stop'\r\n"
"$version = '%s'\r\n"
"$url = \"https://github.com/aayushlbef/Tithify/releases/download/$version/Tithify_Setup.exe\"\r\n"
"$tmp = \"$env:TEMP\\Tithify_Update_$version.exe\"\r\n"
"$appExe = \"$env:LOCALAPPDATA\\Tithify\\Tithify.exe\"\r\n"
"\r\n"
"Write-Host ''\r\n"
"Write-Host ' ==================================================' -ForegroundColor Cyan\r\n"
"Write-Host ' Tithify -- Auto Updater' -ForegroundColor Cyan\r\n"
"Write-Host ' ==================================================' -ForegroundColor DarkGray\r\n"
"Write-Host ''\r\n"
"Write-Host \" New version : $version\" -ForegroundColor White\r\n"
"Write-Host \" Source : $url\" -ForegroundColor DarkGray\r\n"
"Write-Host ''\r\n"
"\r\n"
"# -- Step 1: Download ------------------------------------------------\r\n"
"Write-Host '[1/3] Downloading installer...' -ForegroundColor Cyan\r\n"
"Write-Host ''\r\n"
"try {\r\n"
" if (Get-Command curl.exe -ErrorAction SilentlyContinue) {\r\n"
" curl.exe -L --progress-bar -o $tmp $url\r\n"
" if ($LASTEXITCODE -ne 0) { throw \"curl exited with code $LASTEXITCODE\" }\r\n"
" } else {\r\n"
" $ProgressPreference = 'Continue'\r\n"
" Invoke-WebRequest -Uri $url -OutFile $tmp -UseBasicParsing\r\n"
" }\r\n"
"} catch {\r\n"
" Write-Host ''\r\n"
" Write-Host \"[-] Download failed: $_\" -ForegroundColor Red\r\n"
" Write-Host ''\r\n"
" Read-Host 'Press Enter to close'\r\n"
" exit 1\r\n"
"}\r\n"
"\r\n"
"if (-not (Test-Path $tmp) -or (Get-Item $tmp).Length -lt 100000) {\r\n"
" Write-Host '[-] Downloaded file appears corrupted. Please try again.' -ForegroundColor Red\r\n"
" Read-Host 'Press Enter to close'\r\n"
" exit 1\r\n"
"}\r\n"
"\r\n"
"Write-Host ''\r\n"
"Write-Host '[+] Download complete!' -ForegroundColor Green\r\n"
"Write-Host ''\r\n"
"\r\n"
"# -- Step 2: Install -------------------------------------------------\r\n"
"Write-Host '[2/3] Installing Tithify...' -ForegroundColor Cyan\r\n"
"Write-Host ' Running installer silently, please wait...' -ForegroundColor DarkGray\r\n"
"Write-Host ''\r\n"
"Start-Process -FilePath $tmp -ArgumentList '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' -Wait\r\n"
"Remove-Item $tmp -Force -ErrorAction SilentlyContinue\r\n"
"Write-Host '[+] Installation complete!' -ForegroundColor Green\r\n"
"Write-Host ''\r\n"
"\r\n"
"# -- Step 3: Relaunch ------------------------------------------------\r\n"
"Write-Host '[3/3] Launching Tithify...' -ForegroundColor Cyan\r\n"
"Start-Sleep -Seconds 1\r\n"
"if (Test-Path $appExe) {\r\n"
" Start-Process -FilePath $appExe\r\n"
" Write-Host '[+] Widget launched successfully.' -ForegroundColor Green\r\n"
"} else {\r\n"
" Write-Host \"[!] Could not find widget at: $appExe\" -ForegroundColor Yellow\r\n"
"}\r\n"
"\r\n"
"Write-Host ''\r\n"
"Write-Host ' Update complete! This window will close in 5 seconds.' -ForegroundColor Cyan\r\n"
"Write-Host ' ==================================================' -ForegroundColor DarkGray\r\n"
"Start-Sleep -Seconds 5\r\n",
versionA
);
// ── Write the script file to disk ────────────────────────────────────────
HANDLE hFile = CreateFileW(ps1Path, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) return;
DWORD written = 0;
WriteFile(hFile, script, (DWORD)strlen(script), &written, NULL);
CloseHandle(hFile);
// ── Launch in a visible PowerShell console window ─────────────────────────
wchar_t args[MAX_PATH + 128] = {0};
swprintf(args, MAX_PATH + 128,
L"-NoProfile -ExecutionPolicy Bypass -File \"%ls\"",
ps1Path);
ShellExecuteW(NULL, L"open", L"powershell.exe", args, NULL, SW_NORMAL);
}
// ── Fullscreen App Detection ─────────────────────────────────────────────────
bool IsShellProcess(DWORD pid) {
if (pid == 0) return true;
// Check explorer process id
DWORD explorerPid = 0;
HWND hShell = GetShellWindow();
if (hShell) {
GetWindowThreadProcessId(hShell, &explorerPid);
} else {
HWND hTb = FindWindow(L"Shell_TrayWnd", NULL);
if (hTb) GetWindowThreadProcessId(hTb, &explorerPid);
}
if (pid == explorerPid) return true;
// Check process executable name
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (hProcess) {
wchar_t exePath[MAX_PATH] = {0};
DWORD size = MAX_PATH;
if (QueryFullProcessImageNameW(hProcess, 0, exePath, &size)) {
const wchar_t* fileName = wcsrchr(exePath, L'\\');
if (fileName) fileName++;
else fileName = exePath;
if (_wcsicmp(fileName, L"explorer.exe") == 0 ||
_wcsicmp(fileName, L"StartMenuExperienceHost.exe") == 0 ||
_wcsicmp(fileName, L"SearchHost.exe") == 0 ||
_wcsicmp(fileName, L"ShellExperienceHost.exe") == 0 ||
_wcsicmp(fileName, L"TextInputHost.exe") == 0 ||
_wcsicmp(fileName, L"ScreenClippingHost.exe") == 0 ||
_wcsicmp(fileName, L"SnippingTool.exe") == 0 ||
_wcsicmp(fileName, L"SnippingToolApp.exe") == 0 ||
_wcsicmp(fileName, L"SnipAndSketch.exe") == 0 ||
_wcsicmp(fileName, L"GameBar.exe") == 0 ||
_wcsicmp(fileName, L"GameBarFTServer.exe") == 0 ||
_wcsicmp(fileName, L"LockApp.exe") == 0 ||
_wcsicmp(fileName, L"SystemSettings.exe") == 0 ||
wcsstr(fileName, L"ScreenClip") != NULL ||
wcsstr(fileName, L"Snipping") != NULL) {
CloseHandle(hProcess);
return true;
}
}
CloseHandle(hProcess);
}
return false;
}
// Returns true if the foreground window is in true fullscreen mode
// (e.g. YouTube fullscreen, media players, games, F11 browser) on the same monitor as Tithify.
bool IsFullscreenAppRunning() {
if (!g_hWnd || g_setupMode) return false;
// 1. Primary Check: Windows notification state
// When in standard desktop mode (working with apps, browsing web, Start menu, Show Desktop):
// SHQueryUserNotificationState reports QUNS_ACCEPTS_NOTIFICATIONS (5) or QUNS_APP (7).
// Windows only sets QUNS_BUSY (2), QUNS_RUNNING_D3D_FULL_SCREEN (3), or QUNS_PRESENTATION_MODE (4)
// when a genuine full-screen application (like YouTube fullscreen, video players, games) is active.
QUERY_USER_NOTIFICATION_STATE quns = (QUERY_USER_NOTIFICATION_STATE)0;
if (SUCCEEDED(SHQueryUserNotificationState(&quns))) {
if (quns != QUNS_BUSY &&
quns != QUNS_RUNNING_D3D_FULL_SCREEN &&
quns != QUNS_PRESENTATION_MODE) {
return false;
}
}
// 2. Verify the active foreground window
HWND hForeground = GetForegroundWindow();
if (!hForeground) return false;
// Desktop and shell windows are never fullscreen apps
if (hForeground == GetDesktopWindow() || hForeground == GetShellWindow())
return false;
// Ignore our own widget windows
if (hForeground == g_hWnd || hForeground == g_hCalWnd || hForeground == g_hMenuWnd)
return false;
// Ignore transparent / click-through overlay windows (e.g. snipping tool overlay)
LONG_PTR exStyle = GetWindowLongPtrW(hForeground, GWL_EXSTYLE);
if (exStyle & WS_EX_TRANSPARENT) {
return false;
}
// Ignore Windows Explorer / Desktop / Taskbar / Shell / Snipping window classes
wchar_t cls[256] = {0};
if (GetClassNameW(hForeground, cls, 256) > 0) {
if (wcscmp(cls, L"WorkerW") == 0 ||
wcscmp(cls, L"Progman") == 0 ||
wcscmp(cls, L"Shell_TrayWnd") == 0 ||
wcscmp(cls, L"Shell_SecondaryTrayWnd") == 0 ||
wcscmp(cls, L"SHELLDLL_DefView") == 0 ||
wcscmp(cls, L"SysListView32") == 0 ||
wcscmp(cls, L"Windows.UI.Core.CoreWindow") == 0 ||
wcscmp(cls, L"XamlExplorerHostIslandWindow") == 0 ||
wcscmp(cls, L"Xaml_WindowedPopupClass") == 0 ||
wcscmp(cls, L"TopLevelWindowForOverflowXamlIsland") == 0 ||
wcscmp(cls, L"ScreenClippingHost") == 0 ||
wcscmp(cls, L"SnippingTool") == 0 ||
wcsstr(cls, L"ScreenClip") != NULL ||
wcsstr(cls, L"Snipping") != NULL) {
return false;
}
}
// Check window title for snipping tools
wchar_t title[256] = {0};
if (GetWindowTextW(hForeground, title, 256) > 0) {
if (wcsstr(title, L"Snipping") != NULL ||
wcsstr(title, L"Screen Clipping") != NULL ||
wcsstr(title, L"Snip & Sketch") != NULL) {
return false;
}
}
// Check process ID: never consider shell host or snipping tool processes as fullscreen apps
DWORD fgPid = 0;
GetWindowThreadProcessId(hForeground, &fgPid);
if (IsShellProcess(fgPid)) {
return false;
}
// 3. Multi-Monitor Awareness: only hide if fullscreen app is on the same monitor as Tithify
HMONITOR hMonApp = MonitorFromWindow(hForeground, MONITOR_DEFAULTTONEAREST);
HMONITOR hMonWidget = MonitorFromWindow(g_hWnd, MONITOR_DEFAULTTONEAREST);
if (!hMonApp || !hMonWidget || hMonApp != hMonWidget) {
return false;
}
MONITORINFO mi = { sizeof(mi) };
if (!GetMonitorInfo(hMonApp, &mi)) return false;
RECT rcWnd;
if (!GetWindowRect(hForeground, &rcWnd)) return false;
// 4. Geometry Check: ensure window covers the entire monitor
bool coversMonitor = (rcWnd.left <= mi.rcMonitor.left &&
rcWnd.top <= mi.rcMonitor.top &&
rcWnd.right >= mi.rcMonitor.right &&
rcWnd.bottom >= mi.rcMonitor.bottom);
if (!coversMonitor) return false;
return true;
}
// ── Desktop Host Window Resolver ──────────────────────────────────────────────
HWND GetDesktopHostWindow() {
HWND hProgman = FindWindowW(L"Progman", NULL);
if (hProgman && FindWindowExW(hProgman, NULL, L"SHELLDLL_DefView", NULL)) {
return hProgman;
}
HWND hWorker = NULL;
while ((hWorker = FindWindowExW(NULL, hWorker, L"WorkerW", NULL)) != NULL) {
if (FindWindowExW(hWorker, NULL, L"SHELLDLL_DefView", NULL)) {
return hWorker;
}
}
return hProgman ? hProgman : GetShellWindow();
}
// ── Real-Time Shell / Foreground Event Hook ──────────────────────────────────
HWINEVENTHOOK g_hEventHook = NULL;
void CALLBACK WinEventProc(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd,
LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {
if (!g_hWnd || !IsWindow(g_hWnd) || g_hiddenForFullscreen || g_hiddenForTaskbar) return;
// When foreground window or focus changes across the system (Start, Search, Taskbar, Show Desktop),
// immediately ensure Tithify is not iconic and sits in the proper z-order.
if (IsIconic(g_hWnd)) {
ShowWindow(g_hWnd, SW_RESTORE);
}
if (!g_isMenuOpen && !g_isCalendarOpen) {
if (g_setupMode || g_isOnTaskbar) {
SetWindowPos(g_hWnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
} else {
HWND hDesktop = GetDesktopHostWindow();
if (hDesktop && (HWND)GetWindowLongPtr(g_hWnd, GWLP_HWNDPARENT) != hDesktop) {
SetWindowLongPtr(g_hWnd, GWLP_HWNDPARENT, (LONG_PTR)hDesktop);
}
SetWindowPos(g_hWnd, HWND_BOTTOM, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
}
}
}
// ── Auto-Hide Taskbar Sync & Animation State ─────────────────────────────────
struct TaskbarSyncState {
bool isAutoHide = false;
bool isCompletelyHidden = false;
int shiftX = 0;
int shiftY = 0;
};
TaskbarSyncState GetTaskbarSyncState() {
TaskbarSyncState state;
APPBARDATA abd = { sizeof(APPBARDATA) };
UINT abState = (UINT)SHAppBarMessage(ABM_GETSTATE, &abd);
state.isAutoHide = (abState & ABS_AUTOHIDE) != 0;
if (!state.isAutoHide) return state;
HWND hTaskbar = FindWindowW(L"Shell_TrayWnd", NULL);
if (!hTaskbar) return state;
RECT rcTaskbar;
if (!GetWindowRect(hTaskbar, &rcTaskbar)) return state;
HMONITOR hMon = MonitorFromWindow(hTaskbar, MONITOR_DEFAULTTONEAREST);
MONITORINFO mi = { sizeof(mi) };
GetMonitorInfo(hMon, &mi);
static int s_expandedHeight = 48;
static int s_expandedWidth = 48;
int tbHeight = rcTaskbar.bottom - rcTaskbar.top;
int tbWidth = rcTaskbar.right - rcTaskbar.left;
if (tbHeight > 10) s_expandedHeight = tbHeight;
if (tbWidth > 10) s_expandedWidth = tbWidth;
// Bottom Taskbar:
if (rcTaskbar.bottom >= mi.rcMonitor.bottom - 10) {
int normalTop = mi.rcMonitor.bottom - s_expandedHeight;
state.shiftY = rcTaskbar.top - normalTop;
if (state.shiftY < 0) state.shiftY = 0;
if (tbHeight <= 4 || rcTaskbar.top >= mi.rcMonitor.bottom - 4) {
state.isCompletelyHidden = true;
}
}
// Top Taskbar:
else if (rcTaskbar.top <= mi.rcMonitor.top + 10) {
int normalBottom = mi.rcMonitor.top + s_expandedHeight;
state.shiftY = rcTaskbar.bottom - normalBottom;
if (state.shiftY > 0) state.shiftY = 0;
if (tbHeight <= 4 || rcTaskbar.bottom <= mi.rcMonitor.top + 4) {
state.isCompletelyHidden = true;
}
}
// Right Taskbar:
else if (rcTaskbar.right >= mi.rcMonitor.right - 10) {
int normalLeft = mi.rcMonitor.right - s_expandedWidth;
state.shiftX = rcTaskbar.left - normalLeft;
if (state.shiftX < 0) state.shiftX = 0;
if (tbWidth <= 4 || rcTaskbar.left >= mi.rcMonitor.right - 4) {
state.isCompletelyHidden = true;
}
}
// Left Taskbar:
else if (rcTaskbar.left <= mi.rcMonitor.left + 10) {
int normalRight = mi.rcMonitor.left + s_expandedWidth;
state.shiftX = rcTaskbar.right - normalRight;
if (state.shiftX > 0) state.shiftX = 0;
if (tbWidth <= 4 || rcTaskbar.right <= mi.rcMonitor.left + 4) {
state.isCompletelyHidden = true;
}
}
return state;
}
// ── Taskbar vs Desktop Location Auto-Detection ───────────────────────────────
bool IsPositionOnTaskbar(int x, int y, int w, int h) {
RECT rcWidget = { x, y, x + w, y + h };
POINT center = { x + w / 2, y + h / 2 };
HMONITOR hMon = MonitorFromRect(&rcWidget, MONITOR_DEFAULTTONEAREST);
if (!hMon) return false;
MONITORINFO mi = { sizeof(mi) };
if (!GetMonitorInfo(hMon, &mi)) return false;
HWND hTaskbar = FindWindowW(L"Shell_TrayWnd", NULL);
RECT rcTaskbar = { 0 };
bool taskbarFound = false;
if (hTaskbar) {
taskbarFound = (GetWindowRect(hTaskbar, &rcTaskbar) != 0);
}
int tbHeight = rcTaskbar.bottom - rcTaskbar.top;
int tbWidth = rcTaskbar.right - rcTaskbar.left;
RECT rcTaskbarArea = { 0 };
// 1. Standard taskbar: Monitor work area differs from monitor rect
if (mi.rcWork.bottom < mi.rcMonitor.bottom) {
rcTaskbarArea = { mi.rcMonitor.left, mi.rcWork.bottom, mi.rcMonitor.right, mi.rcMonitor.bottom };
} else if (mi.rcWork.top > mi.rcMonitor.top) {
rcTaskbarArea = { mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right, mi.rcWork.top };
} else if (mi.rcWork.left > mi.rcMonitor.left) {
rcTaskbarArea = { mi.rcMonitor.left, mi.rcMonitor.top, mi.rcWork.left, mi.rcMonitor.bottom };
} else if (mi.rcWork.right < mi.rcMonitor.right) {
rcTaskbarArea = { mi.rcWork.right, mi.rcMonitor.top, mi.rcMonitor.right, mi.rcMonitor.bottom };
} else if (taskbarFound) {
// 2. Auto-hide taskbar (work area equals monitor rect)
if (tbHeight > 10 && tbWidth > 10) {
rcTaskbarArea = rcTaskbar;
} else {
// Taskbar is collapsed auto-hide bar: synthesize expanded rect at the monitor edge
int defH = (int)(48 * g_dpiScale);
if (rcTaskbar.bottom >= mi.rcMonitor.bottom - 10) {
rcTaskbarArea = { mi.rcMonitor.left, mi.rcMonitor.bottom - defH, mi.rcMonitor.right, mi.rcMonitor.bottom };
} else if (rcTaskbar.top <= mi.rcMonitor.top + 10) {
rcTaskbarArea = { mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right, mi.rcMonitor.top + defH };
} else if (rcTaskbar.right >= mi.rcMonitor.right - 10) {
rcTaskbarArea = { mi.rcMonitor.right - defH, mi.rcMonitor.top, mi.rcMonitor.right, mi.rcMonitor.bottom };
} else if (rcTaskbar.left <= mi.rcMonitor.left + 10) {
rcTaskbarArea = { mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.left + defH, mi.rcMonitor.bottom };
}
}
} else {
// 3. Fallback: bottom 48px of primary monitor
int defH = (int)(48 * g_dpiScale);
rcTaskbarArea = { mi.rcMonitor.left, mi.rcMonitor.bottom - defH, mi.rcMonitor.right, mi.rcMonitor.bottom };
}
// Test if widget center point or >30% overlap lies in taskbar area
if (PtInRect(&rcTaskbarArea, center)) {
return true;
}
RECT rcIntersect;
if (IntersectRect(&rcIntersect, &rcWidget, &rcTaskbarArea)) {
int intersectArea = (rcIntersect.right - rcIntersect.left) * (rcIntersect.bottom - rcIntersect.top);
int widgetArea = w * h;
if (intersectArea > widgetArea / 3) {
return true;
}
}
return false;
}
void UpdateWidgetMode() {
if (!g_hWnd) return;
int winW = (int)((g_showDay ? 190 : 155) * g_dpiScale);
int winH = (int)(48 * g_dpiScale);
g_isOnTaskbar = IsPositionOnTaskbar(g_xPos, g_yPos, winW, winH);
// In Win32, an owned popup window is always placed above its owner in Z-order.
// - When on taskbar: owner is Shell_TrayWnd so Tithify stays naturally above the taskbar.
// - When on desktop: owner is Progman / WorkerW (desktop host) so Tithify stays directly
// above the desktop wallpaper and never disappears when "Show Desktop" (Win+D) is invoked.
HWND hTaskbar = FindWindowW(L"Shell_TrayWnd", NULL);
HWND hDesktop = GetDesktopHostWindow();
if (g_isOnTaskbar) {
if (hTaskbar) SetWindowLongPtr(g_hWnd, GWLP_HWNDPARENT, (LONG_PTR)hTaskbar);
else SetWindowLongPtr(g_hWnd, GWLP_HWNDPARENT, 0);
} else {
if (hDesktop) SetWindowLongPtr(g_hWnd, GWLP_HWNDPARENT, (LONG_PTR)hDesktop);
else SetWindowLongPtr(g_hWnd, GWLP_HWNDPARENT, 0);
}
LONG_PTR exStyle = GetWindowLongPtr(g_hWnd, GWL_EXSTYLE);
if (g_setupMode || g_isOnTaskbar) {
// Setup mode (unlocked for dragging) or taskbar mode: keep TOPMOST
if (!(exStyle & WS_EX_TOPMOST)) {
SetWindowLongPtr(g_hWnd, GWL_EXSTYLE, exStyle | WS_EX_TOPMOST);
}
SetWindowPos(g_hWnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
} else {
// Locked on desktop: behave like a desktop icon (bottom of window stack)
if (exStyle & WS_EX_TOPMOST) {
SetWindowLongPtr(g_hWnd, GWL_EXSTYLE, exStyle & ~WS_EX_TOPMOST);
}
SetWindowPos(g_hWnd, HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
SetWindowPos(g_hWnd, HWND_BOTTOM, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
}
}
std::wstring GetConfigPath() {
wchar_t path[MAX_PATH];
GetModuleFileNameW(NULL, path, MAX_PATH);
std::wstring ws(path);
size_t pos = ws.find_last_of(L"\\/");
if (pos != std::wstring::npos) {
ws = ws.substr(0, pos);
}
return ws + L"\\tithify.cfg";
}
void RenderWidget(HWND hWnd);
void LoadConfig() {
std::wstring path = GetConfigPath();
std::string npath(path.begin(), path.end());
FILE* file = fopen(npath.c_str(), "r");
if (!file) {
// Fallback for legacy widget.cfg
wchar_t exePath[MAX_PATH];
GetModuleFileNameW(NULL, exePath, MAX_PATH);
std::wstring ws(exePath);
size_t pos = ws.find_last_of(L"\\/");
if (pos != std::wstring::npos) ws = ws.substr(0, pos);
std::wstring legacyPath = ws + L"\\widget.cfg";
std::string nLegacy(legacyPath.begin(), legacyPath.end());
file = fopen(nLegacy.c_str(), "r");
}
if (file) {
int x, y, setup, showDay = 1, bgPreset = 0, opacity = 200;
unsigned int colorVal = (unsigned int)RGB(31, 31, 31);
int n = fscanf(file, "%d,%d,%d,%d,%u,%d,%d", &x, &y, &setup, &showDay, &colorVal, &opacity, &bgPreset);
if (n >= 3) {
g_xPos = x;
g_yPos = y;
g_setupMode = (setup != 0);
if (n >= 4) g_showDay = (showDay != 0);
if (n >= 5) g_bgColorRGB = (COLORREF)colorVal;
if (n >= 6) g_bgOpacity = opacity;
if (n >= 7) g_bgPresetMode = bgPreset;
}
fclose(file);
}
}
void SaveConfig() {
std::wstring path = GetConfigPath();
std::string npath(path.begin(), path.end());
FILE* file = fopen(npath.c_str(), "w");
if (file) {
fprintf(file, "%d,%d,%d,%d,%u,%d,%d",
g_xPos, g_yPos, g_setupMode ? 1 : 0, g_showDay ? 1 : 0,
(unsigned int)g_bgColorRGB, g_bgOpacity, g_bgPresetMode);
fclose(file);
}
}
bool PickCustomBackgroundColor(HWND hWndOwner) {
static COLORREF custColors[16] = {
RGB(255,255,255), RGB(0,0,0), RGB(240,240,240), RGB(32,32,32),
RGB(230,50,50), RGB(50,180,50), RGB(50,120,240), RGB(240,180,50),
RGB(150,50,200), RGB(50,200,200), RGB(255,128,0), RGB(128,128,128),
RGB(64,64,64), RGB(192,192,192), RGB(255,192,203), RGB(128,0,0)
};
CHOOSECOLORW cc = { sizeof(CHOOSECOLORW) };
cc.hwndOwner = hWndOwner;
cc.lpCustColors = custColors;
cc.rgbResult = g_bgColorRGB;
cc.Flags = CC_FULLOPEN | CC_RGBINIT;
if (ChooseColorW(&cc)) {
g_bgColorRGB = cc.rgbResult;
g_bgPresetMode = 1; // Custom color mode
SaveConfig();
if (g_hWnd) RenderWidget(g_hWnd);
return true;
}
return false;
}
// ── Startup Registry Helpers ────────────────────────────────────────────────
static const wchar_t* STARTUP_REG_KEY = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
static const wchar_t* STARTUP_REG_VALUE = L"Tithify";
bool IsStartupEnabled() {
HKEY hKey;
if (RegOpenKeyExW(HKEY_CURRENT_USER, STARTUP_REG_KEY, 0, KEY_READ, &hKey) != ERROR_SUCCESS)
return false;
DWORD type = 0, size = 0;
bool exists = (RegQueryValueExW(hKey, STARTUP_REG_VALUE, NULL, &type, NULL, &size) == ERROR_SUCCESS);
RegCloseKey(hKey);
return exists;
}
void SetStartupEnabled(bool enable) {
HKEY hKey;
if (RegOpenKeyExW(HKEY_CURRENT_USER, STARTUP_REG_KEY, 0, KEY_SET_VALUE, &hKey) != ERROR_SUCCESS)
return;
if (enable) {
wchar_t exePath[MAX_PATH];
GetModuleFileNameW(NULL, exePath, MAX_PATH);
std::wstring val = std::wstring(L"\"") + exePath + L"\"";
RegSetValueExW(hKey, STARTUP_REG_VALUE, 0, REG_SZ,
(const BYTE*)val.c_str(), (DWORD)((val.size() + 1) * sizeof(wchar_t)));
} else {
RegDeleteValueW(hKey, STARTUP_REG_VALUE);
}
RegCloseKey(hKey);
}
// ── Nepali Date Calculator (Pure C++) ────────────────────────────────────────
#include "bs_data.h"
const wchar_t* kNepaliMonthNamesEN[] = {
L"Baisakh", L"Jestha", L"Ashadh", L"Shrawan", L"Bhadra", L"Ashwin",
L"Kartik", L"Mangsir", L"Poush", L"Magh", L"Falgun", L"Chaitra"
};
const wchar_t* kNepaliMonthNamesNP[] = {
L"\u092C\u0948\u0936\u093E\u0916", // Baisakh (बैशाख)
L"\u091C\u0947\u0920", // Jestha (जेठ)
L"\u0905\u0938\u093E\u0930", // Ashadh (असार)
L"\u0936\u094D\u0930\u093E\u0935\u0923", // Shrawan (श्रावण)
L"\u092D\u0926\u094C", // Bhadra (भदौ)
L"\u0905\u0938\u094B\u091C", // Ashwin (असोज)
L"\u0915\u093E\u0930\u094D\u0924\u093F\u0915", // Kartik (कार्तिक)
L"\u092E\u0902\u0938\u093F\u0930", // Mangsir (मंसिर)
L"\u092A\u0941\u0937", // Poush (पुष)
L"\u092E\u093E\u0918", // Magh (माघ)
L"\u092B\u093E\u0932\u094D\u0917\u0941\u0928", // Falgun (फाल्गुन)
L"\u091A\u0948\u0924" // Chaitra (चैत)
};
const wchar_t* kEnglishMonthNames[] = {
L"January", L"February", L"March", L"April", L"May", L"June",
L"July", L"August", L"September", L"October", L"November", L"December"
};
const wchar_t* kNepaliDayNamesEN[] = {
L"Sunday", L"Monday", L"Tuesday", L"Wednesday", L"Thursday", L"Friday", L"Saturday"
};
const wchar_t* kNepaliDayNamesNP[] = {
L"\u0906\u0907\u0924\u092C\u093E\u0930", // Sunday (आइतबार)
L"\u0938\u094B\u092E\u092C\u093E\u0930", // Monday (सोमबार)
L"\u092E\u0902\u0917\u0932\u092C\u093E\u0930", // Tuesday (मंगलबार)
L"\u092C\u0941\u0927\u092C\u093E\u0930", // Wednesday (बुधबार)
L"\u092C\u093F\u0939\u0940\u092C\u093E\u0930", // Thursday (बिहीबार)
L"\u0936\u0941\u0915\u094D\u0930\u092C\u093E\u0930", // Friday (शुक्रबार)
L"\u0936\u0928\u093F\u092C\u093E\u0930" // Saturday (शनिबार)
};
// ── Forward declaration for Calendar window handle ───────────────────────────
extern HWND g_hCalWnd;
// ── Nepali Public Holidays & Notable Festivals Engine ────────────────────────
struct NepaliHoliday {
int month; // 1 = Baisakh, ..., 12 = Chaitra
int day; // Day of BS month (1..32)
bool isPublicHoliday;
std::wstring titleNP;
std::wstring titleEN;
std::wstring category;
std::wstring description;
};
enum HolidayFetchState {
FETCH_IDLE,
FETCH_SUCCESS,
FETCH_DOWNLOADING,
FETCH_ERROR_OFFLINE
};
#define HOLIDAY_FILE_MAGIC 0x4857444E
#define HOLIDAY_FILE_VERSION 1
#define ENCODE_XOR_KEY 0x5A
int g_loadedHolidayYear = 0;
std::vector<NepaliHoliday> g_currentYearHolidays;
HolidayFetchState g_holidayFetchState = FETCH_IDLE;
bool g_isHolidayFetchInProgress = false;
DWORD g_lastHolidayFetchAttemptTime = 0;
std::string WideToUtf8(const std::wstring& wstr) {
if (wstr.empty()) return "";
int len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), NULL, 0, NULL, NULL);
std::string str(len, 0);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), &str[0], len, NULL, NULL);
return str;
}
std::wstring Utf8ToWide(const std::string& str) {
if (str.empty()) return L"";
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), NULL, 0);
std::wstring wstr(len, 0);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), &wstr[0], len);
return wstr;
}
std::wstring GetHolidayCachePath(int bsYear) {
wchar_t appDataPath[MAX_PATH];
if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, appDataPath))) {
std::wstring dir = std::wstring(appDataPath) + L"\\Tithify";
CreateDirectoryW(dir.c_str(), NULL);
return dir + L"\\holidays_" + std::to_wstring(bsYear) + L".dat";
}
wchar_t path[MAX_PATH];
GetModuleFileNameW(NULL, path, MAX_PATH);
std::wstring ws(path);
size_t pos = ws.find_last_of(L"\\/");
if (pos != std::wstring::npos) {
ws = ws.substr(0, pos);
}
return ws + L"\\holidays_" + std::to_wstring(bsYear) + L".dat";
}
bool SaveEncodedHolidayFile(int bsYear, const std::vector<NepaliHoliday>& holidays) {
std::wstring filePath = GetHolidayCachePath(bsYear);
FILE* f = _wfopen(filePath.c_str(), L"wb");
if (!f) return false;
uint32_t magic = HOLIDAY_FILE_MAGIC;
uint16_t version = HOLIDAY_FILE_VERSION;
uint16_t year = (uint16_t)bsYear;
uint16_t count = (uint16_t)holidays.size();
fwrite(&magic, sizeof(magic), 1, f);
fwrite(&version, sizeof(version), 1, f);
fwrite(&year, sizeof(year), 1, f);
fwrite(&count, sizeof(count), 1, f);
for (const auto& h : holidays) {
uint8_t m = (uint8_t)h.month;
uint8_t d = (uint8_t)h.day;
uint8_t pub = h.isPublicHoliday ? 1 : 0;
fwrite(&m, sizeof(m), 1, f);
fwrite(&d, sizeof(d), 1, f);
fwrite(&pub, sizeof(pub), 1, f);
auto writeEncStr = [&](const std::wstring& ws) {
std::string utf8 = WideToUtf8(ws);
uint16_t len = (uint16_t)utf8.size();
fwrite(&len, sizeof(len), 1, f);
for (size_t i = 0; i < utf8.size(); ++i) {
uint8_t b = (uint8_t)utf8[i] ^ ENCODE_XOR_KEY;
fwrite(&b, 1, 1, f);
}
};
writeEncStr(h.titleNP);
writeEncStr(h.titleEN);
writeEncStr(h.category);
writeEncStr(h.description);
}
fclose(f);
return true;
}
bool LoadEncodedHolidayFile(int bsYear, std::vector<NepaliHoliday>& outHolidays) {
std::wstring filePath = GetHolidayCachePath(bsYear);
FILE* f = _wfopen(filePath.c_str(), L"rb");
if (!f) return false;
uint32_t magic = 0;
uint16_t version = 0;
uint16_t year = 0;
uint16_t count = 0;
if (fread(&magic, sizeof(magic), 1, f) != 1 || magic != HOLIDAY_FILE_MAGIC) { fclose(f); return false; }
if (fread(&version, sizeof(version), 1, f) != 1 || version != HOLIDAY_FILE_VERSION) { fclose(f); return false; }
if (fread(&year, sizeof(year), 1, f) != 1 || year != bsYear) { fclose(f); return false; }
if (fread(&count, sizeof(count), 1, f) != 1) { fclose(f); return false; }
outHolidays.clear();
for (uint16_t i = 0; i < count; ++i) {
NepaliHoliday h;
uint8_t m = 0, d = 0, pub = 0;
if (fread(&m, sizeof(m), 1, f) != 1) break;
if (fread(&d, sizeof(d), 1, f) != 1) break;
if (fread(&pub, sizeof(pub), 1, f) != 1) break;
h.month = m;
h.day = d;
h.isPublicHoliday = (pub != 0);
auto readEncStr = [&]() -> std::wstring {
uint16_t len = 0;
if (fread(&len, sizeof(len), 1, f) != 1) return L"";
std::string utf8(len, '\0');
for (uint16_t j = 0; j < len; ++j) {
uint8_t b = 0;
if (fread(&b, 1, 1, f) != 1) break;
utf8[j] = (char)(b ^ ENCODE_XOR_KEY);
}
return Utf8ToWide(utf8);
};
h.titleNP = readEncStr();
h.titleEN = readEncStr();
h.category = readEncStr();
h.description = readEncStr();
outHolidays.push_back(h);
}
fclose(f);
return !outHolidays.empty();
}
bool ParseHolidaysJson(const std::string& json, int expectedYear, std::vector<NepaliHoliday>& outHolidays) {
outHolidays.clear();
const char* p = json.c_str();
const char* holArray = strstr(p, "\"holidays\"");
if (!holArray) return false;
const char* openBracket = strchr(holArray, '[');
if (!openBracket) return false;
p = openBracket + 1;
while (*p && *p != ']') {
const char* objStart = strchr(p, '{');
if (!objStart) break;
const char* objEnd = strchr(objStart, '}');
if (!objEnd) break;
std::string obj(objStart, objEnd - objStart + 1);
NepaliHoliday h;
h.month = 0;
h.day = 0;