-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_args_debugger.cpp
More file actions
2102 lines (1834 loc) · 78.3 KB
/
cli_args_debugger.cpp
File metadata and controls
2102 lines (1834 loc) · 78.3 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
//
// cli_args_debugger.cpp
//
// Build Requirements:
// ------------------
// 1. Visual Studio 2022 (Community Edition or higher)
// - Install the following workloads:
// * "Desktop development with C++"
// * "Universal Windows Platform development"
// 2. Required components:
// - Windows 10/11 SDK (latest version)
// - Visual C++ tools for CMake
// 3. DirectX Dependencies:
// - DirectX SDK (June 2010) for legacy components, or a modern Windows SDK
//
// Additionally: Place the files qrcodegen.hpp and qrcodegen.cpp (from QrCodeGen by Nayuki)
// in the same directory as this file and add them to your project.
// ------------------
#ifndef UNICODE
#define UNICODE
#define _UNICODE
#endif
#include <DirectXMath.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <audioclient.h>
#include <avrt.h> // For AvSetMmThreadCharacteristics
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <ctime>
#include <d2d1.h>
#include <d3d11.h>
#include <d3dcompiler.h>
#include <dwrite.h>
#include <excpt.h> // For SEH exception handling
#include <fstream>
#include <iomanip> // For setw/setfill
#include <knownfolders.h>
#include <mmdeviceapi.h>
#include <share.h> // For _wfsopen share flags
#include <shlobj.h>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include <windows.h>
#include <mmsystem.h> // For PlaySound
#include <wrl/client.h>
#include <psapi.h> // For GetProcessMemoryInfo
// Debug memory leak detection
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
// Safe string functions for buffer overflow prevention
#include <strsafe.h>
#define INITGUID // Required by /permissive- for GUID initialization
#include <functiondiscoverykeys_devpkey.h> // For PKEY_Device_FriendlyName
#include <ks.h> // For GUID constants
#include <ksmedia.h> // For KSDATAFORMAT_SUBTYPE constants
#include <propsys.h> // IPropertyStore, PKEY_*
#include <propvarutil.h> // PropVariant helpers
#pragma comment(lib, "propsys") // + linker
// NTSTATUS and RTL_OSVERSIONINFOW are already defined in Windows SDK
// No need to redefine them
// Link with required libraries
#pragma comment(lib, "d2d1")
#pragma comment(lib, "dwrite")
#pragma comment(lib, "d3d11")
#pragma comment(lib, "d3dcompiler")
#pragma comment(lib, "ole32")
#pragma comment(lib, "avrt")
#pragma comment(lib, "user32") // For window functions
#pragma comment(lib, "shell32") // For SHGetKnownFolderPath
#pragma comment(lib, "gdi32") // For GDI functions
#pragma comment(lib, "winmm") // For PlaySound
#pragma comment(lib, "psapi") // For GetProcessMemoryInfo
// Include QrCodeGen (ensure that qrcodegen.hpp and qrcodegen.cpp are in your project)
#include "qrcodegen.hpp"
using qrcodegen::QrCode;
// Use Microsoft::WRL::ComPtr for COM object management
using Microsoft::WRL::ComPtr;
// Helper macro that calls a DirectX function and throws an exception on failure.
#define DX_CALL(expr, msg) \
do \
{ \
auto hr = (expr); \
if (FAILED(hr)) \
throw std::runtime_error(msg); \
} while (0)
// ===========================================================================
// LOGGING SUPPORT
// ===========================================================================
// Simple header-only logger that writes UTF-16 text to a file
// located next to the executable (CloudStreamingArgsDebugger.log).
//
// • InitLogger() – call once from wWinMain right after COM is up.
// • Log(L"text") – append one line with local‑time prefix.
// • ShowLogs() – read the file and place it into loaded_data_ so it is
// rendered in the right‑upper corner (triggered via "logs")
// Global variables for logging (exported for tests)
FILE* g_log_file = nullptr; // File handle for the log file
std::wstring g_logPath; // Path to the log file
namespace // anonymous, internal
{
CRITICAL_SECTION g_log_cs; // Critical section for thread safety
} // namespace
void InitLogger()
{
PWSTR appdata_path = nullptr;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &appdata_path);
if (SUCCEEDED(hr))
{
g_logPath.assign(appdata_path);
CoTaskMemFree(appdata_path);
g_logPath += L"\\CloudStreamingArgsDebugger\\debug.log";
std::wstring dir = g_logPath.substr(0, g_logPath.find_last_of(L"\\"));
CreateDirectoryW(dir.c_str(), nullptr);
}
else
{
wchar_t exePath[MAX_PATH] = L"\0";
GetModuleFileNameW(nullptr, exePath, MAX_PATH);
g_logPath.assign(exePath);
size_t pos = g_logPath.find_last_of(L"\\/");
if (pos != std::wstring::npos)
g_logPath.erase(pos + 1);
g_logPath += L"CloudStreamingArgsDebugger.log";
}
// Open file in append mode with UTF-16LE encoding
// Use _SH_DENYNO to allow other handles to read the file while we have it open
g_log_file = _wfsopen(g_logPath.c_str(), L"a+, ccs=UTF-16LE", _SH_DENYNO);
// If this is a new file, write BOM (Byte Order Mark)
if (g_log_file && ftell(g_log_file) == 0)
{
fputwc(0xFEFF, g_log_file); // UTF-16LE BOM
}
// Initialize critical section for thread-safe logging
InitializeCriticalSection(&g_log_cs);
}
void Log(const std::wstring& text)
{
if (!g_log_file)
return;
// Lock the critical section before accessing the file
EnterCriticalSection(&g_log_cs);
SYSTEMTIME st;
GetLocalTime(&st);
// Format log entry with timestamp
std::wstring entry = L"[";
entry += std::to_wstring(st.wYear) + L"-";
// Month with padding
if (st.wMonth < 10)
entry += L"0";
entry += std::to_wstring(st.wMonth) + L"-";
// Day with padding
if (st.wDay < 10)
entry += L"0";
entry += std::to_wstring(st.wDay) + L" ";
// Hour with padding
if (st.wHour < 10)
entry += L"0";
entry += std::to_wstring(st.wHour) + L":";
// Minute with padding
if (st.wMinute < 10)
entry += L"0";
entry += std::to_wstring(st.wMinute) + L":";
// Second with padding
if (st.wSecond < 10)
entry += L"0";
entry += std::to_wstring(st.wSecond) + L"] ";
// Add the actual log message
entry += text + L"\n";
// Write to file and flush
fputws(entry.c_str(), g_log_file);
fflush(g_log_file);
// Unlock the critical section
LeaveCriticalSection(&g_log_cs);
}
// Simple log function for SEH wrapper to use
// Exported for seh_wrapper.cpp
void LogSEH(const wchar_t* message)
{
if (message)
{
// Convert C-string to wstring for main Log function
Log(std::wstring(message));
// Also output to debug console for immediate visibility
OutputDebugStringW(message);
OutputDebugStringW(L"\n");
}
}
// Helper function: robust conversion from std::wstring to std::string using WideCharToMultiByte (UTF-8)
std::string wstring_to_string(const std::wstring& wstr)
{
if (wstr.empty())
return std::string();
// Use the string length so embedded null characters are preserved
int size_needed =
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), static_cast<int>(wstr.size()), &strTo[0], size_needed, nullptr,
nullptr);
return strTo;
}
#include "cli_args_display.hpp"
constexpr const wchar_t* kWindowClassName = L"CloudStreamingArgsDebuggerClass";
constexpr const wchar_t* kWindowCaption = L"Cloud Streaming Args Debugger";
// Description text for the window
const std::vector<std::wstring> kDescriptionLines = {
L"Cloud Streaming Args Debugger", L"This utility displays all command-line arguments for cloud streaming applications.",
L"Type 'exit', 'save', 'read', 'logs', 'path', 'sound' or 'memory' and press Enter to execute commands."};
constexpr float kMargin = 20.0f;
constexpr float kLineHeight = 30.0f;
// Structures for 3D rendering
struct SimpleVertex
{
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT3 color;
};
struct ConstantBufferData
{
DirectX::XMMATRIX world_view_projection;
};
class ArgumentDebuggerWindow;
LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
ArgumentDebuggerWindow* g_app_instance = nullptr;
// External SEH wrapper function (defined in seh_wrapper.cpp)
extern "C" DWORD WINAPI RawAudioThreadWithSEH(LPVOID param) noexcept;
// Global function for unhandled exception filter - renamed to avoid conflict
LONG WINAPI AppUnhandledExceptionFilter(EXCEPTION_POINTERS* ep)
{
Log(L"Unhandled SEH exception: code=0x" + std::to_wstring(ep->ExceptionRecord->ExceptionCode));
return EXCEPTION_EXECUTE_HANDLER;
}
class ArgumentDebuggerWindow
{
public:
ArgumentDebuggerWindow() = default;
~ArgumentDebuggerWindow()
{
Cleanup();
}
// Throws on failure.
void Initialize(HINSTANCE h_instance, int cmd_show, const std::vector<std::wstring>& args);
int RunMessageLoop();
void OnCharInput(wchar_t ch);
void OnDestroy();
bool is_running() const
{
return is_running_;
}
// Thread implementation with C++ exception handling - public for thread access
DWORD AudioCaptureThreadImpl(LPVOID param);
private:
void InitializeWindow(HINSTANCE h_instance, int cmd_show);
void InitializeDevice();
void CreateDeviceAndSwapChain(UINT width, UINT height);
void CreateRenderTargetView();
void CreateD2DResources();
void CreateShadersAndGeometry();
void InitializeMicrophone();
void PollMicrophone();
void RenderFrame();
void Cleanup();
void UpdateRotation(float delta_time);
// Audio capture thread function with correct calling convention and SEH wrapper
static __declspec(nothrow) DWORD WINAPI AudioCaptureThread(LPVOID param);
private:
// Update QR code – here we add the FPS synchronization logic.
void UpdateQrCode(ULONGLONG current_time);
// Methods for file operations (saving/loading data)
void SaveData();
void ReadData();
// Helper to load entire log file into loaded_data_
void ShowLogs();
// Helper to calculate and cache path information once
void CalculatePathInfo();
// Play telephone-like beeps for 1 minute
void PlayTelephoneBeeps();
// Show memory usage statistics
void ShowMemoryStats();
HWND window_handle_ = nullptr;
bool is_running_ = true;
ULONGLONG last_time_ = 0;
float rotation_angle_ = 0.0f;
std::wstring user_input_;
std::vector<std::wstring> args_;
// New variables for displaying command status and loaded data:
std::wstring command_status_;
std::wstring loaded_data_;
std::wstring loaded_data_title_; // Title for the loaded data section
bool show_paths_ = false; // Flag to control file paths display
bool show_logs_ = false; // Flag to control logs display
// Cached path information to avoid expensive system calls every frame
std::vector<std::pair<std::wstring, std::wstring>> cached_path_items_;
// Variables for FPS and QR code
float current_fps_ = 0.0f;
// Adding a variable for "synchronized" FPS,
// which will be the same as what is shown in the QR code.
int synced_fps_ = 0;
ULONGLONG last_qr_update_time_ = 0;
ComPtr<ID2D1Bitmap> qr_bitmap_;
// Direct2D and DirectWrite objects
ComPtr<ID2D1Factory> d2d_factory_;
ComPtr<ID2D1RenderTarget> d2d_render_target_;
ComPtr<IDWriteFactory> dwrite_factory_;
ComPtr<IDWriteTextFormat> text_format_;
ComPtr<IDWriteTextFormat> small_text_format_; // Smaller font for logs
ComPtr<IDWriteTextFormat> data_text_format_; // Medium font for loaded data
// D2D Brushes - created once and reused
ComPtr<ID2D1SolidColorBrush> white_brush_;
ComPtr<ID2D1SolidColorBrush> green_brush_;
ComPtr<ID2D1SolidColorBrush> yellow_brush_;
// Direct3D objects
ComPtr<ID3D11Device> d3d_device_;
ComPtr<ID3D11DeviceContext> immediate_context_;
ComPtr<IDXGISwapChain> swap_chain_;
ComPtr<ID3D11RenderTargetView> d3d_render_target_view_;
// Shader and geometry objects
ComPtr<ID3D11Buffer> vertex_buffer_;
ComPtr<ID3D11Buffer> index_buffer_;
ComPtr<ID3D11Buffer> constant_buffer_;
ComPtr<ID3D11InputLayout> vertex_layout_;
ComPtr<ID3D11VertexShader> vertex_shader_;
ComPtr<ID3D11PixelShader> pixel_shader_;
// WASAPI
ComPtr<IMMDeviceEnumerator> device_enumerator_;
ComPtr<IMMDevice> capture_device_;
ComPtr<IAudioClient> audio_client_;
ComPtr<IAudioCaptureClient> capture_client_;
WAVEFORMATEX* mix_format_ = nullptr;
HANDLE audio_event_ = nullptr;
HANDLE audio_thread_ = nullptr;
std::atomic<float> mic_level_{0.f}; // 0..1
std::atomic<bool> mic_available_{false};
std::atomic<bool> audio_thread_running_{false}; // Flag for safe thread termination
std::wstring mic_name_; // FriendlyName ("USB Mic (Realtek ...)")
};
#ifndef EXCLUDE_MAIN
int WINAPI wWinMain(HINSTANCE h_instance, HINSTANCE, PWSTR, int cmd_show)
{
#ifdef _DEBUG
// Enable memory leak detection in debug builds
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// Break on allocation number (uncomment to debug specific leak)
// _CrtSetBreakAlloc(123);
#endif
try
{
// Initialize COM once at the start - STA is the safest option for UI thread and D2D
DX_CALL(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED), "COM initialization failed");
InitLogger();
Log(L"Application start");
Log(L"wWinMain: entered");
// Set unhandled exception filter using a regular function
SetUnhandledExceptionFilter(AppUnhandledExceptionFilter);
int argc = 0;
LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
std::vector<std::wstring> args;
if (argv != nullptr)
{
for (int i = 1; i < argc; ++i)
{
args.push_back(argv[i]);
}
LocalFree(argv);
}
ArgumentDebuggerWindow debugger_app;
g_app_instance = &debugger_app;
debugger_app.Initialize(h_instance, cmd_show, args);
int exit_code = debugger_app.RunMessageLoop();
g_app_instance = nullptr;
Log(L"Application exit, code = " + std::to_wstring(exit_code));
Log(L"wWinMain: leaving, exitCode=" + std::to_wstring(exit_code));
// Close the log file and delete critical section
if (g_log_file)
{
fclose(g_log_file);
g_log_file = nullptr;
}
// Delete critical section
DeleteCriticalSection(&g_log_cs);
CoUninitialize();
return exit_code;
}
catch (const std::exception& ex)
{
// Convert char* to wstring for logging
std::wstring wstr(ex.what(), ex.what() + strlen(ex.what()));
Log(L"Unhandled C++ exception");
Log(L"FATAL: " + wstr);
// Close log file before exit
if (g_log_file)
{
fclose(g_log_file);
g_log_file = nullptr;
}
// Delete critical section in exception case as well
DeleteCriticalSection(&g_log_cs);
MessageBoxA(nullptr, ex.what(), "Initialization Error", MB_OK | MB_ICONERROR);
return -1;
}
}
#endif // EXCLUDE_MAIN
void ArgumentDebuggerWindow::Initialize(HINSTANCE h_instance, int cmd_show, const std::vector<std::wstring>& args)
{
args_ = args;
InitializeWindow(h_instance, cmd_show);
InitializeDevice();
}
int ArgumentDebuggerWindow::RunMessageLoop()
{
Log(L"RunMessageLoop: started");
MSG msg = {};
last_time_ = GetTickCount64();
while (is_running_)
{
bool hadMsg = false;
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
hadMsg = true;
if (msg.message == WM_QUIT)
{
Log(L"WM_QUIT received, wParam=" + std::to_wstring(msg.wParam));
is_running_ = false;
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (!hadMsg)
{
// Log only once every 10 seconds to avoid bloating the log file
static ULONGLONG t0 = GetTickCount64();
ULONGLONG now = GetTickCount64();
if (now - t0 > 10000)
{
Log(L"RunMessageLoop: idle");
t0 = now;
}
}
// Frame rate limiting - target 60 FPS
static ULONGLONG lastFrameTime = 0;
ULONGLONG currentFrameTime = GetTickCount64();
const ULONGLONG targetFrameTime = 16; // ~60 FPS (1000ms / 60 = 16.67ms)
if (currentFrameTime - lastFrameTime < targetFrameTime)
{
// Sleep to maintain target frame rate
DWORD sleepTime = static_cast<DWORD>(targetFrameTime - (currentFrameTime - lastFrameTime));
if (sleepTime > 0 && sleepTime < targetFrameTime)
{
Sleep(sleepTime);
}
}
lastFrameTime = GetTickCount64();
try
{
RenderFrame();
}
catch (const std::exception& ex)
{
// Safe string conversion with bounds checking
size_t msgLen = strnlen_s(ex.what(), 1024); // Limit to 1KB
std::wstring wideMsg;
if (msgLen > 0)
{
wideMsg = std::wstring(ex.what(), ex.what() + msgLen);
}
Log(L"Render error: " + wideMsg);
MessageBoxA(window_handle_, ex.what(), "Render error", MB_ICONERROR);
PostQuitMessage(1);
break;
}
catch (...)
{
Log(L"Unknown exception in render loop - terminating");
MessageBoxW(window_handle_, L"Unknown error occurred", L"Error", MB_ICONERROR);
PostQuitMessage(1);
break;
}
}
Log(L"RunMessageLoop: finished");
return static_cast<int>(msg.wParam);
}
// Keyboard input handling: added support for "save", "read" and "logs" commands
void ArgumentDebuggerWindow::OnCharInput(wchar_t ch)
{
if (ch == VK_RETURN)
{
if (_wcsicmp(user_input_.c_str(), L"exit") == 0)
{
Log(L"Command: exit");
PostQuitMessage(0);
is_running_ = false;
}
else if (_wcsicmp(user_input_.c_str(), L"save") == 0)
{
Log(L"Command: save");
SaveData();
}
else if (_wcsicmp(user_input_.c_str(), L"read") == 0)
{
Log(L"Command: read");
ReadData();
if (!loaded_data_.empty())
{
loaded_data_title_ = L"Save File Contents:";
show_logs_ = true; // Show the data when read succeeds
}
}
else if (_wcsicmp(user_input_.c_str(), L"logs") == 0)
{
Log(L"Command: logs");
show_logs_ = !show_logs_;
if (show_logs_)
{
ShowLogs();
loaded_data_title_ = L"Log File Contents:";
command_status_ = L"Logs enabled.";
}
else
{
loaded_data_.clear();
loaded_data_title_.clear();
command_status_ = L"Logs disabled.";
}
}
else if (_wcsicmp(user_input_.c_str(), L"path") == 0)
{
Log(L"Command: path");
show_paths_ = !show_paths_;
if (show_paths_)
{
// Calculate path information once when enabling
CalculatePathInfo();
command_status_ = L"File paths enabled.";
}
else
{
// Clear cached data when disabling
cached_path_items_.clear();
command_status_ = L"File paths disabled.";
}
}
else if (_wcsicmp(user_input_.c_str(), L"sound") == 0)
{
Log(L"Command: sound");
command_status_ = L"Playing low-frequency beeps (300Hz) for 1 minute...";
PlayTelephoneBeeps();
}
else if (_wcsicmp(user_input_.c_str(), L"memory") == 0)
{
Log(L"Command: memory");
ShowMemoryStats();
}
else
{
command_status_ = L"Unknown command.";
}
user_input_.clear();
}
else if (ch == VK_BACK)
{
if (!user_input_.empty())
user_input_.pop_back();
}
else
{
user_input_ += ch;
}
}
void ArgumentDebuggerWindow::OnDestroy()
{
Log(L"Window destroy event");
// 1. Signal threads to exit via atomic flags
is_running_ = false;
audio_thread_running_.store(false);
// Wake up audio thread if waiting
if (audio_event_)
SetEvent(audio_event_);
// 2. Wait for thread completion with timeout to prevent hanging
if (audio_thread_)
{
DWORD wait_result = WaitForSingleObject(audio_thread_, 5000); // 5 second timeout
if (wait_result == WAIT_TIMEOUT)
{
Log(L"WARNING: Audio thread did not terminate gracefully, forcing termination");
TerminateThread(audio_thread_, 0);
}
CloseHandle(audio_thread_);
audio_thread_ = nullptr;
}
if (audio_event_)
{ // Close event handle
CloseHandle(audio_event_);
audio_event_ = nullptr;
}
Cleanup(); // 3. Now safely release COM objects
PostQuitMessage(0);
}
void ArgumentDebuggerWindow::InitializeWindow(HINSTANCE h_instance, int /*cmd_show*/)
{
Log(L"InitializeWindow: registering class");
// Register and create the window.
WNDCLASS wc = {};
wc.lpfnWndProc = WindowProc;
wc.hInstance = h_instance;
wc.lpszClassName = kWindowClassName;
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
if (!RegisterClass(&wc))
throw std::runtime_error("Failed to register window class.");
int screen_width = GetSystemMetrics(SM_CXSCREEN);
int screen_height = GetSystemMetrics(SM_CYSCREEN);
window_handle_ = CreateWindowEx(WS_EX_TOPMOST, kWindowClassName, kWindowCaption, WS_POPUP, 0, 0, screen_width,
screen_height, nullptr, nullptr, h_instance, nullptr);
if (!window_handle_)
throw std::runtime_error("Failed to create window.");
Log(L"InitializeWindow: HWND=" + std::to_wstring(reinterpret_cast<uintptr_t>(window_handle_)));
ShowWindow(window_handle_, SW_SHOWMAXIMIZED);
}
void ArgumentDebuggerWindow::InitializeDevice()
{
RECT rc;
GetClientRect(window_handle_, &rc);
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
CreateDeviceAndSwapChain(width, height);
CreateRenderTargetView();
CreateD2DResources();
CreateShadersAndGeometry();
InitializeMicrophone();
}
void ArgumentDebuggerWindow::CreateDeviceAndSwapChain(UINT width, UINT height)
{
DXGI_SWAP_CHAIN_DESC sd = {};
sd.BufferCount = 1;
sd.BufferDesc.Width = width;
sd.BufferDesc.Height = height;
sd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHARED;
sd.OutputWindow = window_handle_;
sd.SampleDesc.Count = 1;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
// Enable debug layer for better diagnostics in debug builds
#ifdef _DEBUG
UINT create_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_DEBUG;
#else
UINT create_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#endif
DX_CALL(D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, create_flags, nullptr, 0,
D3D11_SDK_VERSION, &sd, swap_chain_.GetAddressOf(),
d3d_device_.GetAddressOf(), nullptr, immediate_context_.GetAddressOf()),
"Failed to create Direct3D device and swap chain.");
}
void ArgumentDebuggerWindow::CreateRenderTargetView()
{
ComPtr<ID3D11Texture2D> back_buffer;
DX_CALL(swap_chain_->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(back_buffer.GetAddressOf())),
"Failed to get back buffer.");
DX_CALL(d3d_device_->CreateRenderTargetView(back_buffer.Get(), nullptr, d3d_render_target_view_.GetAddressOf()),
"Failed to create render target view.");
}
void ArgumentDebuggerWindow::CreateD2DResources()
{
// Create the Direct2D factory.
DX_CALL(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, D2D1_FACTORY_OPTIONS{}, d2d_factory_.GetAddressOf()),
"Failed to create Direct2D factory.");
// Get the DXGI surface from the swap chain.
ComPtr<IDXGISurface> dxgi_surface;
DX_CALL(swap_chain_->GetBuffer(0, IID_PPV_ARGS(&dxgi_surface)), "Failed to get DXGI surface.");
D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED), 0, 0);
DX_CALL(d2d_factory_->CreateDxgiSurfaceRenderTarget(dxgi_surface.Get(), &props, d2d_render_target_.GetAddressOf()),
"Failed to create Direct2D render target.");
// Create the DirectWrite factory and text format.
DX_CALL(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory),
reinterpret_cast<IUnknown**>(dwrite_factory_.GetAddressOf())),
"Failed to create DirectWrite factory.");
DX_CALL(dwrite_factory_->CreateTextFormat(L"Arial", nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL, 24.0f, L"en-us", text_format_.GetAddressOf()),
"Failed to create text format.");
text_format_->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
text_format_->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
// Create a smaller text format for logs (half the size of the regular text)
DX_CALL(dwrite_factory_->CreateTextFormat(L"Consolas", nullptr, // Using monospaced font for logs
DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
12.0f, // Half the size of the regular font
L"en-us", small_text_format_.GetAddressOf()),
"Failed to create small text format.");
// Set text alignment properties
small_text_format_->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
small_text_format_->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
// Use trailing alignment for device name text to align to the right
small_text_format_->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_TRAILING);
// Create a medium text format for loaded data (double the size of small font)
DX_CALL(dwrite_factory_->CreateTextFormat(L"Consolas", nullptr, // Using monospaced font for data
DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
24.0f, // Double the size of small_text_format_
L"en-us", data_text_format_.GetAddressOf()),
"Failed to create data text format.");
data_text_format_->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
data_text_format_->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
data_text_format_->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
// Create brushes once during initialization
DX_CALL(d2d_render_target_->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), white_brush_.GetAddressOf()),
"Failed to create white brush.");
DX_CALL(d2d_render_target_->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Green), green_brush_.GetAddressOf()),
"Failed to create green brush.");
DX_CALL(d2d_render_target_->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow), yellow_brush_.GetAddressOf()),
"Failed to create yellow brush.");
}
void ArgumentDebuggerWindow::CreateShadersAndGeometry()
{
// Vertex shader source code.
constexpr const char vs_src[] = "cbuffer ConstantBuffer : register(b0) {"
" matrix WorldViewProjection;"
"};"
"struct VS_INPUT { float3 Pos : POSITION; float3 Color : COLOR; };"
"struct PS_INPUT { float4 Pos : SV_POSITION; float3 Color : COLOR; };"
"PS_INPUT VSMain(VS_INPUT input) {"
" PS_INPUT output;"
" output.Pos = mul(float4(input.Pos, 1.0f), WorldViewProjection);"
" output.Color = input.Color;"
" return output;"
"}";
// Pixel shader source code.
constexpr const char ps_src[] = "struct PS_INPUT { float4 Pos : SV_POSITION; float3 Color : COLOR; };"
"float4 PSMain(PS_INPUT input) : SV_Target {"
" return float4(input.Color, 1.0f);"
"}";
ComPtr<ID3DBlob> vs_blob, ps_blob, error_blob;
DX_CALL(D3DCompile(vs_src, sizeof(vs_src) - 1, nullptr, nullptr, nullptr, "VSMain", "vs_4_0", 0, 0,
vs_blob.GetAddressOf(), error_blob.GetAddressOf()),
"Failed to compile vertex shader.");
DX_CALL(D3DCompile(ps_src, sizeof(ps_src) - 1, nullptr, nullptr, nullptr, "PSMain", "ps_4_0", 0, 0,
ps_blob.GetAddressOf(), error_blob.GetAddressOf()),
"Failed to compile pixel shader.");
DX_CALL(d3d_device_->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nullptr,
vertex_shader_.GetAddressOf()),
"Failed to create vertex shader.");
DX_CALL(d3d_device_->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nullptr,
pixel_shader_.GetAddressOf()),
"Failed to create pixel shader.");
// Define input layout.
std::array<D3D11_INPUT_ELEMENT_DESC, 2> layout_desc = {
{{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}}};
DX_CALL(d3d_device_->CreateInputLayout(layout_desc.data(), static_cast<UINT>(layout_desc.size()),
vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(),
vertex_layout_.GetAddressOf()),
"Failed to create input layout.");
immediate_context_->IASetInputLayout(vertex_layout_.Get());
// Define vertices (cube).
std::array<SimpleVertex, 8> vertices = {
{// Front face
{DirectX::XMFLOAT3(-1.0f, 1.0f, -1.0f), DirectX::XMFLOAT3(1.0f, 0.0f, 0.0f)},
{DirectX::XMFLOAT3(1.0f, 1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, 1.0f, 0.0f)},
{DirectX::XMFLOAT3(1.0f, -1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, 1.0f)},
{DirectX::XMFLOAT3(-1.0f, -1.0f, -1.0f), DirectX::XMFLOAT3(1.0f, 1.0f, 0.0f)},
// Back face
{DirectX::XMFLOAT3(-1.0f, 1.0f, 1.0f), DirectX::XMFLOAT3(1.0f, 0.0f, 1.0f)},
{DirectX::XMFLOAT3(1.0f, 1.0f, 1.0f), DirectX::XMFLOAT3(0.0f, 1.0f, 1.0f)},
{DirectX::XMFLOAT3(1.0f, -1.0f, 1.0f), DirectX::XMFLOAT3(1.0f, 1.0f, 1.0f)},
{DirectX::XMFLOAT3(-1.0f, -1.0f, 1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f)}}};
// Create vertex buffer.
D3D11_BUFFER_DESC bd = {};
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = static_cast<UINT>(sizeof(SimpleVertex) * vertices.size());
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA init_data = {};
init_data.pSysMem = vertices.data();
DX_CALL(d3d_device_->CreateBuffer(&bd, &init_data, vertex_buffer_.GetAddressOf()),
"Failed to create vertex buffer.");
// Define indices.
std::array<WORD, 36> indices = {
{0, 1, 2, 2, 3, 0, 4, 7, 6, 6, 5, 4, 4, 0, 3, 3, 7, 4, 1, 5, 6, 6, 2, 1, 4, 5, 1, 1, 0, 4, 3, 2, 6, 6, 7, 3}};
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = static_cast<UINT>(sizeof(WORD) * indices.size());
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
init_data.pSysMem = indices.data();
DX_CALL(d3d_device_->CreateBuffer(&bd, &init_data, index_buffer_.GetAddressOf()), "Failed to create index buffer.");
// Create constant buffer.
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof(ConstantBufferData);
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.CPUAccessFlags = 0;
DX_CALL(d3d_device_->CreateBuffer(&bd, nullptr, constant_buffer_.GetAddressOf()),
"Failed to create constant buffer.");
}
void ArgumentDebuggerWindow::UpdateQrCode(ULONGLONG current_time)
{
// Update the QR code no more than once every 5 seconds.
if (current_time - last_qr_update_time_ < 5000)
return;
last_qr_update_time_ = current_time;
time_t unix_time = time(nullptr);
// Get the integer value of FPS.
int fps_for_qr = static_cast<int>(current_fps_);
// Save this value for synchronized file output.
synced_fps_ = fps_for_qr;
// Create the string for the QR code
std::ostringstream oss;
oss << "t=" << unix_time << ";f=" << fps_for_qr;
if (!args_.empty())
{
oss << ";args=";
for (const auto& arg : args_)
{
oss << wstring_to_string(arg) << " ";
}
}
std::string qr_data = oss.str();
// Generate the QR code (error correction level MEDIUM).
QrCode qr = QrCode::encodeText(qr_data.c_str(), QrCode::Ecc::MEDIUM);
int qr_modules = qr.getSize();
constexpr int pixel_size = 375; // final size 375x375
float scale = static_cast<float>(pixel_size) / qr_modules;
std::vector<uint32_t> pixels(pixel_size * pixel_size, 0xffffffff); // white background
for (int y = 0; y < pixel_size; y++)
{
for (int x = 0; x < pixel_size; x++)
{
int module_x = static_cast<int>(x / scale);
int module_y = static_cast<int>(y / scale);
if (module_x < qr_modules && module_y < qr_modules)
{
if (qr.getModule(module_x, module_y))
pixels[y * pixel_size + x] = 0xff000000; // black pixel
}
}
}
D2D1_BITMAP_PROPERTIES bitmapProperties = {};
bitmapProperties.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM;
bitmapProperties.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
bitmapProperties.dpiX = 96.0f;
bitmapProperties.dpiY = 96.0f;
qr_bitmap_.Reset();
DX_CALL(d2d_render_target_->CreateBitmap(D2D1::SizeU(pixel_size, pixel_size), pixels.data(),
pixel_size * sizeof(uint32_t), &bitmapProperties,
qr_bitmap_.GetAddressOf()),
"Failed to create QR code bitmap.");
}
void ArgumentDebuggerWindow::RenderFrame()
{
ULONGLONG current_time = GetTickCount64();
float delta_time = (current_time - last_time_) / 1000.0f;
last_time_ = current_time;
// Update the instantaneous FPS
current_fps_ = (delta_time > 0.0f) ? (1.0f / delta_time) : 0.0f;
UpdateRotation(delta_time);
// Clear the D3D render target
FLOAT clear_color[4] = {0.0f, 0.0f, 0.0f, 1.0f};
immediate_context_->ClearRenderTargetView(d3d_render_target_view_.Get(), clear_color);
immediate_context_->OMSetRenderTargets(1, d3d_render_target_view_.GetAddressOf(), nullptr);
RECT rc;
GetClientRect(window_handle_, &rc);