From da3e96ddddb124acbafde442685191c8b31f37d0 Mon Sep 17 00:00:00 2001 From: Redstone1024 <2824517378@qq.com> Date: Sat, 21 Jun 2025 22:22:11 +0800 Subject: [PATCH] feat(debug): add a debug console --- Redcraft.FocusIME/Source/Private/Main.cpp | 53 ++++++++++++++++++----- 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/Redcraft.FocusIME/Source/Private/Main.cpp b/Redcraft.FocusIME/Source/Private/Main.cpp index 84b4274..2c12064 100644 --- a/Redcraft.FocusIME/Source/Private/Main.cpp +++ b/Redcraft.FocusIME/Source/Private/Main.cpp @@ -9,8 +9,6 @@ #include #include #include -#include -#include #pragma comment(lib, "psapi.lib") @@ -19,10 +17,9 @@ // ReSharper disable CppDeprecatedEntity // ReSharper disable CppClangTidyCertErr33C -std::mutex GLogMutex; std::ofstream GLogFile; -std::atomic GShouldExit = false; +bool GShouldExit = false; void PrintLog(const std::string& Text); @@ -106,6 +103,36 @@ int WINAPI WinMain(HINSTANCE Instance, HINSTANCE, LPSTR, int) return 1; } +# if BUILD_DEBUG || BUILD_DEVELOPMENT + { + if (!AllocConsole()) + { + MessageBox(nullptr, "Failed to allocate console.", "FocusIME", MB_OK | MB_ICONERROR); + + DestroyWindow(MainWindow); + + CloseHandle(Mutex); + + return 1; + } + + freopen("CONOUT$", "w", stdout); + freopen("CONOUT$", "w", stderr); + freopen("CONIN$", "r", stdin); + + SetConsoleTitle("FocusIME Debug Console"); + + std::ios::sync_with_stdio(true); + + std::wcout.clear(); + std::cout.clear(); + std::wcerr.clear(); + std::cerr.clear(); + std::wcin.clear(); + std::cin.clear(); + } +# endif + GLogFile.open("Log.txt", std::ios::out | std::ios::app); if (!GLogFile.is_open()) @@ -161,11 +188,13 @@ int WINAPI WinMain(HINSTANCE Instance, HINSTANCE, LPSTR, int) PrintLog("FocusIME is shutting down..."); - { - std::lock_guard Lock(GLogMutex); + GLogFile.close(); - GLogFile.close(); +# if BUILD_DEBUG || BUILD_DEVELOPMENT + { + FreeConsole(); } +# endif UnhookWinEvent(FocusEventHook); @@ -324,10 +353,6 @@ void PrintLog(const std::string& Text) const long long Milliseconds = (std::chrono::duration_cast(Now.time_since_epoch()) % 1000).count(); - std::lock_guard Lock(GLogMutex); - - if (!GLogFile.is_open()) return; - const std::tm* LocalTime = std::localtime(&Time); // NOLINT(concurrency-mt-unsafe) char Buffer[] = "[2025-06-21 20:05:04.305]: "; @@ -344,7 +369,11 @@ void PrintLog(const std::string& Text) GLogFile << Buffer << Text << std::endl; - GLogFile.flush(); +#if BUILD_DEBUG || BUILD_DEVELOPMENT + { + std::clog << Buffer << Text << std::endl; + } +#endif } // ReSharper restore CppDeprecatedEntity