-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
executable file
·2322 lines (2008 loc) · 89.5 KB
/
main.c
File metadata and controls
executable file
·2322 lines (2008 loc) · 89.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
// main.c
#define _WIN32_WINNT 0x0600
#include <windows.h>
#include <winhttp.h>
#include <shlobj.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <commctrl.h>
#include <objbase.h>
#include "resource.h"
#pragma comment(lib, "winhttp.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "advapi32.lib")
#define WM_TRAYICON (WM_USER + 1)
#define ID_TRAY_EXIT 1001
#define ID_TRAY_REFRESH 1002
#define ID_TRAY_CONFIGURE 1004
#define ID_TRAY_HISTORY 1005
// Registry settings
#define REG_KEY_PATH "SOFTWARE\\JPIT\\APIMonitor"
#define REG_VALUE_URL "ApiUrl"
#define REG_VALUE_INTERVAL "RefreshInterval"
#define REG_VALUE_LOGGING "LoggingEnabled"
#define REG_VALUE_CONFIGURED "Configured"
#define REG_VALUE_HISTORY_LIMIT "HistoryLimit"
#define REG_VALUE_HISTORY_COUNT "HistoryCount"
#define REG_VALUE_HISTORY_DATA "HistoryData"
#define WM_VALIDATE_RESULT (WM_APP + 1)
#define WM_SHOW_FIRST_CONFIG (WM_USER + 2)
#define ID_TIMER_WEBVIEW_SHOW_FALLBACK 1006
#define WEBVIEW_SHOW_FALLBACK_DELAY_MS 350
typedef enum {
RESULT_NONE, // Initial state - no result yet
RESULT_ERROR, // Connection/network error
RESULT_INVALID, // Connected but invalid response
RESULT_SUCCESS,
RESULT_FAIL
} ApiResult;
typedef struct {
ApiResult result;
char message[256];
} ApiResponse;
typedef struct {
int attempt;
int maxAttempts;
} ThreadParams;
typedef struct {
SYSTEMTIME timestamp;
ApiResult oldResult;
ApiResult newResult;
char oldMessage[256];
char newMessage[256];
} HistoryEntry;
// Global variables
static NOTIFYICONDATA nid = {0};
static HMENU hMenu = NULL;
static char configApiUrl[512] = "http://example.com/api/status";
static int configRefreshInterval = 60;
static char logFilePath[MAX_PATH];
static HICON hIconEmpty = NULL;
static HICON hIconSuccess = NULL;
static HICON hIconFail = NULL;
static HICON hIconBlank = NULL;
static UINT_PTR timerRefresh = 0;
static UINT_PTR timerTooltip = 0;
static BOOL iconVisible = TRUE;
static HICON currentIcon = NULL;
static char currentMessage[256] = "";
static ApiResult currentResult = RESULT_NONE;
static SYSTEMTIME lastUpdateTime = {0};
static HWND g_hwnd = NULL;
static HINSTANCE g_hInstance = NULL;
static HANDLE g_hMutex = NULL; // Mutex for single instance check
static CRITICAL_SECTION logCriticalSection; // For thread-safe logging
static BOOL configLoggingEnabled = TRUE; // Global variable for logging toggle (default true)
static int configHistoryLimit = 100;
static HistoryEntry* historyBuffer = NULL;
static int historyCapacity = 0;
static int historyCount = 0;
static int historyHead = 0;
// URL validation thread params
typedef struct {
char url[512];
HWND hDlg;
LONG generation;
} ValidateParams;
static volatile LONG g_validateGeneration = 0;
// Display settings tracking (for RDP reconnect icon refresh)
static int lastScreenWidth = 0;
static int lastScreenHeight = 0;
static int lastDpiX = 0;
static int lastDpiY = 0;
// ============================================================================
// WebView2 COM interface definitions (minimal vtable approach)
// ============================================================================
// GUIDs
DEFINE_GUID(IID_ICoreWebView2Environment, 0xb96d755e,0x0319,0x4e92,0xa2,0x96,0x23,0x43,0x6f,0x46,0xa1,0xfc);
DEFINE_GUID(IID_ICoreWebView2Controller, 0x4d00c0d1,0x9583,0x4f38,0x8e,0x50,0xa9,0xa6,0xb3,0x44,0x78,0xcd);
DEFINE_GUID(IID_ICoreWebView2, 0x76eceacb,0x0462,0x4d94,0xac,0x83,0x42,0x3a,0x67,0x93,0x77,0x5e);
DEFINE_GUID(IID_ICoreWebView2Settings, 0xe562e4f0,0xd7fa,0x43ac,0x8d,0x71,0xc0,0x51,0x50,0x49,0x9f,0x00);
typedef struct EventRegistrationToken { __int64 value; } EventRegistrationToken;
// Forward declarations of COM interfaces
typedef struct ICoreWebView2Environment ICoreWebView2Environment;
typedef struct ICoreWebView2Controller ICoreWebView2Controller;
typedef struct ICoreWebView2 ICoreWebView2;
typedef struct ICoreWebView2Settings ICoreWebView2Settings;
typedef struct ICoreWebView2WebMessageReceivedEventArgs ICoreWebView2WebMessageReceivedEventArgs;
typedef struct ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler;
typedef struct ICoreWebView2CreateCoreWebView2ControllerCompletedHandler ICoreWebView2CreateCoreWebView2ControllerCompletedHandler;
typedef struct ICoreWebView2WebMessageReceivedEventHandler ICoreWebView2WebMessageReceivedEventHandler;
// ICoreWebView2Environment vtable
typedef struct ICoreWebView2EnvironmentVtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(ICoreWebView2Environment*, REFIID, void**);
ULONG (STDMETHODCALLTYPE *AddRef)(ICoreWebView2Environment*);
ULONG (STDMETHODCALLTYPE *Release)(ICoreWebView2Environment*);
HRESULT (STDMETHODCALLTYPE *CreateCoreWebView2Controller)(ICoreWebView2Environment*, HWND, ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*);
HRESULT (STDMETHODCALLTYPE *CreateWebResourceResponse)(ICoreWebView2Environment*, void*, int, LPCWSTR, LPCWSTR, void**);
HRESULT (STDMETHODCALLTYPE *get_BrowserVersionString)(ICoreWebView2Environment*, LPWSTR*);
HRESULT (STDMETHODCALLTYPE *add_NewBrowserVersionAvailable)(ICoreWebView2Environment*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_NewBrowserVersionAvailable)(ICoreWebView2Environment*, EventRegistrationToken);
} ICoreWebView2EnvironmentVtbl;
struct ICoreWebView2Environment { const ICoreWebView2EnvironmentVtbl *lpVtbl; };
// ICoreWebView2Controller vtable
typedef struct ICoreWebView2ControllerVtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(ICoreWebView2Controller*, REFIID, void**);
ULONG (STDMETHODCALLTYPE *AddRef)(ICoreWebView2Controller*);
ULONG (STDMETHODCALLTYPE *Release)(ICoreWebView2Controller*);
HRESULT (STDMETHODCALLTYPE *get_IsVisible)(ICoreWebView2Controller*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_IsVisible)(ICoreWebView2Controller*, BOOL);
HRESULT (STDMETHODCALLTYPE *get_Bounds)(ICoreWebView2Controller*, RECT*);
HRESULT (STDMETHODCALLTYPE *put_Bounds)(ICoreWebView2Controller*, RECT);
HRESULT (STDMETHODCALLTYPE *get_ZoomFactor)(ICoreWebView2Controller*, double*);
HRESULT (STDMETHODCALLTYPE *put_ZoomFactor)(ICoreWebView2Controller*, double);
HRESULT (STDMETHODCALLTYPE *add_ZoomFactorChanged)(ICoreWebView2Controller*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_ZoomFactorChanged)(ICoreWebView2Controller*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *SetBoundsAndZoomFactor)(ICoreWebView2Controller*, RECT, double);
HRESULT (STDMETHODCALLTYPE *MoveFocus)(ICoreWebView2Controller*, int);
HRESULT (STDMETHODCALLTYPE *add_MoveFocusRequested)(ICoreWebView2Controller*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_MoveFocusRequested)(ICoreWebView2Controller*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_GotFocus)(ICoreWebView2Controller*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_GotFocus)(ICoreWebView2Controller*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_LostFocus)(ICoreWebView2Controller*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_LostFocus)(ICoreWebView2Controller*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_AcceleratorKeyPressed)(ICoreWebView2Controller*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_AcceleratorKeyPressed)(ICoreWebView2Controller*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *get_ParentWindow)(ICoreWebView2Controller*, HWND*);
HRESULT (STDMETHODCALLTYPE *put_ParentWindow)(ICoreWebView2Controller*, HWND);
HRESULT (STDMETHODCALLTYPE *NotifyParentWindowPositionChanged)(ICoreWebView2Controller*);
HRESULT (STDMETHODCALLTYPE *Close)(ICoreWebView2Controller*);
HRESULT (STDMETHODCALLTYPE *get_CoreWebView2)(ICoreWebView2Controller*, ICoreWebView2**);
} ICoreWebView2ControllerVtbl;
struct ICoreWebView2Controller { const ICoreWebView2ControllerVtbl *lpVtbl; };
// ICoreWebView2 vtable (full table required)
typedef struct ICoreWebView2Vtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(ICoreWebView2*, REFIID, void**);
ULONG (STDMETHODCALLTYPE *AddRef)(ICoreWebView2*);
ULONG (STDMETHODCALLTYPE *Release)(ICoreWebView2*);
HRESULT (STDMETHODCALLTYPE *get_Settings)(ICoreWebView2*, ICoreWebView2Settings**);
HRESULT (STDMETHODCALLTYPE *get_Source)(ICoreWebView2*, LPWSTR*);
HRESULT (STDMETHODCALLTYPE *Navigate)(ICoreWebView2*, LPCWSTR);
HRESULT (STDMETHODCALLTYPE *NavigateToString)(ICoreWebView2*, LPCWSTR);
HRESULT (STDMETHODCALLTYPE *add_NavigationStarting)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_NavigationStarting)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_ContentLoading)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_ContentLoading)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_SourceChanged)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_SourceChanged)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_HistoryChanged)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_HistoryChanged)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_NavigationCompleted)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_NavigationCompleted)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_FrameNavigationStarting)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_FrameNavigationStarting)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_FrameNavigationCompleted)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_FrameNavigationCompleted)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_ScriptDialogOpening)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_ScriptDialogOpening)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_PermissionRequested)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_PermissionRequested)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_ProcessFailed)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_ProcessFailed)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *AddScriptToExecuteOnDocumentCreated)(ICoreWebView2*, LPCWSTR, void*);
HRESULT (STDMETHODCALLTYPE *RemoveScriptToExecuteOnDocumentCreated)(ICoreWebView2*, LPCWSTR);
HRESULT (STDMETHODCALLTYPE *ExecuteScript)(ICoreWebView2*, LPCWSTR, void*);
HRESULT (STDMETHODCALLTYPE *CapturePreview)(ICoreWebView2*, int, void*, void*);
HRESULT (STDMETHODCALLTYPE *Reload)(ICoreWebView2*);
HRESULT (STDMETHODCALLTYPE *PostWebMessageAsJson)(ICoreWebView2*, LPCWSTR);
HRESULT (STDMETHODCALLTYPE *PostWebMessageAsString)(ICoreWebView2*, LPCWSTR);
HRESULT (STDMETHODCALLTYPE *add_WebMessageReceived)(ICoreWebView2*, ICoreWebView2WebMessageReceivedEventHandler*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_WebMessageReceived)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *CallDevToolsProtocolMethod)(ICoreWebView2*, LPCWSTR, LPCWSTR, void*);
HRESULT (STDMETHODCALLTYPE *get_BrowserProcessId)(ICoreWebView2*, UINT32*);
HRESULT (STDMETHODCALLTYPE *get_CanGoBack)(ICoreWebView2*, BOOL*);
HRESULT (STDMETHODCALLTYPE *get_CanGoForward)(ICoreWebView2*, BOOL*);
HRESULT (STDMETHODCALLTYPE *GoBack)(ICoreWebView2*);
HRESULT (STDMETHODCALLTYPE *GoForward)(ICoreWebView2*);
HRESULT (STDMETHODCALLTYPE *GetDevToolsProtocolEventReceiver)(ICoreWebView2*, LPCWSTR, void**);
HRESULT (STDMETHODCALLTYPE *Stop)(ICoreWebView2*);
HRESULT (STDMETHODCALLTYPE *add_NewWindowRequested)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_NewWindowRequested)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *add_DocumentTitleChanged)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_DocumentTitleChanged)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *get_DocumentTitle)(ICoreWebView2*, LPWSTR*);
HRESULT (STDMETHODCALLTYPE *AddHostObjectToScript)(ICoreWebView2*, LPCWSTR, void*);
HRESULT (STDMETHODCALLTYPE *RemoveHostObjectFromScript)(ICoreWebView2*, LPCWSTR);
HRESULT (STDMETHODCALLTYPE *OpenDevToolsWindow)(ICoreWebView2*);
HRESULT (STDMETHODCALLTYPE *add_ContainsFullScreenElementChanged)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_ContainsFullScreenElementChanged)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *get_ContainsFullScreenElement)(ICoreWebView2*, BOOL*);
HRESULT (STDMETHODCALLTYPE *add_WebResourceRequested)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_WebResourceRequested)(ICoreWebView2*, EventRegistrationToken);
HRESULT (STDMETHODCALLTYPE *AddWebResourceRequestedFilter)(ICoreWebView2*, LPCWSTR, int);
HRESULT (STDMETHODCALLTYPE *RemoveWebResourceRequestedFilter)(ICoreWebView2*, LPCWSTR, int);
HRESULT (STDMETHODCALLTYPE *add_WindowCloseRequested)(ICoreWebView2*, void*, EventRegistrationToken*);
HRESULT (STDMETHODCALLTYPE *remove_WindowCloseRequested)(ICoreWebView2*, EventRegistrationToken);
} ICoreWebView2Vtbl;
struct ICoreWebView2 { const ICoreWebView2Vtbl *lpVtbl; };
// ICoreWebView2Settings vtable
typedef struct ICoreWebView2SettingsVtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(ICoreWebView2Settings*, REFIID, void**);
ULONG (STDMETHODCALLTYPE *AddRef)(ICoreWebView2Settings*);
ULONG (STDMETHODCALLTYPE *Release)(ICoreWebView2Settings*);
HRESULT (STDMETHODCALLTYPE *get_IsScriptEnabled)(ICoreWebView2Settings*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_IsScriptEnabled)(ICoreWebView2Settings*, BOOL);
HRESULT (STDMETHODCALLTYPE *get_IsWebMessageEnabled)(ICoreWebView2Settings*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_IsWebMessageEnabled)(ICoreWebView2Settings*, BOOL);
HRESULT (STDMETHODCALLTYPE *get_AreDefaultScriptDialogsEnabled)(ICoreWebView2Settings*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_AreDefaultScriptDialogsEnabled)(ICoreWebView2Settings*, BOOL);
HRESULT (STDMETHODCALLTYPE *get_IsStatusBarEnabled)(ICoreWebView2Settings*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_IsStatusBarEnabled)(ICoreWebView2Settings*, BOOL);
HRESULT (STDMETHODCALLTYPE *get_AreDevToolsEnabled)(ICoreWebView2Settings*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_AreDevToolsEnabled)(ICoreWebView2Settings*, BOOL);
HRESULT (STDMETHODCALLTYPE *get_AreDefaultContextMenusEnabled)(ICoreWebView2Settings*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_AreDefaultContextMenusEnabled)(ICoreWebView2Settings*, BOOL);
HRESULT (STDMETHODCALLTYPE *get_AreHostObjectsAllowed)(ICoreWebView2Settings*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_AreHostObjectsAllowed)(ICoreWebView2Settings*, BOOL);
HRESULT (STDMETHODCALLTYPE *get_IsZoomControlEnabled)(ICoreWebView2Settings*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_IsZoomControlEnabled)(ICoreWebView2Settings*, BOOL);
HRESULT (STDMETHODCALLTYPE *get_IsBuiltInErrorPageEnabled)(ICoreWebView2Settings*, BOOL*);
HRESULT (STDMETHODCALLTYPE *put_IsBuiltInErrorPageEnabled)(ICoreWebView2Settings*, BOOL);
} ICoreWebView2SettingsVtbl;
struct ICoreWebView2Settings { const ICoreWebView2SettingsVtbl *lpVtbl; };
// ICoreWebView2WebMessageReceivedEventArgs vtable
typedef struct ICoreWebView2WebMessageReceivedEventArgsVtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(ICoreWebView2WebMessageReceivedEventArgs*, REFIID, void**);
ULONG (STDMETHODCALLTYPE *AddRef)(ICoreWebView2WebMessageReceivedEventArgs*);
ULONG (STDMETHODCALLTYPE *Release)(ICoreWebView2WebMessageReceivedEventArgs*);
HRESULT (STDMETHODCALLTYPE *get_Source)(ICoreWebView2WebMessageReceivedEventArgs*, LPWSTR*);
HRESULT (STDMETHODCALLTYPE *get_WebMessageAsJson)(ICoreWebView2WebMessageReceivedEventArgs*, LPWSTR*);
HRESULT (STDMETHODCALLTYPE *TryGetWebMessageAsString)(ICoreWebView2WebMessageReceivedEventArgs*, LPWSTR*);
} ICoreWebView2WebMessageReceivedEventArgsVtbl;
struct ICoreWebView2WebMessageReceivedEventArgs { const ICoreWebView2WebMessageReceivedEventArgsVtbl *lpVtbl; };
// ============================================================================
// COM callback handler types
// ============================================================================
typedef struct EnvironmentCompletedHandlerVtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*, REFIID, void**);
ULONG (STDMETHODCALLTYPE *AddRef)(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
ULONG (STDMETHODCALLTYPE *Release)(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
HRESULT (STDMETHODCALLTYPE *Invoke)(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*, HRESULT, ICoreWebView2Environment*);
} EnvironmentCompletedHandlerVtbl;
struct ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler {
const EnvironmentCompletedHandlerVtbl *lpVtbl;
ULONG refCount;
};
typedef struct ControllerCompletedHandlerVtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*, REFIID, void**);
ULONG (STDMETHODCALLTYPE *AddRef)(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*);
ULONG (STDMETHODCALLTYPE *Release)(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*);
HRESULT (STDMETHODCALLTYPE *Invoke)(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*, HRESULT, ICoreWebView2Controller*);
} ControllerCompletedHandlerVtbl;
struct ICoreWebView2CreateCoreWebView2ControllerCompletedHandler {
const ControllerCompletedHandlerVtbl *lpVtbl;
ULONG refCount;
};
typedef struct WebMessageReceivedHandlerVtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(ICoreWebView2WebMessageReceivedEventHandler*, REFIID, void**);
ULONG (STDMETHODCALLTYPE *AddRef)(ICoreWebView2WebMessageReceivedEventHandler*);
ULONG (STDMETHODCALLTYPE *Release)(ICoreWebView2WebMessageReceivedEventHandler*);
HRESULT (STDMETHODCALLTYPE *Invoke)(ICoreWebView2WebMessageReceivedEventHandler*, ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs*);
} WebMessageReceivedHandlerVtbl;
struct ICoreWebView2WebMessageReceivedEventHandler {
const WebMessageReceivedHandlerVtbl *lpVtbl;
ULONG refCount;
};
// ============================================================================
// WebView2 globals
// ============================================================================
static HWND g_webviewHwnd = NULL;
static ICoreWebView2Environment *g_webviewEnv = NULL;
static ICoreWebView2Controller *g_webviewController = NULL;
static ICoreWebView2 *g_webviewView = NULL;
static char g_pendingView[16] = "";
static BOOL g_webviewWindowShown = FALSE;
typedef HRESULT (STDAPICALLTYPE *PFN_CreateCoreWebView2EnvironmentWithOptions)(
LPCWSTR browserExecutableFolder, LPCWSTR userDataFolder, void* options,
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* handler);
static PFN_CreateCoreWebView2EnvironmentWithOptions fnCreateEnvironment = NULL;
static WCHAR g_extractedDllPath[MAX_PATH] = {0};
// Function prototypes
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void InitTrayIcon(HWND hwnd);
void CreateContextMenu();
BOOL LoadConfigFromRegistry();
void SaveConfigToRegistry();
BOOL IsFirstLaunch();
void MarkAsConfigured();
void LoadConfigFromIni(const char* iniPath);
void ApplyConfiguration();
void ShowConfigDialog(HWND hwndParent);
void ShowHistoryDialog(HWND hwndParent);
void UpdateStatus(ApiResult result, const char* message);
void RefreshStatus();
DWORD WINAPI RefreshThread(LPVOID param);
void SetIcon(HICON icon);
void CALLBACK TooltipTimer(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);
void CALLBACK RefreshTimer(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);
void ParseXmlResponse(const char* xml, ApiResponse* response);
void ExitApplication(HWND hwnd);
void UpdateTooltip();
void SetRefreshInterval(int seconds, BOOL isUserSetting);
void CaptureCurrentDisplaySettings();
BOOL HasDisplaySettingsChanged();
void RefreshTrayIconForNewResolution();
void LogMessage(const char* format, ...);
void CheckLogFileSize();
DWORD WINAPI ValidateUrlThread(LPVOID param);
const char* ApiResultToString(ApiResult r);
void InitHistoryBuffer(int capacity);
void AddHistoryEntry(ApiResult oldResult, const char* oldMsg, ApiResult newResult, const char* newMsg);
HistoryEntry* GetHistoryEntry(int displayIndex);
void FreeHistoryBuffer(void);
void SaveHistoryToRegistry(void);
void LoadHistoryFromRegistry(void);
static void ShowWebViewDialog(const char* view, int width, int height);
// Logging function: writes to ProgramData\APIMonitor.log with timestamp and thread ID
void LogMessage(const char* format, ...) {
// Skip logging if disabled
if (!configLoggingEnabled) {
return;
}
EnterCriticalSection(&logCriticalSection);
// Check log file size before writing (limit to ~10MB)
CheckLogFileSize();
FILE* logFile = fopen(logFilePath, "a");
if (!logFile) {
LeaveCriticalSection(&logCriticalSection);
return;
}
// Timestamp
SYSTEMTIME st;
GetLocalTime(&st);
fprintf(logFile, "[%04d-%02d-%02d %02d:%02d:%02d] [TID:%lu] ",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond,
GetCurrentThreadId());
// Message
va_list args;
va_start(args, format);
vfprintf(logFile, format, args);
va_end(args);
fprintf(logFile, "\n");
fclose(logFile);
LeaveCriticalSection(&logCriticalSection);
}
void CheckLogFileSize() {
FILE* f = fopen(logFilePath, "r");
if (!f) return;
fseek(f, 0, SEEK_END);
long size = ftell(f);
fclose(f);
// If larger than 10MB, truncate
if (size > 10 * 1024 * 1024) {
fclose(fopen(logFilePath, "w"));
LogMessage("Log file exceeded 10MB, restarted.");
}
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
// Initialize logging system
InitializeCriticalSection(&logCriticalSection);
// Get ProgramData folder for logging
char programDataPath[MAX_PATH];
if (SHGetFolderPathA(NULL, CSIDL_COMMON_APPDATA, NULL, 0, programDataPath) == S_OK) {
strcpy(logFilePath, programDataPath);
strcat(logFilePath, "\\APIMonitor");
CreateDirectoryA(logFilePath, NULL);
strcat(logFilePath, "\\APIMonitor.log");
} else {
// Fallback to executable directory
char exePath[MAX_PATH];
GetModuleFileNameA(NULL, exePath, MAX_PATH);
char* lastSlash = strrchr(exePath, '\\');
if (lastSlash) *lastSlash = '\0';
strcpy(logFilePath, exePath);
strcat(logFilePath, "\\APIMonitor.log");
}
LogMessage("=== Application starting (Version: APIMonitor/1.0) ===");
// Single instance check
g_hMutex = CreateMutexA(NULL, TRUE, "Global\\APIMonitor_SingleInstance_Mutex");
if (GetLastError() == ERROR_ALREADY_EXISTS) {
LogMessage("ERROR: Another instance is already running. Exiting.");
MessageBoxA(NULL,
"Only one copy of the API monitor can be running at any given time.",
"API Monitor Already Running",
MB_OK | MB_ICONINFORMATION);
if (g_hMutex) CloseHandle(g_hMutex);
DeleteCriticalSection(&logCriticalSection);
return 0;
}
LogMessage("Single instance check passed.");
g_hInstance = hInstance;
// Check if this is a first launch (no Configured flag in registry)
BOOL firstLaunch = IsFirstLaunch();
// Try loading configuration from registry
BOOL loadedFromRegistry = LoadConfigFromRegistry();
// If registry was empty, try INI migration
if (!loadedFromRegistry) {
char iniPath[MAX_PATH];
GetModuleFileNameA(NULL, iniPath, MAX_PATH);
char* lastSlash = strrchr(iniPath, '\\');
if (lastSlash) *lastSlash = '\0';
strcat(iniPath, "\\config.ini");
LoadConfigFromIni(iniPath);
SaveConfigToRegistry();
LogMessage("Migrated configuration from INI to registry.");
}
LogMessage("Configuration loaded: URL=%s, Interval=%d, Logging=%s, HistoryLimit=%d",
configApiUrl, configRefreshInterval, configLoggingEnabled ? "enabled" : "disabled", configHistoryLimit);
// Initialize history buffer
InitHistoryBuffer(configHistoryLimit);
LoadHistoryFromRegistry();
// Load icons
hIconEmpty = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDI_EMPTY),
IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
hIconSuccess = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDI_SUCCESS),
IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
hIconFail = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDI_FAIL),
IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
hIconBlank = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDI_BLANK),
IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
if (!hIconEmpty || !hIconSuccess || !hIconFail || !hIconBlank) {
char errMsg[256];
sprintf(errMsg, "Failed to load embedded icons. Error: %lu", GetLastError());
LogMessage("ERROR: %s", errMsg);
MessageBoxA(NULL, errMsg, "Icon Loading Error", MB_OK | MB_ICONERROR);
DeleteCriticalSection(&logCriticalSection);
return 1;
}
LogMessage("Icons loaded successfully.");
// Capture initial display settings
CaptureCurrentDisplaySettings();
// Create window class
WNDCLASSEXA wc = {0};
wc.cbSize = sizeof(WNDCLASSEXA);
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = "APIMonitorClass";
if (!RegisterClassExA(&wc)) {
LogMessage("ERROR: Failed to register window class. Error: %lu", GetLastError());
MessageBoxA(NULL, "Failed to register window class", "Error", MB_OK | MB_ICONERROR);
DeleteCriticalSection(&logCriticalSection);
return 1;
}
// Create hidden message window
HWND hwnd = CreateWindowExA(0, "APIMonitorClass", "APIMonitor", 0,
0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL);
if (!hwnd) {
LogMessage("ERROR: Failed to create window. Error: %lu", GetLastError());
MessageBoxA(NULL, "Failed to create window", "Error", MB_OK | MB_ICONERROR);
DeleteCriticalSection(&logCriticalSection);
return 1;
}
g_hwnd = hwnd;
LogMessage("Message window created.");
// Initialize tray icon
InitTrayIcon(hwnd);
LogMessage("Tray icon initialized.");
// Create context menu
CreateContextMenu();
// Set up timers
timerTooltip = SetTimer(hwnd, 2, 1000, TooltipTimer);
// Initial check
LogMessage("Performing initial API check.");
RefreshStatus();
// Start refresh timer
timerRefresh = SetTimer(hwnd, 1, configRefreshInterval * 1000, RefreshTimer);
LogMessage("Refresh timer started with %d second interval.", configRefreshInterval);
// On first launch, post message to show config dialog after message loop starts
if (firstLaunch) {
LogMessage("First launch detected, will show configuration dialog.");
MarkAsConfigured();
PostMessage(hwnd, WM_SHOW_FIRST_CONFIG, 0, 0);
}
// Message loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
ExitApplication(hwnd);
DeleteCriticalSection(&logCriticalSection);
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_SHOW_FIRST_CONFIG:
ShowConfigDialog(g_hwnd);
break;
case WM_TRAYICON:
if (lParam == WM_RBUTTONUP) {
POINT pt;
GetCursorPos(&pt);
SetForegroundWindow(hwnd);
EnableMenuItem(hMenu, ID_TRAY_CONFIGURE, g_webviewHwnd ? MF_GRAYED : MF_ENABLED);
EnableMenuItem(hMenu, ID_TRAY_HISTORY, g_webviewHwnd ? MF_GRAYED : MF_ENABLED);
TrackPopupMenu(hMenu, TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, NULL);
LogMessage("Context menu opened at position (%ld, %ld).", pt.x, pt.y);
} else if (lParam == WM_LBUTTONDBLCLK) {
LogMessage("Tray icon double-clicked. Triggering manual refresh.");
RefreshStatus();
}
break;
case WM_DISPLAYCHANGE:
Sleep(1000);
if (HasDisplaySettingsChanged()) {
LogMessage("Display settings changed. Screen: %dx%d, DPI: %dx%d -> %dx%d, DPI: %dx%d",
lastScreenWidth, lastScreenHeight, lastDpiX, lastDpiY,
GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
GetDeviceCaps(GetDC(NULL), LOGPIXELSX), GetDeviceCaps(GetDC(NULL), LOGPIXELSY));
RefreshTrayIconForNewResolution();
CaptureCurrentDisplaySettings();
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case ID_TRAY_EXIT:
LogMessage("User selected Exit from context menu.");
ExitApplication(hwnd);
break;
case ID_TRAY_REFRESH:
LogMessage("User selected Refresh from context menu.");
RefreshStatus();
break;
case ID_TRAY_CONFIGURE:
LogMessage("User selected Configure from context menu.");
ShowConfigDialog(g_hwnd);
break;
case ID_TRAY_HISTORY:
LogMessage("User selected History from context menu.");
ShowHistoryDialog(g_hwnd);
break;
}
break;
case WM_TIMER:
if (wParam == 1) RefreshTimer(hwnd, uMsg, wParam, 0);
else if (wParam == 2) TooltipTimer(hwnd, uMsg, wParam, 0);
break;
case WM_DESTROY:
LogMessage("Window destroyed.");
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
void InitTrayIcon(HWND hwnd) {
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.hWnd = hwnd;
nid.uID = 1;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.uCallbackMessage = WM_TRAYICON;
nid.hIcon = hIconEmpty;
strcpy(nid.szTip, "API Monitor - Initializing...");
Shell_NotifyIconA(NIM_ADD, &nid);
LogMessage("Tray icon added to system tray.");
}
void CreateContextMenu() {
hMenu = CreatePopupMenu();
AppendMenuA(hMenu, MF_STRING, ID_TRAY_REFRESH, "Refresh");
AppendMenuA(hMenu, MF_STRING, ID_TRAY_HISTORY, "History");
AppendMenuA(hMenu, MF_SEPARATOR, 0, NULL);
AppendMenuA(hMenu, MF_STRING, ID_TRAY_CONFIGURE, "Configure");
AppendMenuA(hMenu, MF_SEPARATOR, 0, NULL);
AppendMenuA(hMenu, MF_STRING, ID_TRAY_EXIT, "Exit");
LogMessage("Context menu created.");
}
// --- Registry-based configuration ---
BOOL LoadConfigFromRegistry() {
HKEY hKey;
LONG result = RegOpenKeyExA(HKEY_CURRENT_USER, REG_KEY_PATH, 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS) {
return FALSE;
}
DWORD type, size;
// Read ApiUrl (REG_SZ)
size = sizeof(configApiUrl);
if (RegQueryValueExA(hKey, REG_VALUE_URL, NULL, &type, (LPBYTE)configApiUrl, &size) != ERROR_SUCCESS
|| type != REG_SZ) {
strcpy(configApiUrl, "http://example.com/api/status");
}
// Read RefreshInterval (REG_DWORD)
DWORD dwInterval = 60;
size = sizeof(dwInterval);
if (RegQueryValueExA(hKey, REG_VALUE_INTERVAL, NULL, &type, (LPBYTE)&dwInterval, &size) == ERROR_SUCCESS
&& type == REG_DWORD) {
configRefreshInterval = (int)dwInterval;
}
// Read LoggingEnabled (REG_DWORD)
DWORD dwLogging = 1;
size = sizeof(dwLogging);
if (RegQueryValueExA(hKey, REG_VALUE_LOGGING, NULL, &type, (LPBYTE)&dwLogging, &size) == ERROR_SUCCESS
&& type == REG_DWORD) {
configLoggingEnabled = (BOOL)dwLogging;
}
// Read HistoryLimit (REG_DWORD)
DWORD dwHistoryLimit = 100;
size = sizeof(dwHistoryLimit);
if (RegQueryValueExA(hKey, REG_VALUE_HISTORY_LIMIT, NULL, &type, (LPBYTE)&dwHistoryLimit, &size) == ERROR_SUCCESS
&& type == REG_DWORD) {
configHistoryLimit = (int)dwHistoryLimit;
if (configHistoryLimit < 10) configHistoryLimit = 10;
if (configHistoryLimit > 10000) configHistoryLimit = 10000;
}
RegCloseKey(hKey);
return TRUE;
}
void SaveConfigToRegistry() {
HKEY hKey;
DWORD disposition;
LONG result = RegCreateKeyExA(HKEY_CURRENT_USER, REG_KEY_PATH, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &disposition);
if (result != ERROR_SUCCESS) {
LogMessage("ERROR: Failed to create/open registry key. Error: %lu", result);
return;
}
// Write ApiUrl (REG_SZ)
RegSetValueExA(hKey, REG_VALUE_URL, 0, REG_SZ,
(const BYTE*)configApiUrl, (DWORD)(strlen(configApiUrl) + 1));
// Write RefreshInterval (REG_DWORD)
DWORD dwInterval = (DWORD)configRefreshInterval;
RegSetValueExA(hKey, REG_VALUE_INTERVAL, 0, REG_DWORD,
(const BYTE*)&dwInterval, sizeof(dwInterval));
// Write LoggingEnabled (REG_DWORD)
DWORD dwLogging = (DWORD)configLoggingEnabled;
RegSetValueExA(hKey, REG_VALUE_LOGGING, 0, REG_DWORD,
(const BYTE*)&dwLogging, sizeof(dwLogging));
// Write HistoryLimit (REG_DWORD)
DWORD dwHistoryLimit = (DWORD)configHistoryLimit;
RegSetValueExA(hKey, REG_VALUE_HISTORY_LIMIT, 0, REG_DWORD,
(const BYTE*)&dwHistoryLimit, sizeof(dwHistoryLimit));
RegCloseKey(hKey);
LogMessage("Configuration saved to registry: URL=%s, Interval=%d, Logging=%s, HistoryLimit=%d",
configApiUrl, configRefreshInterval, configLoggingEnabled ? "enabled" : "disabled", configHistoryLimit);
}
BOOL IsFirstLaunch() {
HKEY hKey;
LONG result = RegOpenKeyExA(HKEY_CURRENT_USER, REG_KEY_PATH, 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS) {
return TRUE;
}
DWORD type, size;
DWORD dwConfigured = 0;
size = sizeof(dwConfigured);
result = RegQueryValueExA(hKey, REG_VALUE_CONFIGURED, NULL, &type, (LPBYTE)&dwConfigured, &size);
RegCloseKey(hKey);
if (result != ERROR_SUCCESS || type != REG_DWORD || dwConfigured == 0) {
return TRUE;
}
return FALSE;
}
void MarkAsConfigured() {
HKEY hKey;
DWORD disposition;
LONG result = RegCreateKeyExA(HKEY_CURRENT_USER, REG_KEY_PATH, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &disposition);
if (result != ERROR_SUCCESS) {
LogMessage("ERROR: Failed to create/open registry key for MarkAsConfigured. Error: %lu", result);
return;
}
DWORD dwConfigured = 1;
RegSetValueExA(hKey, REG_VALUE_CONFIGURED, 0, REG_DWORD,
(const BYTE*)&dwConfigured, sizeof(dwConfigured));
RegCloseKey(hKey);
}
// INI fallback for one-time migration from old config.ini
void LoadConfigFromIni(const char* iniPath) {
GetPrivateProfileStringA("General", "ApiUrl", "http://example.com/api/status",
configApiUrl, sizeof(configApiUrl), iniPath);
configRefreshInterval = GetPrivateProfileIntA("General", "RefreshInterval", 60, iniPath);
configLoggingEnabled = (BOOL)GetPrivateProfileIntA("General", "LoggingEnabled", 1, iniPath);
}
// --- History ring buffer ---
const char* ApiResultToString(ApiResult r) {
switch (r) {
case RESULT_NONE: return "-";
case RESULT_SUCCESS: return "Success";
case RESULT_FAIL: return "Fail";
case RESULT_ERROR: return "Error";
case RESULT_INVALID: return "Invalid";
default: return "Unknown";
}
}
void InitHistoryBuffer(int capacity) {
if (capacity < 10) capacity = 10;
if (capacity > 10000) capacity = 10000;
if (historyBuffer && capacity == historyCapacity) return;
HistoryEntry* newBuf = (HistoryEntry*)calloc(capacity, sizeof(HistoryEntry));
if (!newBuf) return;
// Preserve most recent entries on resize
if (historyBuffer && historyCount > 0) {
int toCopy = historyCount < capacity ? historyCount : capacity;
for (int i = 0; i < toCopy; i++) {
// GetHistoryEntry(0) = most recent, so copy in reverse display order
HistoryEntry* src = GetHistoryEntry(i);
if (src) {
newBuf[(toCopy - 1 - i) % capacity] = *src;
}
}
historyHead = toCopy % capacity;
historyCount = toCopy;
} else {
historyHead = 0;
historyCount = 0;
}
free(historyBuffer);
historyBuffer = newBuf;
historyCapacity = capacity;
}
void AddHistoryEntry(ApiResult oldResult, const char* oldMsg, ApiResult newResult, const char* newMsg) {
if (!historyBuffer || historyCapacity <= 0) return;
HistoryEntry* entry = &historyBuffer[historyHead];
GetLocalTime(&entry->timestamp);
entry->oldResult = oldResult;
entry->newResult = newResult;
strncpy(entry->oldMessage, oldMsg ? oldMsg : "", sizeof(entry->oldMessage) - 1);
entry->oldMessage[sizeof(entry->oldMessage) - 1] = '\0';
strncpy(entry->newMessage, newMsg ? newMsg : "", sizeof(entry->newMessage) - 1);
entry->newMessage[sizeof(entry->newMessage) - 1] = '\0';
historyHead = (historyHead + 1) % historyCapacity;
if (historyCount < historyCapacity) historyCount++;
}
HistoryEntry* GetHistoryEntry(int displayIndex) {
if (!historyBuffer || displayIndex < 0 || displayIndex >= historyCount) return NULL;
// displayIndex 0 = most recent
int bufIdx = (historyHead - 1 - displayIndex + historyCapacity) % historyCapacity;
return &historyBuffer[bufIdx];
}
void FreeHistoryBuffer(void) {
free(historyBuffer);
historyBuffer = NULL;
historyCapacity = 0;
historyCount = 0;
historyHead = 0;
}
void SaveHistoryToRegistry(void) {
HKEY hKey;
DWORD disposition;
LONG result = RegCreateKeyExA(HKEY_CURRENT_USER, REG_KEY_PATH, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &disposition);
if (result != ERROR_SUCCESS) {
LogMessage("ERROR: Failed to open registry for history save. Error: %lu", result);
return;
}
if (historyCount == 0 || !historyBuffer) {
DWORD zero = 0;
RegSetValueExA(hKey, REG_VALUE_HISTORY_COUNT, 0, REG_DWORD,
(const BYTE*)&zero, sizeof(zero));
RegDeleteValueA(hKey, REG_VALUE_HISTORY_DATA);
RegCloseKey(hKey);
LogMessage("History saved to registry: 0 entries.");
return;
}
// Serialize most-recent-first
DWORD dataSize = (DWORD)(historyCount * sizeof(HistoryEntry));
BYTE* data = (BYTE*)malloc(dataSize);
if (!data) {
RegCloseKey(hKey);
return;
}
for (int i = 0; i < historyCount; i++) {
HistoryEntry* entry = GetHistoryEntry(i); // 0 = most recent
if (entry) {
memcpy(data + i * sizeof(HistoryEntry), entry, sizeof(HistoryEntry));
}
}
DWORD dwCount = (DWORD)historyCount;
RegSetValueExA(hKey, REG_VALUE_HISTORY_COUNT, 0, REG_DWORD,
(const BYTE*)&dwCount, sizeof(dwCount));
RegSetValueExA(hKey, REG_VALUE_HISTORY_DATA, 0, REG_BINARY,
data, dataSize);
free(data);
RegCloseKey(hKey);
LogMessage("History saved to registry: %d entries.", historyCount);
}
void LoadHistoryFromRegistry(void) {
HKEY hKey;
LONG result = RegOpenKeyExA(HKEY_CURRENT_USER, REG_KEY_PATH, 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS) return;
DWORD type, size;
// Read count
DWORD dwCount = 0;
size = sizeof(dwCount);
if (RegQueryValueExA(hKey, REG_VALUE_HISTORY_COUNT, NULL, &type, (LPBYTE)&dwCount, &size) != ERROR_SUCCESS
|| type != REG_DWORD || dwCount == 0) {
RegCloseKey(hKey);
return;
}
// Read data size first
size = 0;
if (RegQueryValueExA(hKey, REG_VALUE_HISTORY_DATA, NULL, &type, NULL, &size) != ERROR_SUCCESS
|| type != REG_BINARY) {
RegCloseKey(hKey);
return;
}
// Validate size matches count
if (size != dwCount * sizeof(HistoryEntry)) {
LogMessage("WARNING: History data size mismatch (expected %lu, got %lu). Discarding.",
(unsigned long)(dwCount * sizeof(HistoryEntry)), (unsigned long)size);
RegCloseKey(hKey);
return;
}
BYTE* data = (BYTE*)malloc(size);
if (!data) {
RegCloseKey(hKey);
return;
}
if (RegQueryValueExA(hKey, REG_VALUE_HISTORY_DATA, NULL, &type, data, &size) != ERROR_SUCCESS) {
free(data);
RegCloseKey(hKey);
return;
}
RegCloseKey(hKey);
// Cap to current buffer capacity
int toLoad = (int)dwCount;
if (toLoad > historyCapacity) toLoad = historyCapacity;
// Data is stored most-recent-first; insert oldest-first so ring buffer order is correct
for (int i = toLoad - 1; i >= 0; i--) {
HistoryEntry* src = (HistoryEntry*)(data + i * sizeof(HistoryEntry));
HistoryEntry* dst = &historyBuffer[historyHead];
*dst = *src;
historyHead = (historyHead + 1) % historyCapacity;
if (historyCount < historyCapacity) historyCount++;
}
free(data);
LogMessage("History loaded from registry: %d entries.", toLoad);
}
void ApplyConfiguration() {
if (g_hwnd) {
if (timerRefresh) KillTimer(g_hwnd, 1);
timerRefresh = SetTimer(g_hwnd, 1, configRefreshInterval * 1000, RefreshTimer);
}
LogMessage("Configuration applied: URL=%s, Interval=%d, Logging=%s",
configApiUrl, configRefreshInterval, configLoggingEnabled ? "enabled" : "disabled");
}
// --- Configuration dialog ---
// Helper: launch a validation thread for the given URL
static void StartValidation(HWND hDlg, const char* url) {
LONG gen = InterlockedIncrement(&g_validateGeneration);