{"repo_name": "Catime", "file_name": "/Catime/src/async_update_checker.c", "inference_info": {"prefix_code": "/**\n * @file async_update_checker.c\n * @brief Asynchronous application update checking functionality\n */\n\n#include \n#include \n#include \"../include/async_update_checker.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n\ntypedef struct {\n HWND hwnd;\n BOOL silentCheck;\n} UpdateThreadParams;\n\nstatic HANDLE g_hUpdateThread = NULL;\nstatic BOOL g_bUpdateThreadRunning = FALSE;\n\n/**\n * @brief Clean up update check thread resources\n */\nvoid CleanupUpdateThread() {\n LOG_INFO(\"Cleaning up update check thread resources\");\n if (g_hUpdateThread != NULL) {\n DWORD waitResult = WaitForSingleObject(g_hUpdateThread, 1000);\n if (waitResult == WAIT_TIMEOUT) {\n LOG_WARNING(\"Wait for thread end timed out, forcibly closing thread handle\");\n } else if (waitResult == WAIT_OBJECT_0) {\n LOG_INFO(\"Thread has ended normally\");\n } else {\n LOG_WARNING(\"Wait for thread returned unexpected result: %lu\", waitResult);\n }\n\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n g_bUpdateThreadRunning = FALSE;\n LOG_INFO(\"Thread resources have been cleaned up\");\n } else {\n LOG_INFO(\"Update check thread not running, no cleanup needed\");\n }\n}\n\n/**\n * @brief Update check thread function\n * @param param Thread parameters\n */\n", "suffix_code": "\n\n/**\n * @brief Check for application updates asynchronously\n * @param hwnd Window handle\n * @param silentCheck Whether to perform a silent check\n */\nvoid CheckForUpdateAsync(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Asynchronous update check requested, window handle: 0x%p, silent mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n\n if (g_bUpdateThreadRunning) {\n LOG_INFO(\"Update check thread already running, skipping this check request\");\n return;\n }\n\n if (g_hUpdateThread != NULL) {\n LOG_INFO(\"Found old thread handle, cleaning up...\");\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n LOG_INFO(\"Old thread handle closed\");\n }\n\n LOG_INFO(\"Allocating memory for thread parameters\");\n UpdateThreadParams* threadParams = (UpdateThreadParams*)malloc(sizeof(UpdateThreadParams));\n if (!threadParams) {\n LOG_ERROR(\"Thread parameter memory allocation failed, cannot start update check thread\");\n return;\n }\n\n threadParams->hwnd = hwnd;\n threadParams->silentCheck = silentCheck;\n LOG_INFO(\"Thread parameters set up\");\n\n g_bUpdateThreadRunning = TRUE;\n\n LOG_INFO(\"Preparing to create update check thread\");\n HANDLE hThread = (HANDLE)_beginthreadex(\n NULL,\n 0,\n UpdateCheckThreadProc,\n threadParams,\n 0,\n NULL\n );\n\n if (hThread) {\n LOG_INFO(\"Update check thread created successfully, thread handle: 0x%p\", hThread);\n g_hUpdateThread = hThread;\n } else {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Update check thread creation failed, error code: %lu, error message: %s\", errorCode, errorMsg);\n\n free(threadParams);\n g_bUpdateThreadRunning = FALSE;\n }\n}", "middle_code": "unsigned __stdcall UpdateCheckThreadProc(void* param) {\n LOG_INFO(\"Update check thread started\");\n UpdateThreadParams* threadParams = (UpdateThreadParams*)param;\n if (!threadParams) {\n LOG_ERROR(\"Thread parameters are null, cannot perform update check\");\n g_bUpdateThreadRunning = FALSE;\n _endthreadex(1);\n return 1;\n }\n HWND hwnd = threadParams->hwnd;\n BOOL silentCheck = threadParams->silentCheck;\n LOG_INFO(\"Thread parameters parsed successfully, window handle: 0x%p, silent check mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n free(threadParams);\n LOG_INFO(\"Thread parameter memory freed\");\n LOG_INFO(\"Starting update check\");\n CheckForUpdateSilent(hwnd, silentCheck);\n LOG_INFO(\"Update check completed\");\n g_bUpdateThreadRunning = FALSE;\n _endthreadex(0);\n return 0;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/Catime/src/main.c", "/**\n * @file main.c\n * @brief Application main entry module implementation file\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\"\n#include \"../include/window.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/media.h\"\n#include \"../include/notification.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/dialog_language.h\"\n#include \"../include/shortcut_checker.h\"\n\n// Required for older Windows SDK\n#ifndef CSIDL_STARTUP\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n// Compiler directives\n#pragma comment(lib, \"dwmapi.lib\")\n#pragma comment(lib, \"user32.lib\")\n#pragma comment(lib, \"gdi32.lib\")\n#pragma comment(lib, \"comdlg32.lib\")\n#pragma comment(lib, \"dbghelp.lib\")\n#pragma comment(lib, \"comctl32.lib\")\n\nextern void CleanupLogSystem(void);\n\nint default_countdown_time = 0;\nint CLOCK_DEFAULT_START_TIME = 300;\nint elapsed_time = 0;\nchar inputText[256] = {0};\nint message_shown = 0;\ntime_t last_config_time = 0;\nRecentFile CLOCK_RECENT_FILES[MAX_RECENT_FILES];\nint CLOCK_RECENT_FILES_COUNT = 0;\nchar CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH] = \"\";\n\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char FONT_INTERNAL_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\n\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid ExitProgram(HWND hwnd);\n\n/**\n * @brief Handle application startup mode\n * @param hwnd Main window handle\n */\nstatic void HandleStartupMode(HWND hwnd) {\n LOG_INFO(\"Setting startup mode: %s\", CLOCK_STARTUP_MODE);\n \n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n LOG_INFO(\"Setting to count-up mode\");\n CLOCK_COUNT_UP = TRUE;\n elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n LOG_INFO(\"Setting to hidden mode, window will be hidden\");\n ShowWindow(hwnd, SW_HIDE);\n KillTimer(hwnd, 1);\n elapsed_time = CLOCK_TOTAL_TIME;\n CLOCK_IS_PAUSED = TRUE;\n message_shown = TRUE;\n countdown_message_shown = TRUE;\n countup_message_shown = TRUE;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n LOG_INFO(\"Setting to show current time mode\");\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_LAST_TIME_UPDATE = 0;\n } else {\n LOG_INFO(\"Using default countdown mode\");\n }\n}\n\n/**\n * @brief Application main entry point\n */\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n // Initialize Common Controls\n InitCommonControls();\n \n // Initialize log system\n if (!InitializeLogSystem()) {\n // If log system initialization fails, continue running but without logging\n MessageBox(NULL, \"Log system initialization failed, the program will continue running but will not log.\", \"Warning\", MB_ICONWARNING);\n }\n\n // Set up exception handler\n SetupExceptionHandler();\n\n LOG_INFO(\"Catime is starting...\");\n // Initialize COM\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM initialization failed, error code: 0x%08X\", hr);\n MessageBox(NULL, \"COM initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"COM initialization successful\");\n\n // Initialize application\n LOG_INFO(\"Starting application initialization...\");\n if (!InitializeApplication(hInstance)) {\n LOG_ERROR(\"Application initialization failed\");\n MessageBox(NULL, \"Application initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"Application initialization successful\");\n\n // Check and create desktop shortcut (if necessary)\n LOG_INFO(\"Checking desktop shortcut...\");\n char exe_path[MAX_PATH];\n GetModuleFileNameA(NULL, exe_path, MAX_PATH);\n LOG_INFO(\"Current program path: %s\", exe_path);\n \n // Set log level to DEBUG to show detailed information\n WriteLog(LOG_LEVEL_DEBUG, \"Starting shortcut detection, checking path: %s\", exe_path);\n \n // Check if path contains WinGet identifier\n if (strstr(exe_path, \"WinGet\") != NULL) {\n WriteLog(LOG_LEVEL_DEBUG, \"Path contains WinGet keyword\");\n }\n \n // Additional test: directly test if file exists\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path))) {\n sprintf(shortcut_path, \"%s\\\\Catime.lnk\", desktop_path);\n WriteLog(LOG_LEVEL_DEBUG, \"Checking if desktop shortcut exists: %s\", shortcut_path);\n if (GetFileAttributesA(shortcut_path) == INVALID_FILE_ATTRIBUTES) {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut does not exist, need to create\");\n } else {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut already exists\");\n }\n }\n \n int shortcut_result = CheckAndCreateShortcut();\n if (shortcut_result == 0) {\n LOG_INFO(\"Desktop shortcut check completed\");\n } else {\n LOG_WARNING(\"Desktop shortcut creation failed, error code: %d\", shortcut_result);\n }\n\n // Initialize dialog multi-language support\n LOG_INFO(\"Starting dialog multi-language support initialization...\");\n if (!InitDialogLanguageSupport()) {\n LOG_WARNING(\"Dialog multi-language support initialization failed, but program will continue running\");\n }\n LOG_INFO(\"Dialog multi-language support initialization successful\");\n\n // Handle single instance\n LOG_INFO(\"Checking if another instance is running...\");\n HANDLE hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n DWORD mutexError = GetLastError();\n \n if (mutexError == ERROR_ALREADY_EXISTS) {\n LOG_INFO(\"Detected another instance is running, trying to close that instance\");\n HWND hwndExisting = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwndExisting) {\n // Close existing window instance\n LOG_INFO(\"Sending close message to existing instance\");\n SendMessage(hwndExisting, WM_CLOSE, 0, 0);\n // Wait for old instance to close\n Sleep(200);\n } else {\n LOG_WARNING(\"Could not find window handle of existing instance, but mutex exists\");\n }\n // Release old mutex\n ReleaseMutex(hMutex);\n CloseHandle(hMutex);\n \n // Create new mutex\n LOG_INFO(\"Creating new mutex\");\n hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n if (GetLastError() == ERROR_ALREADY_EXISTS) {\n LOG_WARNING(\"Still have conflict after creating new mutex, possible race condition\");\n }\n }\n Sleep(50);\n\n // Create main window\n LOG_INFO(\"Starting main window creation...\");\n HWND hwnd = CreateMainWindow(hInstance, nCmdShow);\n if (!hwnd) {\n LOG_ERROR(\"Main window creation failed\");\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Main window creation successful, handle: 0x%p\", hwnd);\n\n // Set timer\n LOG_INFO(\"Setting main timer...\");\n if (SetTimer(hwnd, 1, 1000, NULL) == 0) {\n DWORD timerError = GetLastError();\n LOG_ERROR(\"Timer creation failed, error code: %lu\", timerError);\n MessageBox(NULL, \"Timer Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Timer set successfully\");\n\n // Handle startup mode\n LOG_INFO(\"Handling startup mode: %s\", CLOCK_STARTUP_MODE);\n HandleStartupMode(hwnd);\n \n // Automatic update check code has been removed\n\n // Message loop\n LOG_INFO(\"Entering main message loop\");\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0) > 0) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n // Clean up resources\n LOG_INFO(\"Program preparing to exit, starting resource cleanup\");\n \n // Clean up update check thread resources\n LOG_INFO(\"Preparing to clean up update check thread resources\");\n CleanupUpdateThread();\n \n CloseHandle(hMutex);\n CoUninitialize();\n \n // Close log system\n CleanupLogSystem();\n \n return (int)msg.wParam;\n // If execution reaches here, the program has exited normally\n}\n"], ["/Catime/src/update_checker.c", "/**\n * @file update_checker.c\n * @brief Minimalist application update check functionality implementation\n * \n * This file implements functions for checking versions, opening browser for downloads, and deleting configuration files.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/language.h\"\n#include \"../include/dialog_language.h\"\n#include \"../resource/resource.h\"\n\n#pragma comment(lib, \"wininet.lib\")\n\n// Update source URL\n#define GITHUB_API_URL \"https://api.github.com/repos/vladelaina/Catime/releases/latest\"\n#define USER_AGENT \"Catime Update Checker\"\n\n// Version information structure definition\ntypedef struct {\n const char* currentVersion;\n const char* latestVersion;\n const char* downloadUrl;\n} UpdateVersionInfo;\n\n// Function declarations\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\n/**\n * @brief Compare version numbers\n * @param version1 First version string\n * @param version2 Second version string\n * @return Returns 1 if version1 > version2, 0 if equal, -1 if version1 < version2\n */\nint CompareVersions(const char* version1, const char* version2) {\n LOG_DEBUG(\"Comparing versions: '%s' vs '%s'\", version1, version2);\n \n int major1, minor1, patch1;\n int major2, minor2, patch2;\n \n // Parse version numbers\n sscanf(version1, \"%d.%d.%d\", &major1, &minor1, &patch1);\n sscanf(version2, \"%d.%d.%d\", &major2, &minor2, &patch2);\n \n LOG_DEBUG(\"Parsed version1: %d.%d.%d, version2: %d.%d.%d\", major1, minor1, patch1, major2, minor2, patch2);\n \n // Compare major version\n if (major1 > major2) return 1;\n if (major1 < major2) return -1;\n \n // Compare minor version\n if (minor1 > minor2) return 1;\n if (minor1 < minor2) return -1;\n \n // Compare patch version\n if (patch1 > patch2) return 1;\n if (patch1 < patch2) return -1;\n \n return 0;\n}\n\n/**\n * @brief Parse JSON response to get latest version and download URL\n */\nBOOL ParseLatestVersionFromJson(const char* jsonResponse, char* latestVersion, size_t maxLen, \n char* downloadUrl, size_t urlMaxLen) {\n LOG_DEBUG(\"Starting to parse JSON response, extracting version information\");\n \n // Find version number\n const char* tagNamePos = strstr(jsonResponse, \"\\\"tag_name\\\":\");\n if (!tagNamePos) {\n LOG_ERROR(\"JSON parsing failed: tag_name field not found\");\n return FALSE;\n }\n \n const char* firstQuote = strchr(tagNamePos + 11, '\\\"');\n if (!firstQuote) return FALSE;\n \n const char* secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy version number\n size_t versionLen = secondQuote - (firstQuote + 1);\n if (versionLen >= maxLen) versionLen = maxLen - 1;\n \n strncpy(latestVersion, firstQuote + 1, versionLen);\n latestVersion[versionLen] = '\\0';\n \n // If version starts with 'v', remove it\n if (latestVersion[0] == 'v' || latestVersion[0] == 'V') {\n memmove(latestVersion, latestVersion + 1, versionLen);\n }\n \n // Find download URL\n const char* downloadUrlPos = strstr(jsonResponse, \"\\\"browser_download_url\\\":\");\n if (!downloadUrlPos) {\n LOG_ERROR(\"JSON parsing failed: browser_download_url field not found\");\n return FALSE;\n }\n \n firstQuote = strchr(downloadUrlPos + 22, '\\\"');\n if (!firstQuote) return FALSE;\n \n secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy download URL\n size_t urlLen = secondQuote - (firstQuote + 1);\n if (urlLen >= urlMaxLen) urlLen = urlMaxLen - 1;\n \n strncpy(downloadUrl, firstQuote + 1, urlLen);\n downloadUrl[urlLen] = '\\0';\n \n return TRUE;\n}\n\n/**\n * @brief Exit message dialog procedure\n */\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Get localized exit text\n const wchar_t* exitText = GetLocalizedString(L\"程序即将退出\", L\"The application will exit now\");\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, exitText);\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, L\"\"); // Clear version text\n \n // Set OK button text\n const wchar_t* okText = GetLocalizedString(L\"确定\", L\"OK\");\n SetDlgItemTextW(hwndDlg, IDOK, okText);\n \n // Hide Yes/No buttons, only show OK button\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_SHOW);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"Catime - 更新提示\", L\"Catime - Update Notice\");\n SetWindowTextW(hwndDlg, titleText);\n \n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display custom exit message dialog\n */\nvoid ShowExitMessageDialog(HWND hwnd) {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n ExitMsgDlgProc);\n}\n\n/**\n * @brief Update dialog procedure\n */\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static UpdateVersionInfo* versionInfo = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Save version information\n versionInfo = (UpdateVersionInfo*)lParam;\n \n // Format display text\n if (versionInfo) {\n // Convert ASCII version numbers to Unicode\n wchar_t currentVersionW[64] = {0};\n wchar_t newVersionW[64] = {0};\n \n // Convert version numbers to wide characters\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->currentVersion, -1, \n currentVersionW, sizeof(currentVersionW)/sizeof(wchar_t));\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->latestVersion, -1, \n newVersionW, sizeof(newVersionW)/sizeof(wchar_t));\n \n // Use pre-formatted strings instead of trying to format ourselves\n wchar_t displayText[256];\n \n // Get localized version text (pre-formatted)\n const wchar_t* currentVersionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n const wchar_t* newVersionText = GetLocalizedString(L\"新版本:\", L\"New version:\");\n\n // Manually build formatted string\n StringCbPrintfW(displayText, sizeof(displayText),\n L\"%s %s\\n%s %s\",\n currentVersionText, currentVersionW,\n newVersionText, newVersionW);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, displayText);\n \n // Set button text\n const wchar_t* yesText = GetLocalizedString(L\"是\", L\"Yes\");\n const wchar_t* noText = GetLocalizedString(L\"否\", L\"No\");\n \n // Explicitly set button text, not relying on dialog resource\n SetDlgItemTextW(hwndDlg, IDYES, yesText);\n SetDlgItemTextW(hwndDlg, IDNO, noText);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"发现新版本\", L\"Update Available\");\n SetWindowTextW(hwndDlg, titleText);\n \n // Hide exit text and OK button, show Yes/No buttons\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, L\"\");\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_HIDE);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDNO);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update notification dialog\n */\nint ShowUpdateNotification(HWND hwnd, const char* currentVersion, const char* latestVersion, const char* downloadUrl) {\n // Create version info structure\n UpdateVersionInfo versionInfo;\n versionInfo.currentVersion = currentVersion;\n versionInfo.latestVersion = latestVersion;\n versionInfo.downloadUrl = downloadUrl;\n \n // Display custom dialog\n return DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n UpdateDlgProc, \n (LPARAM)&versionInfo);\n}\n\n/**\n * @brief Update error dialog procedure\n */\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Get error message text\n const wchar_t* errorMsg = (const wchar_t*)lParam;\n if (errorMsg) {\n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_ERROR_TEXT, errorMsg);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update error dialog\n */\nvoid ShowUpdateErrorDialog(HWND hwnd, const wchar_t* errorMsg) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_ERROR_DIALOG), \n hwnd, \n UpdateErrorDlgProc, \n (LPARAM)errorMsg);\n}\n\n/**\n * @brief No update required dialog procedure\n */\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_NO_UPDATE_DIALOG);\n \n // Get current version information\n const char* currentVersion = (const char*)lParam;\n if (currentVersion) {\n // Get localized basic text\n const wchar_t* baseText = GetDialogLocalizedString(IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT);\n if (!baseText) {\n // If localized text not found, use default text\n baseText = L\"You are already using the latest version!\";\n }\n \n // Get localized \"Current version\" text\n const wchar_t* versionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n \n // Create complete message including version number\n wchar_t fullMessage[256];\n StringCbPrintfW(fullMessage, sizeof(fullMessage),\n L\"%s\\n%s %hs\", baseText, versionText, currentVersion);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_NO_UPDATE_TEXT, fullMessage);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display no update required dialog\n * @param hwnd Parent window handle\n * @param currentVersion Current version number\n */\nvoid ShowNoUpdateDialog(HWND hwnd, const char* currentVersion) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_NO_UPDATE_DIALOG), \n hwnd, \n NoUpdateDlgProc, \n (LPARAM)currentVersion);\n}\n\n/**\n * @brief Open browser to download update and exit program\n */\nBOOL OpenBrowserForUpdateAndExit(const char* url, HWND hwnd) {\n // Open browser\n HINSTANCE hInstance = ShellExecuteA(hwnd, \"open\", url, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)hInstance <= 32) {\n // Failed to open browser\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法打开浏览器下载更新\", L\"Could not open browser to download update\"));\n return FALSE;\n }\n \n LOG_INFO(\"Successfully opened browser, preparing to exit program\");\n \n // Prompt user\n wchar_t message[512];\n StringCbPrintfW(message, sizeof(message),\n L\"即将退出程序\");\n \n LOG_INFO(\"Sending exit message to main window\");\n // Use custom dialog to display exit message\n ShowExitMessageDialog(hwnd);\n \n // Exit program\n PostMessage(hwnd, WM_CLOSE, 0, 0);\n return TRUE;\n}\n\n/**\n * @brief General update check function\n */\nvoid CheckForUpdateInternal(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Starting update check process, silent mode: %s\", silentCheck ? \"yes\" : \"no\");\n \n // Create Internet session\n LOG_INFO(\"Attempting to create Internet session\");\n HINTERNET hInternet = InternetOpenA(USER_AGENT, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);\n if (!hInternet) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to create Internet session, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法创建Internet连接\", L\"Could not create Internet connection\"));\n }\n return;\n }\n LOG_INFO(\"Internet session created successfully\");\n \n // Connect to update API\n LOG_INFO(\"Attempting to connect to GitHub API: %s\", GITHUB_API_URL);\n HINTERNET hConnect = InternetOpenUrlA(hInternet, GITHUB_API_URL, NULL, 0, \n INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, 0);\n if (!hConnect) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to connect to GitHub API, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n InternetCloseHandle(hInternet);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法连接到更新服务器\", L\"Could not connect to update server\"));\n }\n return;\n }\n LOG_INFO(\"Successfully connected to GitHub API\");\n \n // Allocate buffer\n LOG_INFO(\"Allocating memory buffer for API response\");\n char* buffer = (char*)malloc(8192);\n if (!buffer) {\n LOG_ERROR(\"Memory allocation failed, could not allocate buffer for API response\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n \n // Read response\n LOG_INFO(\"Starting to read response data from API\");\n DWORD bytesRead = 0;\n DWORD totalBytes = 0;\n size_t bufferSize = 8192;\n \n while (InternetReadFile(hConnect, buffer + totalBytes, \n bufferSize - totalBytes - 1, &bytesRead) && bytesRead > 0) {\n LOG_DEBUG(\"Read %lu bytes of data, accumulated %lu bytes\", bytesRead, totalBytes + bytesRead);\n totalBytes += bytesRead;\n if (totalBytes >= bufferSize - 256) {\n size_t newSize = bufferSize * 2;\n char* newBuffer = (char*)realloc(buffer, newSize);\n if (!newBuffer) {\n // Fix: If realloc fails, free the original buffer and abort\n LOG_ERROR(\"Failed to reallocate buffer, current size: %zu bytes\", bufferSize);\n free(buffer);\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n LOG_DEBUG(\"Buffer expanded, new size: %zu bytes\", newSize);\n buffer = newBuffer;\n bufferSize = newSize;\n }\n }\n \n buffer[totalBytes] = '\\0';\n LOG_INFO(\"Successfully read API response, total %lu bytes of data\", totalBytes);\n \n // Close connection\n LOG_INFO(\"Closing Internet connection\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n \n // Parse version and download URL\n LOG_INFO(\"Starting to parse API response, extracting version info and download URL\");\n char latestVersion[32] = {0};\n char downloadUrl[256] = {0};\n if (!ParseLatestVersionFromJson(buffer, latestVersion, sizeof(latestVersion), \n downloadUrl, sizeof(downloadUrl))) {\n LOG_ERROR(\"Failed to parse version information, response may not be valid JSON format\");\n free(buffer);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法解析版本信息\", L\"Could not parse version information\"));\n }\n return;\n }\n LOG_INFO(\"Successfully parsed version information, GitHub latest version: %s, download URL: %s\", latestVersion, downloadUrl);\n \n free(buffer);\n \n // Get current version\n const char* currentVersion = CATIME_VERSION;\n LOG_INFO(\"Current application version: %s\", currentVersion);\n \n // Compare versions\n LOG_INFO(\"Comparing version numbers: current version %s vs. latest version %s\", currentVersion, latestVersion);\n int versionCompare = CompareVersions(latestVersion, currentVersion);\n if (versionCompare > 0) {\n // New version available\n LOG_INFO(\"New version found! Current: %s, Available update: %s\", currentVersion, latestVersion);\n int response = ShowUpdateNotification(hwnd, currentVersion, latestVersion, downloadUrl);\n LOG_INFO(\"Update prompt dialog result: %s\", response == IDYES ? \"User agreed to update\" : \"User declined update\");\n \n if (response == IDYES) {\n LOG_INFO(\"User chose to update now, preparing to open browser and exit program\");\n OpenBrowserForUpdateAndExit(downloadUrl, hwnd);\n }\n } else if (!silentCheck) {\n // Already using latest version\n LOG_INFO(\"Current version %s is already the latest, no update needed\", currentVersion);\n \n // Use localized strings instead of building complete message\n ShowNoUpdateDialog(hwnd, currentVersion);\n } else {\n LOG_INFO(\"Silent check mode: Current version %s is already the latest, no prompt shown\", currentVersion);\n }\n \n LOG_INFO(\"Update check process complete\");\n}\n\n/**\n * @brief Check for application updates\n */\nvoid CheckForUpdate(HWND hwnd) {\n CheckForUpdateInternal(hwnd, FALSE);\n}\n\n/**\n * @brief Silently check for application updates\n */\nvoid CheckForUpdateSilent(HWND hwnd, BOOL silentCheck) {\n CheckForUpdateInternal(hwnd, silentCheck);\n} \n"], ["/Catime/src/notification.c", "/**\n * @file notification.c\n * @brief Application notification system implementation\n * \n * This module implements various notification functions of the application, including:\n * 1. Custom styled popup notification windows with fade-in/fade-out animation effects\n * 2. System tray notification message integration\n * 3. Creation, display and lifecycle management of notification windows\n * \n * The notification system supports UTF-8 encoded Chinese text to ensure correct display in multilingual environments.\n */\n\n#include \n#include \n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\" // Contains definitions of all IDs and constants\n#include // For GET_X_LPARAM and GET_Y_LPARAM macros\n\n// Imported from config.h\n// New: notification type configuration\nextern NotificationType NOTIFICATION_TYPE;\n\n/**\n * Notification window animation state enumeration\n * Tracks the current animation phase of the notification window\n */\ntypedef enum {\n ANIM_FADE_IN, // Fade-in phase - opacity increases from 0 to target value\n ANIM_VISIBLE, // Fully visible phase - maintains maximum opacity\n ANIM_FADE_OUT, // Fade-out phase - opacity decreases from maximum to 0\n} AnimationState;\n\n// Forward declarations\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid RegisterNotificationClass(HINSTANCE hInstance);\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius);\n\n/**\n * @brief Calculate the width required for text rendering\n * @param hdc Device context\n * @param text Text to measure\n * @param font Font to use\n * @return int Width required for text rendering (pixels)\n */\nint CalculateTextWidth(HDC hdc, const wchar_t* text, HFONT font) {\n HFONT oldFont = (HFONT)SelectObject(hdc, font);\n SIZE textSize;\n GetTextExtentPoint32W(hdc, text, wcslen(text), &textSize);\n SelectObject(hdc, oldFont);\n return textSize.cx;\n}\n\n/**\n * @brief Show notification (based on configured notification type)\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays different styles of notifications based on the configured notification type\n */\nvoid ShowNotification(HWND hwnd, const char* message) {\n // Read the latest notification type configuration\n ReadNotificationTypeConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Choose the corresponding notification method based on notification type\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n ShowToastNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n ShowModalNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_OS:\n ShowTrayNotification(hwnd, message);\n break;\n default:\n // Default to using Catime notification window\n ShowToastNotification(hwnd, message);\n break;\n }\n}\n\n/**\n * Modal dialog thread parameter structure\n */\ntypedef struct {\n HWND hwnd; // Parent window handle\n char message[512]; // Message content\n} DialogThreadParams;\n\n/**\n * @brief Thread function to display modal dialog\n * @param lpParam Thread parameter, pointer to DialogThreadParams structure\n * @return DWORD Thread return value\n */\nDWORD WINAPI ShowModalDialogThread(LPVOID lpParam) {\n DialogThreadParams* params = (DialogThreadParams*)lpParam;\n \n // Convert UTF-8 message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, params->message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, display English version directly\n MessageBoxA(params->hwnd, params->message, \"Catime\", MB_OK);\n free(params);\n return 0;\n }\n \n MultiByteToWideChar(CP_UTF8, 0, params->message, -1, wmessage, wlen);\n \n // Display modal dialog with fixed title \"Catime\"\n MessageBoxW(params->hwnd, wmessage, L\"Catime\", MB_OK);\n \n // Free allocated memory\n free(wmessage);\n free(params);\n \n return 0;\n}\n\n/**\n * @brief Display system modal dialog notification\n * @param hwnd Parent window handle\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a modal dialog in a separate thread, which won't block the main program\n */\nvoid ShowModalNotification(HWND hwnd, const char* message) {\n // Create thread parameter structure\n DialogThreadParams* params = (DialogThreadParams*)malloc(sizeof(DialogThreadParams));\n if (!params) return;\n \n // Copy parameters\n params->hwnd = hwnd;\n strncpy(params->message, message, sizeof(params->message) - 1);\n params->message[sizeof(params->message) - 1] = '\\0';\n \n // Create new thread to display dialog\n HANDLE hThread = CreateThread(\n NULL, // Default security attributes\n 0, // Default stack size\n ShowModalDialogThread, // Thread function\n params, // Thread parameter\n 0, // Run thread immediately\n NULL // Don't receive thread ID\n );\n \n // If thread creation fails, free resources\n if (hThread == NULL) {\n free(params);\n // Fall back to non-blocking notification method\n MessageBeep(MB_OK);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Close thread handle, let system clean up automatically\n CloseHandle(hThread);\n}\n\n/**\n * @brief Display custom styled toast notification\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a custom notification window with animation effects in the bottom right corner of the screen:\n * 1. Register notification window class (if needed)\n * 2. Calculate notification display position (bottom right of work area)\n * 3. Create notification window with fade-in/fade-out effects\n * 4. Set auto-close timer\n * \n * Note: If creating custom notification window fails, will fall back to using system tray notification\n */\nvoid ShowToastNotification(HWND hwnd, const char* message) {\n static BOOL isClassRegistered = FALSE;\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n \n // Dynamically read the latest notification settings before displaying notification\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Register notification window class (if not already registered)\n if (!isClassRegistered) {\n RegisterNotificationClass(hInstance);\n isClassRegistered = TRUE;\n }\n \n // Convert message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, fall back to system tray notification\n ShowTrayNotification(hwnd, message);\n return;\n }\n MultiByteToWideChar(CP_UTF8, 0, message, -1, wmessage, wlen);\n \n // Calculate width needed for text\n HDC hdc = GetDC(hwnd);\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Calculate text width and add margins\n int textWidth = CalculateTextWidth(hdc, wmessage, contentFont);\n int notificationWidth = textWidth + 40; // 20 pixel margin on each side\n \n // Ensure width is within allowed range\n if (notificationWidth < NOTIFICATION_MIN_WIDTH) \n notificationWidth = NOTIFICATION_MIN_WIDTH;\n if (notificationWidth > NOTIFICATION_MAX_WIDTH) \n notificationWidth = NOTIFICATION_MAX_WIDTH;\n \n DeleteObject(contentFont);\n ReleaseDC(hwnd, hdc);\n \n // Get work area size, calculate notification window position (bottom right)\n RECT workArea;\n SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);\n \n int x = workArea.right - notificationWidth - 20;\n int y = workArea.bottom - NOTIFICATION_HEIGHT - 20;\n \n // Create notification window, add layered support for transparency effects\n HWND hNotification = CreateWindowExW(\n WS_EX_TOPMOST | WS_EX_LAYERED | WS_EX_TOOLWINDOW, // Keep on top and hide from taskbar\n NOTIFICATION_CLASS_NAME,\n L\"Catime Notification\", // Window title (not visible)\n WS_POPUP, // Borderless popup window style\n x, y, // Bottom right screen position\n notificationWidth, NOTIFICATION_HEIGHT,\n NULL, NULL, hInstance, NULL\n );\n \n // Fall back to system tray notification if creation fails\n if (!hNotification) {\n free(wmessage);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Save message text and window width to window properties\n SetPropW(hNotification, L\"MessageText\", (HANDLE)wmessage);\n SetPropW(hNotification, L\"WindowWidth\", (HANDLE)(LONG_PTR)notificationWidth);\n \n // Set initial animation state to fade-in\n SetPropW(hNotification, L\"AnimState\", (HANDLE)ANIM_FADE_IN);\n SetPropW(hNotification, L\"Opacity\", (HANDLE)0); // Initial opacity is 0\n \n // Set initial window to completely transparent\n SetLayeredWindowAttributes(hNotification, 0, 0, LWA_ALPHA);\n \n // Show window but don't activate (don't steal focus)\n ShowWindow(hNotification, SW_SHOWNOACTIVATE);\n UpdateWindow(hNotification);\n \n // Start fade-in animation\n SetTimer(hNotification, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n \n // Set auto-close timer, using globally configured timeout\n SetTimer(hNotification, NOTIFICATION_TIMER_ID, NOTIFICATION_TIMEOUT_MS, NULL);\n}\n\n/**\n * @brief Register notification window class\n * @param hInstance Application instance handle\n * \n * Registers custom notification window class with Windows, defining basic behavior and appearance:\n * 1. Set window procedure function\n * 2. Define default cursor and background\n * 3. Specify unique window class name\n * \n * This function is only called the first time a notification is displayed, subsequent calls reuse the registered class.\n */\nvoid RegisterNotificationClass(HINSTANCE hInstance) {\n WNDCLASSEXW wc = {0};\n wc.cbSize = sizeof(WNDCLASSEXW);\n wc.lpfnWndProc = NotificationWndProc;\n wc.hInstance = hInstance;\n wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n wc.lpszClassName = NOTIFICATION_CLASS_NAME;\n \n RegisterClassExW(&wc);\n}\n\n/**\n * @brief Notification window message processing procedure\n * @param hwnd Window handle\n * @param msg Message ID\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return LRESULT Message processing result\n * \n * Handles all Windows messages for the notification window, including:\n * - WM_PAINT: Draw notification window content (title, message text)\n * - WM_TIMER: Handle auto-close and animation effects\n * - WM_LBUTTONDOWN: Handle user click to close\n * - WM_DESTROY: Release window resources\n * \n * Specifically handles animation state transition logic to ensure smooth fade-in/fade-out effects.\n */\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_PAINT: {\n PAINTSTRUCT ps;\n HDC hdc = BeginPaint(hwnd, &ps);\n \n // Get window client area size\n RECT clientRect;\n GetClientRect(hwnd, &clientRect);\n \n // Create compatible DC and bitmap for double-buffered drawing to avoid flickering\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, clientRect.right, clientRect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n \n // Fill white background\n HBRUSH whiteBrush = CreateSolidBrush(RGB(255, 255, 255));\n FillRect(memDC, &clientRect, whiteBrush);\n DeleteObject(whiteBrush);\n \n // Draw rectangle with border\n DrawRoundedRectangle(memDC, clientRect, 0);\n \n // Set text drawing mode to transparent background\n SetBkMode(memDC, TRANSPARENT);\n \n // Create title font - bold\n HFONT titleFont = CreateFontW(22, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Create message content font\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Draw title \"Catime\"\n SelectObject(memDC, titleFont);\n SetTextColor(memDC, RGB(0, 0, 0));\n RECT titleRect = {15, 10, clientRect.right - 15, 35};\n DrawTextW(memDC, L\"Catime\", -1, &titleRect, DT_SINGLELINE);\n \n // Draw message content - placed below title, using single line mode\n SelectObject(memDC, contentFont);\n SetTextColor(memDC, RGB(100, 100, 100));\n const wchar_t* message = (const wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n RECT textRect = {15, 35, clientRect.right - 15, clientRect.bottom - 10};\n // Use DT_SINGLELINE|DT_END_ELLIPSIS to ensure text is displayed in one line, with ellipsis for long text\n DrawTextW(memDC, message, -1, &textRect, DT_SINGLELINE|DT_END_ELLIPSIS);\n }\n \n // Copy content from memory DC to window DC\n BitBlt(hdc, 0, 0, clientRect.right, clientRect.bottom, memDC, 0, 0, SRCCOPY);\n \n // Clean up resources\n SelectObject(memDC, oldBitmap);\n DeleteObject(titleFont);\n DeleteObject(contentFont);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n \n EndPaint(hwnd, &ps);\n return 0;\n }\n \n case WM_TIMER:\n if (wParam == NOTIFICATION_TIMER_ID) {\n // Auto-close timer triggered, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // Check current state - only start fade-out when fully visible\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState == ANIM_VISIBLE) {\n // Set to fade-out state\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start animation timer\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n return 0;\n }\n else if (wParam == ANIMATION_TIMER_ID) {\n // Handle animation effect timer\n AnimationState state = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n DWORD opacityVal = (DWORD)(DWORD_PTR)GetPropW(hwnd, L\"Opacity\");\n BYTE opacity = (BYTE)opacityVal;\n \n // Calculate maximum opacity value (percentage converted to 0-255 range)\n BYTE maxOpacity = (BYTE)((NOTIFICATION_MAX_OPACITY * 255) / 100);\n \n switch (state) {\n case ANIM_FADE_IN:\n // Fade-in animation - gradually increase opacity\n if (opacity >= maxOpacity - ANIMATION_STEP) {\n // Reached maximum opacity, completed fade-in\n opacity = maxOpacity;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n \n // Switch to visible state and stop animation\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_VISIBLE);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n } else {\n // Normal fade-in - increase by one step each time\n opacity += ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_FADE_OUT:\n // Fade-out animation - gradually decrease opacity\n if (opacity <= ANIMATION_STEP) {\n // Completely transparent, destroy window\n KillTimer(hwnd, ANIMATION_TIMER_ID); // Make sure to stop timer first\n DestroyWindow(hwnd);\n } else {\n // Normal fade-out - decrease by one step each time\n opacity -= ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_VISIBLE:\n // Fully visible state doesn't need animation, stop timer\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n break;\n }\n return 0;\n }\n break;\n \n case WM_LBUTTONDOWN: {\n // Handle left mouse button click event (close notification early)\n \n // Get current state - only respond to clicks when fully visible or after fade-in completes\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState != ANIM_VISIBLE) {\n return 0; // Ignore click, avoid interference during animation\n }\n \n // Click anywhere, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID); // Stop auto-close timer\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n return 0;\n }\n \n case WM_DESTROY: {\n // Cleanup work when window is destroyed\n \n // Stop all timers\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n \n // Free message text memory\n wchar_t* message = (wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n free(message);\n }\n \n // Remove all window properties\n RemovePropW(hwnd, L\"MessageText\");\n RemovePropW(hwnd, L\"AnimState\");\n RemovePropW(hwnd, L\"Opacity\");\n return 0;\n }\n }\n \n return DefWindowProc(hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Draw rectangle with border\n * @param hdc Device context\n * @param rect Rectangle area\n * @param radius Corner radius (unused)\n * \n * Draws a rectangle with light gray border in the specified device context.\n * This function reserves the corner radius parameter, but current implementation uses standard rectangle.\n * Can be extended to support true rounded rectangles in future versions.\n */\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius) {\n // Create light gray border pen\n HPEN pen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n HPEN oldPen = (HPEN)SelectObject(hdc, pen);\n \n // Use normal rectangle instead of rounded rectangle\n Rectangle(hdc, rect.left, rect.top, rect.right, rect.bottom);\n \n // Clean up resources\n SelectObject(hdc, oldPen);\n DeleteObject(pen);\n}\n\n/**\n * @brief Close all currently displayed Catime notification windows\n * \n * Find and close all notification windows created by Catime, ignoring their current display time settings,\n * directly start fade-out animation. Usually called when switching timer modes to ensure notifications don't continue to display.\n */\nvoid CloseAllNotifications(void) {\n // Find all notification windows created by Catime\n HWND hwnd = NULL;\n HWND hwndPrev = NULL;\n \n // Use FindWindowExW to find each matching window one by one\n // First call with hwndPrev as NULL finds the first window\n // Subsequent calls pass the previously found window handle to find the next window\n while ((hwnd = FindWindowExW(NULL, hwndPrev, NOTIFICATION_CLASS_NAME, NULL)) != NULL) {\n // Check current state\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n \n // Stop current auto-close timer\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // If window hasn't started fading out yet, start fade-out animation\n if (currentState != ANIM_FADE_OUT) {\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start fade-out animation\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n \n // Save current window handle for next search\n hwndPrev = hwnd;\n }\n}\n"], ["/Catime/src/window_events.c", "/**\n * @file window_events.c\n * @brief Implementation of basic window event handling\n * \n * This file implements the basic event handling functionality for the application window,\n * including window creation, destruction, resizing, and position adjustment.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/tray.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/window_events.h\"\n\n/**\n * @brief Handle window creation event\n * @param hwnd Window handle\n * @return BOOL Processing result\n */\nBOOL HandleWindowCreate(HWND hwnd) {\n HWND hwndParent = GetParent(hwnd);\n if (hwndParent != NULL) {\n EnableWindow(hwndParent, TRUE);\n }\n \n // Load window settings\n LoadWindowSettings(hwnd);\n \n // Set click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // Ensure window is in topmost state\n SetWindowTopmost(hwnd, CLOCK_WINDOW_TOPMOST);\n \n return TRUE;\n}\n\n/**\n * @brief Handle window destruction event\n * @param hwnd Window handle\n */\nvoid HandleWindowDestroy(HWND hwnd) {\n SaveWindowSettings(hwnd); // Save window settings\n KillTimer(hwnd, 1);\n RemoveTrayIcon();\n \n // Clean up update check thread\n extern void CleanupUpdateThread(void);\n CleanupUpdateThread();\n \n PostQuitMessage(0);\n}\n\n/**\n * @brief Handle window reset event\n * @param hwnd Window handle\n */\nvoid HandleWindowReset(HWND hwnd) {\n // Unconditionally apply topmost setting from configuration\n // Regardless of the current CLOCK_WINDOW_TOPMOST value, force it to TRUE and apply\n CLOCK_WINDOW_TOPMOST = TRUE;\n SetWindowTopmost(hwnd, TRUE);\n WriteConfigTopmost(\"TRUE\");\n \n // Ensure window is always visible - solves the issue of timer not being visible after reset\n ShowWindow(hwnd, SW_SHOW);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowResize(HWND hwnd, int delta) {\n return HandleScaleWindow(hwnd, delta);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowMove(HWND hwnd) {\n return HandleDragWindow(hwnd);\n}\n"], ["/Catime/src/dialog_procedure.c", "/**\n * @file dialog_procedure.c\n * @brief Implementation of dialog message handling procedures\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/audio_player.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/dialog_language.h\"\n\nstatic void DrawColorSelectButton(HDC hdc, HWND hwnd);\n\nextern char inputText[256];\n\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES];\nextern int POMODORO_TIMES_COUNT;\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nWNDPROC wpOrigEditProc;\n\nstatic HWND g_hwndAboutDlg = NULL;\nstatic HWND g_hwndErrorDlg = NULL;\nHWND g_hwndInputDialog = NULL;\nstatic WNDPROC wpOrigLoopEditProc;\n\n#define URL_GITHUB_REPO L\"https://github.com/vladelaina/Catime\"\n\nLRESULT APIENTRY EditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n static BOOL firstKeyProcessed = FALSE;\n\n switch (msg) {\n case WM_SETFOCUS:\n PostMessage(hwnd, EM_SETSEL, 0, -1);\n firstKeyProcessed = FALSE;\n break;\n\n case WM_KEYDOWN:\n if (!firstKeyProcessed) {\n firstKeyProcessed = TRUE;\n }\n\n if (wParam == VK_RETURN) {\n HWND hwndOkButton = GetDlgItem(GetParent(hwnd), CLOCK_IDC_BUTTON_OK);\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwndOkButton);\n return 0;\n }\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n\n case WM_CHAR:\n if (wParam == 1 || (wParam == 'a' || wParam == 'A') && GetKeyState(VK_CONTROL) < 0) {\n return 0;\n }\n if (wParam == VK_RETURN) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(wpOrigEditProc, hwnd, msg, wParam, lParam);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\nvoid ShowErrorDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDD_ERROR_DIALOG),\n hwndParent,\n ErrorDlgProc);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG:\n SetDlgItemTextW(hwndDlg, IDC_ERROR_TEXT,\n GetLocalizedString(L\"输入格式无效,请重新输入。\", L\"Invalid input format, please try again.\"));\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"错误\", L\"Error\"));\n return TRUE;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Input dialog procedure\n */\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n\n g_hwndInputDialog = hwndDlg;\n\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n DWORD dlgId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n\n ApplyDialogLanguage(hwndDlg, (int)dlgId);\n\n if (dlgId == CLOCK_IDD_SHORTCUT_DIALOG) {\n }\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n\n SetFocus(hwndEdit);\n\n PostMessage(hwndDlg, WM_APP+100, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+101, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+102, 0, (LPARAM)hwndEdit);\n\n SendDlgItemMessage(hwndDlg, CLOCK_IDC_EDIT, EM_SETSEL, 0, -1);\n\n SendMessage(hwndDlg, DM_SETDEFID, CLOCK_IDC_BUTTON_OK, 0);\n\n SetTimer(hwndDlg, 9999, 50, NULL);\n\n PostMessage(hwndDlg, WM_APP+103, 0, 0);\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return FALSE;\n }\n\n case WM_CLOSE: {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n\n case WM_CTLCOLOREDIT: {\n HDC hdcEdit = (HDC)wParam;\n SetBkColor(hdcEdit, RGB(0xFF, 0xFF, 0xFF));\n if (!hEditBrush) {\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n }\n return (INT_PTR)hEditBrush;\n }\n\n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, inputText, sizeof(inputText));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (inputText[0] == '\\0' || isAllSpaces) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n int total_seconds;\n if (ParseInput(inputText, &total_seconds)) {\n int dialogId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n if (dialogId == CLOCK_IDD_POMODORO_TIME_DIALOG) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_POMODORO_LOOP_DIALOG) {\n WriteConfigPomodoroLoopCount(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_STARTUP_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_SHORTCUT_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n }\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n return TRUE;\n }\n break;\n\n case WM_TIMER:\n if (wParam == 9999) {\n KillTimer(hwndDlg, 9999);\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit && IsWindow(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n return TRUE;\n }\n break;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n int dlgId = GetDlgCtrlID((HWND)lParam);\n if (dlgId == CLOCK_IDD_COLOR_DIALOG) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n } else {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n }\n return TRUE;\n }\n break;\n\n case WM_APP+100:\n case WM_APP+101:\n case WM_APP+102:\n if (lParam) {\n HWND hwndEdit = (HWND)lParam;\n if (IsWindow(hwndEdit) && IsWindowVisible(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n }\n return TRUE;\n\n case WM_APP+103:\n {\n INPUT inputs[8] = {0};\n int inputCount = 0;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n SendInput(inputCount, inputs, sizeof(INPUT));\n }\n return TRUE;\n\n case WM_DESTROY:\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n g_hwndInputDialog = NULL;\n }\n break;\n }\n return FALSE;\n}\n\nINT_PTR CALLBACK AboutDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HICON hLargeIcon = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n hLargeIcon = (HICON)LoadImage(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDI_CATIME),\n IMAGE_ICON,\n ABOUT_ICON_SIZE,\n ABOUT_ICON_SIZE,\n LR_DEFAULTCOLOR);\n\n if (hLargeIcon) {\n SendDlgItemMessage(hwndDlg, IDC_ABOUT_ICON, STM_SETICON, (WPARAM)hLargeIcon, 0);\n }\n\n ApplyDialogLanguage(hwndDlg, IDD_ABOUT_DIALOG);\n\n const wchar_t* versionFormat = GetDialogLocalizedString(IDD_ABOUT_DIALOG, IDC_VERSION_TEXT);\n if (versionFormat) {\n wchar_t versionText[256];\n StringCbPrintfW(versionText, sizeof(versionText), versionFormat, CATIME_VERSION);\n SetDlgItemTextW(hwndDlg, IDC_VERSION_TEXT, versionText);\n }\n\n SetDlgItemTextW(hwndDlg, IDC_CREDIT_LINK, GetLocalizedString(L\"特别感谢猫屋敷梨梨Official提供的图标\", L\"Special thanks to Neko House Lili Official for the icon\"));\n SetDlgItemTextW(hwndDlg, IDC_CREDITS, GetLocalizedString(L\"鸣谢\", L\"Credits\"));\n SetDlgItemTextW(hwndDlg, IDC_BILIBILI_LINK, GetLocalizedString(L\"BiliBili\", L\"BiliBili\"));\n SetDlgItemTextW(hwndDlg, IDC_GITHUB_LINK, GetLocalizedString(L\"GitHub\", L\"GitHub\"));\n SetDlgItemTextW(hwndDlg, IDC_COPYRIGHT_LINK, GetLocalizedString(L\"版权声明\", L\"Copyright Notice\"));\n SetDlgItemTextW(hwndDlg, IDC_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n const wchar_t* dateFormat = GetLocalizedString(L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\");\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), dateFormat,\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return TRUE;\n }\n\n case WM_DESTROY:\n if (hLargeIcon) {\n DestroyIcon(hLargeIcon);\n hLargeIcon = NULL;\n }\n g_hwndAboutDlg = NULL;\n break;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n g_hwndAboutDlg = NULL;\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDIT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://space.bilibili.com/26087398\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_BILIBILI_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_BILIBILI_SPACE, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_GITHUB_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_GITHUB_REPO, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDITS) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/#thanks\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_SUPPORT) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support.html\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_COPYRIGHT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime#️copyright-notice\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n break;\n\n case WM_CLOSE:\n // Close all child dialogs\n EndDialog(hwndDlg, 0);\n g_hwndAboutDlg = NULL; // Clear dialog handle\n return TRUE;\n\n case WM_CTLCOLORSTATIC:\n {\n HDC hdc = (HDC)wParam;\n HWND hwndCtl = (HWND)lParam;\n \n if (GetDlgCtrlID(hwndCtl) == IDC_CREDIT_LINK || \n GetDlgCtrlID(hwndCtl) == IDC_BILIBILI_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_GITHUB_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_CREDITS ||\n GetDlgCtrlID(hwndCtl) == IDC_COPYRIGHT_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_SUPPORT) {\n SetTextColor(hdc, 0x00D26919); // Keep the same orange color (BGR format)\n SetBkMode(hdc, TRANSPARENT);\n return (INT_PTR)GetStockObject(NULL_BRUSH);\n }\n break;\n }\n }\n return FALSE;\n}\n\n// Add DPI awareness related type definitions (if not provided by the compiler)\n#ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n// DPI_AWARENESS_CONTEXT is a HANDLE\ntypedef HANDLE DPI_AWARENESS_CONTEXT;\n// Related DPI context constants definition\n#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n#endif\n\n// Show the About dialog\nvoid ShowAboutDialog(HWND hwndParent) {\n // If an About dialog already exists, close it first\n if (g_hwndAboutDlg != NULL && IsWindow(g_hwndAboutDlg)) {\n EndDialog(g_hwndAboutDlg, 0);\n g_hwndAboutDlg = NULL;\n }\n \n // Save current DPI awareness context\n HANDLE hOldDpiContext = NULL;\n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n // Function pointer type definitions\n typedef HANDLE (WINAPI* GetThreadDpiAwarenessContextFunc)(void);\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n \n GetThreadDpiAwarenessContextFunc getThreadDpiAwarenessContextFunc = \n (GetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"GetThreadDpiAwarenessContext\");\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (getThreadDpiAwarenessContextFunc && setThreadDpiAwarenessContextFunc) {\n // Save current DPI context\n hOldDpiContext = getThreadDpiAwarenessContextFunc();\n // Set to per-monitor DPI awareness V2 mode\n setThreadDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n }\n }\n \n // Create new About dialog\n g_hwndAboutDlg = CreateDialog(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_ABOUT_DIALOG), \n hwndParent, \n AboutDlgProc);\n \n // Restore original DPI awareness context\n if (hUser32 && hOldDpiContext) {\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (setThreadDpiAwarenessContextFunc) {\n setThreadDpiAwarenessContextFunc(hOldDpiContext);\n }\n }\n \n ShowWindow(g_hwndAboutDlg, SW_SHOW);\n}\n\n// Add global variable to track pomodoro loop count setting dialog handle\nstatic HWND g_hwndPomodoroLoopDialog = NULL;\n\nvoid ShowPomodoroLoopDialog(HWND hwndParent) {\n if (!g_hwndPomodoroLoopDialog) {\n g_hwndPomodoroLoopDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_LOOP_DIALOG),\n hwndParent,\n PomodoroLoopDlgProc\n );\n if (g_hwndPomodoroLoopDialog) {\n ShowWindow(g_hwndPomodoroLoopDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroLoopDialog);\n }\n}\n\n// Add subclassing procedure for loop count edit box\nLRESULT APIENTRY LoopEditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n switch (uMsg) {\n case WM_KEYDOWN: {\n if (wParam == VK_RETURN) {\n // Send BM_CLICK message to the parent window (dialog)\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwnd);\n return 0;\n }\n // Handle Ctrl+A select all\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n }\n case WM_CHAR: {\n // Handle Ctrl+A character message to prevent alert sound\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n // Prevent Enter key from generating character messages for further processing to avoid alert sound\n if (wParam == VK_RETURN) { // VK_RETURN (0x0D) is the char code for Enter\n return 0;\n }\n break;\n }\n }\n return CallWindowProc(wpOrigLoopEditProc, hwnd, uMsg, wParam, lParam);\n}\n\n// Modify helper function to handle numeric input with spaces\nBOOL IsValidNumberInput(const wchar_t* str) {\n // Check if empty\n if (!str || !*str) {\n return FALSE;\n }\n \n BOOL hasDigit = FALSE; // Used to track if at least one digit is found\n wchar_t cleanStr[16] = {0}; // Used to store cleaned string\n int cleanIndex = 0;\n \n // Traverse string, ignore spaces, only keep digits\n for (int i = 0; str[i]; i++) {\n if (iswdigit(str[i])) {\n cleanStr[cleanIndex++] = str[i];\n hasDigit = TRUE;\n } else if (!iswspace(str[i])) { // If not a space and not a digit, then invalid\n return FALSE;\n }\n }\n \n return hasDigit; // Return TRUE as long as there is at least one digit\n}\n\n// Modify PomodoroLoopDlgProc function\nINT_PTR CALLBACK PomodoroLoopDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_LOOP_DIALOG);\n \n // Set static text\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_STATIC, GetLocalizedString(L\"请输入循环次数(1-100):\", L\"Please enter loop count (1-100):\"));\n \n // Set focus to edit box\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetFocus(hwndEdit);\n \n // Subclass edit control\n wpOrigLoopEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, \n (LONG_PTR)LoopEditSubclassProc);\n \n return FALSE;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n wchar_t input_str[16];\n GetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, input_str, sizeof(input_str)/sizeof(wchar_t));\n \n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; input_str[i]; i++) {\n if (!iswspace(input_str[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (input_str[0] == L'\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n \n // Validate input and handle spaces\n if (!IsValidNumberInput(input_str)) {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n \n // Extract digits (ignoring spaces)\n wchar_t cleanStr[16] = {0};\n int cleanIndex = 0;\n for (int i = 0; input_str[i]; i++) {\n if (iswdigit(input_str[i])) {\n cleanStr[cleanIndex++] = input_str[i];\n }\n }\n \n int new_loop_count = _wtoi(cleanStr);\n if (new_loop_count >= 1 && new_loop_count <= 100) {\n // Update configuration file and global variables\n WriteConfigPomodoroLoopCount(new_loop_count);\n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroLoopDialog = NULL;\n } else {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n break;\n\n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigLoopEditProc);\n }\n break;\n\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n return FALSE;\n}\n\n// Add global variable to track website URL dialog handle\nstatic HWND g_hwndWebsiteDialog = NULL;\n\n// Website URL input dialog procedure\nINT_PTR CALLBACK WebsiteDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n // Set dialog as modal\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n \n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // If URL already exists, prefill the edit box\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, CLOCK_TIMEOUT_WEBSITE_URL);\n }\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_WEBSITE_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n char url[MAX_PATH] = {0};\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, url, sizeof(url));\n \n // Check if the input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; url[i]; i++) {\n if (!isspace((unsigned char)url[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (url[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n // Validate URL format - simple check, should at least contain http:// or https://\n if (strncmp(url, \"http://\", 7) != 0 && strncmp(url, \"https://\", 8) != 0) {\n // Add https:// prefix\n char tempUrl[MAX_PATH] = \"https://\";\n StringCbCatA(tempUrl, sizeof(tempUrl), url);\n StringCbCopyA(url, sizeof(url), tempUrl);\n }\n \n // Update configuration\n WriteConfigTimeoutWebsite(url);\n EndDialog(hwndDlg, IDOK);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // User cancelled, don't change timeout action\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n return FALSE;\n}\n\n// Show website URL input dialog\nvoid ShowWebsiteDialog(HWND hwndParent) {\n // Use modal dialog instead of modeless dialog, so we can know whether the user confirmed or cancelled\n INT_PTR result = DialogBox(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_WEBSITE_DIALOG),\n hwndParent,\n WebsiteDialogProc\n );\n \n // Only when the user clicks OK and inputs a valid URL will IDOK be returned, at which point WebsiteDialogProc has already set CLOCK_TIMEOUT_ACTION\n // If the user cancels or closes the dialog, the timeout action won't be changed\n}\n\n// Set global variable to track the Pomodoro combination dialog handle\nstatic HWND g_hwndPomodoroComboDialog = NULL;\n\n// Add Pomodoro combination dialog procedure\nINT_PTR CALLBACK PomodoroComboDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Read current pomodoro time options from configuration and format for display\n char currentOptions[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char timeStr[32];\n int seconds = POMODORO_TIMES[i];\n \n // Format time into human-readable format\n if (seconds >= 3600) {\n int hours = seconds / 3600;\n int mins = (seconds % 3600) / 60;\n int secs = seconds % 60;\n if (mins == 0 && secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh \", hours);\n else if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm \", hours, mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm%ds \", hours, mins, secs);\n } else if (seconds >= 60) {\n int mins = seconds / 60;\n int secs = seconds % 60;\n if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm \", mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm%ds \", mins, secs);\n } else {\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%ds \", seconds);\n }\n \n StringCbCatA(currentOptions, sizeof(currentOptions), timeStr);\n }\n \n // Remove trailing space\n if (strlen(currentOptions) > 0 && currentOptions[strlen(currentOptions) - 1] == ' ') {\n currentOptions[strlen(currentOptions) - 1] = '\\0';\n }\n \n // Set edit box text\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, currentOptions);\n \n // Apply multilingual support - moved here to ensure all default text is covered\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_COMBO_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || LOWORD(wParam) == IDOK) {\n char input[256] = {0};\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, input, sizeof(input));\n \n // Parse input time format and convert to seconds array\n char *token, *saveptr;\n char input_copy[256];\n StringCbCopyA(input_copy, sizeof(input_copy), input);\n \n int times[MAX_POMODORO_TIMES] = {0};\n int times_count = 0;\n \n token = strtok_r(input_copy, \" \", &saveptr);\n while (token && times_count < MAX_POMODORO_TIMES) {\n int seconds = 0;\n if (ParseTimeInput(token, &seconds)) {\n times[times_count++] = seconds;\n }\n token = strtok_r(NULL, \" \", &saveptr);\n }\n \n if (times_count > 0) {\n // Update global variables\n POMODORO_TIMES_COUNT = times_count;\n for (int i = 0; i < times_count; i++) {\n POMODORO_TIMES[i] = times[i];\n }\n \n // Update basic pomodoro times\n if (times_count > 0) POMODORO_WORK_TIME = times[0];\n if (times_count > 1) POMODORO_SHORT_BREAK = times[1];\n if (times_count > 2) POMODORO_LONG_BREAK = times[2];\n \n // Write to configuration file\n WriteConfigPomodoroTimeOptions(times, times_count);\n }\n \n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n }\n \n return FALSE;\n}\n\nvoid ShowPomodoroComboDialog(HWND hwndParent) {\n if (!g_hwndPomodoroComboDialog) {\n g_hwndPomodoroComboDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_COMBO_DIALOG),\n hwndParent,\n PomodoroComboDialogProc\n );\n if (g_hwndPomodoroComboDialog) {\n ShowWindow(g_hwndPomodoroComboDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroComboDialog);\n }\n}\n\nBOOL ParseTimeInput(const char* input, int* seconds) {\n if (!input || !seconds) return FALSE;\n\n *seconds = 0;\n char* buffer = _strdup(input);\n if (!buffer) return FALSE;\n\n int len = strlen(buffer);\n char* pos = buffer;\n int value = 0;\n int tempSeconds = 0;\n\n while (*pos) {\n if (isdigit((unsigned char)*pos)) {\n value = 0;\n while (isdigit((unsigned char)*pos)) {\n value = value * 10 + (*pos - '0');\n pos++;\n }\n\n if (*pos == 'h' || *pos == 'H') {\n tempSeconds += value * 3600;\n pos++;\n } else if (*pos == 'm' || *pos == 'M') {\n tempSeconds += value * 60;\n pos++;\n } else if (*pos == 's' || *pos == 'S') {\n tempSeconds += value;\n pos++;\n } else if (*pos == '\\0') {\n tempSeconds += value * 60;\n } else {\n free(buffer);\n return FALSE;\n }\n } else {\n pos++;\n }\n }\n\n free(buffer);\n *seconds = tempSeconds;\n return TRUE;\n}\n\nstatic HWND g_hwndNotificationMessagesDialog = NULL;\n\nINT_PTR CALLBACK NotificationMessagesDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n\n ReadNotificationMessagesConfig();\n \n // For handling UTF-8 Chinese characters, we need to convert to Unicode\n wchar_t wideText[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT)];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL1, \n GetLocalizedString(L\"Countdown timeout message:\", L\"Countdown timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL2, \n GetLocalizedString(L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL3,\n GetLocalizedString(L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"));\n \n // Localize button text\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"OK\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"Cancel\", L\"Cancel\"));\n \n // Subclass edit boxes to support Ctrl+A for select all\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n // Save original window procedure\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Apply the same subclassing process to other edit boxes\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Select all text in the first edit box\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_EDIT1, EM_SETSEL, 0, -1);\n \n // Set focus to the first edit box\n SetFocus(GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1));\n \n return FALSE; // Return FALSE because we manually set focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n // Get text from edit boxes (Unicode method)\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Save to configuration file and update global variables\n WriteConfigNotificationMessages(timeout_msg, pomodoro_msg, cycle_complete_msg);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification message settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification message settings dialog for modifying various notification prompt texts.\n */\nvoid ShowNotificationMessagesDialog(HWND hwndParent) {\n if (!g_hwndNotificationMessagesDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationMessagesConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_MESSAGES_DIALOG), \n hwndParent, \n NotificationMessagesDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationMessagesDialog);\n }\n}\n\n// Add global variable to track notification display settings dialog handle\nstatic HWND g_hwndNotificationDisplayDialog = NULL;\n\n// Add notification display settings dialog procedure\nINT_PTR CALLBACK NotificationDisplayDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set window to topmost\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n \n // Create brushes\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n \n // Read latest configuration\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n // Set current values to edit boxes\n char buffer[32];\n \n // Display time (seconds, support decimal) - convert milliseconds to seconds\n StringCbPrintfA(buffer, sizeof(buffer), \"%.1f\", (float)NOTIFICATION_TIMEOUT_MS / 1000.0f);\n // Remove trailing .0\n if (strlen(buffer) > 2 && buffer[strlen(buffer)-2] == '.' && buffer[strlen(buffer)-1] == '0') {\n buffer[strlen(buffer)-2] = '\\0';\n }\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, buffer);\n \n // Opacity (percentage)\n StringCbPrintfA(buffer, sizeof(buffer), \"%d\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, buffer);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_LABEL, \n GetLocalizedString(L\"Notification display time (sec):\", L\"Notification display time (sec):\"));\n \n // Modify edit box style, remove ES_NUMBER to allow decimal point\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n LONG style = GetWindowLong(hEditTime, GWL_STYLE);\n SetWindowLong(hEditTime, GWL_STYLE, style & ~ES_NUMBER);\n \n // Subclass edit boxes to support Enter key submission and input restrictions\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Set focus to time edit box\n SetFocus(hEditTime);\n \n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n char timeStr[32] = {0};\n char opacityStr[32] = {0};\n \n // Get user input values\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, timeStr, sizeof(timeStr));\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, opacityStr, sizeof(opacityStr));\n \n // Use more robust method to replace Chinese period\n // First get the text in Unicode format\n wchar_t wTimeStr[32] = {0};\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, wTimeStr, sizeof(wTimeStr)/sizeof(wchar_t));\n \n // Replace Chinese punctuation marks in Unicode text\n for (int i = 0; wTimeStr[i] != L'\\0'; i++) {\n // Recognize various punctuation marks as decimal point\n if (wTimeStr[i] == L'。' || // Chinese period\n wTimeStr[i] == L',' || // Chinese comma\n wTimeStr[i] == L',' || // English comma\n wTimeStr[i] == L'·' || // Chinese middle dot\n wTimeStr[i] == L'`' || // Backtick\n wTimeStr[i] == L':' || // Chinese colon\n wTimeStr[i] == L':' || // English colon\n wTimeStr[i] == L';' || // Chinese semicolon\n wTimeStr[i] == L';' || // English semicolon\n wTimeStr[i] == L'/' || // Forward slash\n wTimeStr[i] == L'\\\\' || // Backslash\n wTimeStr[i] == L'~' || // Tilde\n wTimeStr[i] == L'~' || // Full-width tilde\n wTimeStr[i] == L'、' || // Chinese enumeration comma\n wTimeStr[i] == L'.') { // Full-width period\n wTimeStr[i] = L'.'; // Replace with English decimal point\n }\n }\n \n // Convert processed Unicode text back to ASCII\n WideCharToMultiByte(CP_ACP, 0, wTimeStr, -1, \n timeStr, sizeof(timeStr), NULL, NULL);\n \n // Parse time (seconds) and convert to milliseconds\n float timeInSeconds = atof(timeStr);\n int timeInMs = (int)(timeInSeconds * 1000.0f);\n \n // Allow time to be set to 0 (no notification) or at least 100 milliseconds\n if (timeInMs > 0 && timeInMs < 100) timeInMs = 100;\n \n // Parse opacity\n int opacity = atoi(opacityStr);\n \n // Ensure opacity is in range 1-100\n if (opacity < 1) opacity = 1;\n if (opacity > 100) opacity = 100;\n \n // Write to configuration\n WriteConfigNotificationTimeout(timeInMs);\n WriteConfigNotificationOpacity(opacity);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n }\n break;\n \n // Add handling for WM_CLOSE message\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n HWND hEditOpacity = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEditOpacity, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification display settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification display settings dialog for modifying notification display time and opacity.\n */\nvoid ShowNotificationDisplayDialog(HWND hwndParent) {\n if (!g_hwndNotificationDisplayDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_DISPLAY_DIALOG), \n hwndParent, \n NotificationDisplayDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationDisplayDialog);\n }\n}\n\n// Add global variable to track the integrated notification settings dialog handle\nstatic HWND g_hwndNotificationSettingsDialog = NULL;\n\n/**\n * @brief Audio playback completion callback function\n * @param hwnd Window handle\n * \n * When audio playback completes, changes \"Stop\" button back to \"Test\" button\n */\nstatic void OnAudioPlaybackComplete(HWND hwnd) {\n if (hwnd && IsWindow(hwnd)) {\n const wchar_t* testText = GetLocalizedString(L\"Test\", L\"Test\");\n SetDlgItemTextW(hwnd, IDC_TEST_SOUND_BUTTON, testText);\n \n // Get dialog data\n HWND hwndTestButton = GetDlgItem(hwnd, IDC_TEST_SOUND_BUTTON);\n \n // Send WM_SETTEXT message to update button text\n if (hwndTestButton && IsWindow(hwndTestButton)) {\n SendMessageW(hwndTestButton, WM_SETTEXT, 0, (LPARAM)testText);\n }\n \n // Update global playback state\n if (g_hwndNotificationSettingsDialog == hwnd) {\n // Send message to dialog to notify state change\n SendMessage(hwnd, WM_APP + 100, 0, 0);\n }\n }\n}\n\n/**\n * @brief Populate audio dropdown box\n * @param hwndDlg Dialog handle\n */\nstatic void PopulateSoundComboBox(HWND hwndDlg) {\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n if (!hwndCombo) return;\n\n // Clear dropdown list\n SendMessage(hwndCombo, CB_RESETCONTENT, 0, 0);\n\n // Add \"None\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"None\", L\"None\"));\n \n // Add \"System Beep\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"System Beep\", L\"System Beep\"));\n\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to wide character path\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n\n // Build search path\n wchar_t wSearchPath[MAX_PATH];\n StringCbPrintfW(wSearchPath, sizeof(wSearchPath), L\"%s\\\\*.*\", wAudioPath);\n\n // Find audio files - using Unicode version of API\n WIN32_FIND_DATAW find_data;\n HANDLE hFind = FindFirstFileW(wSearchPath, &find_data);\n if (hFind != INVALID_HANDLE_VALUE) {\n do {\n // Check file extension\n wchar_t* ext = wcsrchr(find_data.cFileName, L'.');\n if (ext && (\n _wcsicmp(ext, L\".flac\") == 0 ||\n _wcsicmp(ext, L\".mp3\") == 0 ||\n _wcsicmp(ext, L\".wav\") == 0\n )) {\n // Add Unicode filename directly to dropdown\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)find_data.cFileName);\n }\n } while (FindNextFileW(hFind, &find_data));\n FindClose(hFind);\n }\n\n // Set currently selected audio file\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n // Check if it's the special system beep marker\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n // Select \"System Beep\" option (index 1)\n SendMessage(hwndCombo, CB_SETCURSEL, 1, 0);\n } else {\n wchar_t wSoundFile[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, NOTIFICATION_SOUND_FILE, -1, wSoundFile, MAX_PATH);\n \n // Get filename part\n wchar_t* fileName = wcsrchr(wSoundFile, L'\\\\');\n if (fileName) fileName++;\n else fileName = wSoundFile;\n \n // Find and select the file in dropdown\n int index = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)fileName);\n if (index != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, index, 0);\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n }\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n}\n\n/**\n * @brief Integrated notification settings dialog procedure\n * @param hwndDlg Dialog handle\n * @param msg Message type\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return INT_PTR Message processing result\n * \n * Integrates notification content and notification display settings in a unified interface\n */\nINT_PTR CALLBACK NotificationSettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static BOOL isPlaying = FALSE; // Add a static variable to track playback status\n static int originalVolume = 0; // Add a static variable to store original volume\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Read latest configuration to global variables\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n // Save original volume value for restoration when canceling\n originalVolume = NOTIFICATION_SOUND_VOLUME;\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG);\n \n // Set notification message text - using Unicode functions\n wchar_t wideText[256];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Set notification display time\n SYSTEMTIME st = {0};\n GetLocalTime(&st);\n \n // Read notification disabled setting\n ReadNotificationDisabledConfig();\n \n // Set checkbox based on disabled state\n CheckDlgButton(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK, NOTIFICATION_DISABLED ? BST_CHECKED : BST_UNCHECKED);\n \n // Enable/disable time control based on state\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !NOTIFICATION_DISABLED);\n \n // Set time control value - display actual configured time regardless of disabled state\n int totalSeconds = NOTIFICATION_TIMEOUT_MS / 1000;\n st.wHour = totalSeconds / 3600;\n st.wMinute = (totalSeconds % 3600) / 60;\n st.wSecond = totalSeconds % 60;\n \n // Set time control's initial value\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_SETSYSTEMTIME, \n GDT_VALID, (LPARAM)&st);\n\n // Set notification opacity slider\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n SendMessage(hwndOpacitySlider, TBM_SETRANGE, TRUE, MAKELONG(1, 100));\n SendMessage(hwndOpacitySlider, TBM_SETPOS, TRUE, NOTIFICATION_MAX_OPACITY);\n \n // Update opacity text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n // Set notification type radio buttons\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_OS:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_OS, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, BST_CHECKED);\n break;\n }\n \n // Populate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Set volume slider\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n SendMessage(hwndSlider, TBM_SETRANGE, TRUE, MAKELONG(0, 100));\n SendMessage(hwndSlider, TBM_SETPOS, TRUE, NOTIFICATION_SOUND_VOLUME);\n \n // Update volume text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", NOTIFICATION_SOUND_VOLUME);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Reset playback state on initialization\n isPlaying = FALSE;\n \n // Set audio playback completion callback\n SetAudioPlaybackCompleteCallback(hwndDlg, OnAudioPlaybackComplete);\n \n // Save dialog handle\n g_hwndNotificationSettingsDialog = hwndDlg;\n \n return TRUE;\n }\n \n case WM_HSCROLL: {\n // Handle slider drag events\n if (GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER) == (HWND)lParam) {\n // Get slider's current position\n int volume = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update volume percentage text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", volume);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Apply volume setting in real-time\n SetAudioVolume(volume);\n \n return TRUE;\n }\n else if (GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT) == (HWND)lParam) {\n // Get slider's current position\n int opacity = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update opacity percentage text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", opacity);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND:\n // Handle notification disable checkbox state change\n if (LOWORD(wParam) == IDC_DISABLE_NOTIFICATION_CHECK && HIWORD(wParam) == BN_CLICKED) {\n BOOL isChecked = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !isChecked);\n return TRUE;\n }\n else if (LOWORD(wParam) == IDOK) {\n // Get notification message text - using Unicode functions\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Get notification display time\n SYSTEMTIME st = {0};\n \n // Check if notification disable checkbox is checked\n BOOL isDisabled = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n \n // Save disabled state\n NOTIFICATION_DISABLED = isDisabled;\n WriteConfigNotificationDisabled(isDisabled);\n \n // Get notification time settings\n // Get notification time settings\n if (SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_GETSYSTEMTIME, 0, (LPARAM)&st) == GDT_VALID) {\n // Calculate total seconds: hours*3600 + minutes*60 + seconds\n int totalSeconds = st.wHour * 3600 + st.wMinute * 60 + st.wSecond;\n \n if (totalSeconds == 0) {\n // If time is 00:00:00, set to 0 (meaning disable notifications)\n NOTIFICATION_TIMEOUT_MS = 0;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n \n } else if (!isDisabled) {\n // Only update non-zero notification time if not disabled\n NOTIFICATION_TIMEOUT_MS = totalSeconds * 1000;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n }\n }\n // If notifications are disabled, don't modify notification time configuration\n \n // Get notification opacity (from slider)\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n int opacity = (int)SendMessage(hwndOpacitySlider, TBM_GETPOS, 0, 0);\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n \n // Get notification type\n if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_OS)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n }\n \n // Get selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n if (index > 0) { // 0 is \"None\" option\n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Check if \"System Beep\" is selected\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker to represent system beep\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n } else {\n NOTIFICATION_SOUND_FILE[0] = '\\0';\n }\n \n // Get volume slider position\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n NOTIFICATION_SOUND_VOLUME = volume;\n \n // Save all settings\n WriteConfigNotificationMessages(\n timeout_msg,\n pomodoro_msg,\n cycle_complete_msg\n );\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n WriteConfigNotificationOpacity(NOTIFICATION_MAX_OPACITY);\n WriteConfigNotificationType(NOTIFICATION_TYPE);\n WriteConfigNotificationSound(NOTIFICATION_SOUND_FILE);\n WriteConfigNotificationVolume(NOTIFICATION_SOUND_VOLUME);\n \n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Restore original volume setting\n NOTIFICATION_SOUND_VOLUME = originalVolume;\n \n // Reapply original volume\n SetAudioVolume(originalVolume);\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDC_TEST_SOUND_BUTTON) {\n if (!isPlaying) {\n // Currently not playing, start playback and change button text to \"Stop\"\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n \n if (index > 0) { // 0 is the \"None\" option\n // Get current slider volume and apply it\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n SetAudioVolume(volume);\n \n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Temporarily save current audio settings\n char tempSoundFile[MAX_PATH];\n StringCbCopyA(tempSoundFile, sizeof(tempSoundFile), NOTIFICATION_SOUND_FILE);\n \n // Temporarily set audio file\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n \n // Play audio\n if (PlayNotificationSound(hwndDlg)) {\n // Playback successful, change button text to \"Stop\"\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Stop\", L\"Stop\"));\n isPlaying = TRUE;\n }\n \n // Restore previous settings\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), tempSoundFile);\n }\n } else {\n // Currently playing, stop playback and restore button text\n StopNotificationSound();\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Test\", L\"Test\"));\n isPlaying = FALSE;\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDC_OPEN_SOUND_DIR_BUTTON) {\n // Get audio directory path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Ensure directory exists\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n \n // Open directory\n ShellExecuteW(hwndDlg, L\"open\", wAudioPath, NULL, NULL, SW_SHOWNORMAL);\n \n // Record currently selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Try to restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n } else {\n // If previous selection not found, default to \"None\"\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0);\n }\n }\n \n return TRUE;\n } else if (LOWORD(wParam) == IDC_NOTIFICATION_SOUND_COMBO && HIWORD(wParam) == CBN_DROPDOWN) {\n // When dropdown is about to open, reload file list\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n \n // Record currently selected file\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n }\n }\n \n return TRUE;\n }\n break;\n \n // Add custom message handling for audio playback completion notification\n case WM_APP + 100:\n // Audio playback is complete, update button state\n isPlaying = FALSE;\n return TRUE;\n \n case WM_CLOSE:\n // Make sure to stop playback when closing dialog\n if (isPlaying) {\n StopNotificationSound();\n }\n \n // Clean up callback\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Clean up callback when dialog is destroyed\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n g_hwndNotificationSettingsDialog = NULL;\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Display integrated notification settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays a unified dialog that includes both notification content and display settings\n */\nvoid ShowNotificationSettingsDialog(HWND hwndParent) {\n if (!g_hwndNotificationSettingsDialog) {\n // Ensure the latest configuration values are read first\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG), \n hwndParent, \n NotificationSettingsDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationSettingsDialog);\n }\n}"], ["/Catime/src/shortcut_checker.c", "/**\n * @file shortcut_checker.c\n * @brief Implementation of desktop shortcut detection and creation\n *\n * Detects if the program is installed from the App Store or WinGet,\n * and creates a desktop shortcut when necessary.\n */\n\n#include \"../include/shortcut_checker.h\"\n#include \"../include/config.h\"\n#include \"../include/log.h\" // Include log header\n#include // For printf debug output\n#include \n#include \n#include \n#include \n#include \n#include \n\n// Import required COM interfaces\n#include \n\n// We don't need to manually define IID_IShellLinkA, it's already defined in system headers\n\n/**\n * @brief Check if a string starts with a specified prefix\n * \n * @param str The string to check\n * @param prefix The prefix string\n * @return bool true if the string starts with the specified prefix, false otherwise\n */\nstatic bool StartsWith(const char* str, const char* prefix) {\n size_t prefix_len = strlen(prefix);\n size_t str_len = strlen(str);\n \n if (str_len < prefix_len) {\n return false;\n }\n \n return strncmp(str, prefix, prefix_len) == 0;\n}\n\n/**\n * @brief Check if a string contains a specified substring\n * \n * @param str The string to check\n * @param substring The substring\n * @return bool true if the string contains the specified substring, false otherwise\n */\nstatic bool Contains(const char* str, const char* substring) {\n return strstr(str, substring) != NULL;\n}\n\n/**\n * @brief Check if the program is installed from the App Store or WinGet\n * \n * @param exe_path Buffer to output the program path\n * @param path_size Buffer size\n * @return bool true if installed from the App Store or WinGet, false otherwise\n */\nstatic bool IsStoreOrWingetInstall(char* exe_path, size_t path_size) {\n // Get program path\n if (GetModuleFileNameA(NULL, exe_path, path_size) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n return false;\n }\n \n LOG_DEBUG(\"Checking program path: %s\", exe_path);\n \n // Check if it's an App Store installation path (starts with C:\\Program Files\\WindowsApps)\n if (StartsWith(exe_path, \"C:\\\\Program Files\\\\WindowsApps\")) {\n LOG_DEBUG(\"Detected App Store installation path\");\n return true;\n }\n \n // Check if it's a WinGet installation path\n // 1. Regular path containing \\AppData\\Local\\Microsoft\\WinGet\\Packages\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\WinGet\\\\Packages\")) {\n LOG_DEBUG(\"Detected WinGet installation path (regular)\");\n return true;\n }\n \n // 2. Possible custom WinGet installation path (if in C:\\Users\\username\\AppData\\Local\\Microsoft\\*)\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\\") && Contains(exe_path, \"WinGet\")) {\n LOG_DEBUG(\"Detected possible WinGet installation path (custom)\");\n return true;\n }\n \n // Force test: When the path contains specific strings, consider it a path that needs to create shortcuts\n // This test path matches the installation path seen in user logs\n if (Contains(exe_path, \"\\\\WinGet\\\\catime.exe\")) {\n LOG_DEBUG(\"Detected specific WinGet installation path\");\n return true;\n }\n \n LOG_DEBUG(\"Not a Store or WinGet installation path\");\n return false;\n}\n\n/**\n * @brief Check if the desktop already has a shortcut and if the shortcut points to the current program\n * \n * @param exe_path Program path\n * @param shortcut_path_out If a shortcut is found, output the shortcut path\n * @param shortcut_path_size Shortcut path buffer size\n * @param target_path_out If a shortcut is found, output the shortcut target path\n * @param target_path_size Target path buffer size\n * @return int 0=shortcut not found, 1=shortcut found and points to current program, 2=shortcut found but points to another path\n */\nstatic int CheckShortcutTarget(const char* exe_path, char* shortcut_path_out, size_t shortcut_path_size, \n char* target_path_out, size_t target_path_size) {\n char desktop_path[MAX_PATH];\n char public_desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char link_target[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n WIN32_FIND_DATAA find_data;\n int result = 0;\n \n // Get user desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n LOG_DEBUG(\"User desktop path: %s\", desktop_path);\n \n // Get public desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_COMMON_DESKTOPDIRECTORY, NULL, 0, public_desktop_path);\n if (FAILED(hr)) {\n LOG_WARNING(\"Failed to get public desktop path, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_DEBUG(\"Public desktop path: %s\", public_desktop_path);\n }\n \n // First check user desktop - build complete shortcut path (Catime.lnk)\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n LOG_DEBUG(\"Checking user desktop shortcut: %s\", shortcut_path);\n \n // Check if the user desktop shortcut file exists\n bool file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n \n // If not found on user desktop, check public desktop\n if (!file_exists && SUCCEEDED(hr)) {\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", public_desktop_path);\n LOG_DEBUG(\"Checking public desktop shortcut: %s\", shortcut_path);\n \n file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n }\n \n // If no shortcut file is found, return 0 directly\n if (!file_exists) {\n LOG_DEBUG(\"No shortcut files found\");\n return 0;\n }\n \n // Save the found shortcut path to the output parameter\n if (shortcut_path_out && shortcut_path_size > 0) {\n strncpy(shortcut_path_out, shortcut_path, shortcut_path_size);\n shortcut_path_out[shortcut_path_size - 1] = '\\0';\n }\n \n // Found shortcut file, get its target\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Convert to wide character\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_ACP, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Load shortcut\n hr = ppf->lpVtbl->Load(ppf, wide_path, STGM_READ);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to load shortcut, hr=0x%08X\", (unsigned int)hr);\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Get shortcut target path\n hr = psl->lpVtbl->GetPath(psl, link_target, MAX_PATH, &find_data, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get shortcut target path, hr=0x%08X\", (unsigned int)hr);\n result = 0;\n } else {\n LOG_DEBUG(\"Shortcut target path: %s\", link_target);\n LOG_DEBUG(\"Current program path: %s\", exe_path);\n \n // Save target path to output parameter\n if (target_path_out && target_path_size > 0) {\n strncpy(target_path_out, link_target, target_path_size);\n target_path_out[target_path_size - 1] = '\\0';\n }\n \n // Check if the shortcut points to the current program\n if (_stricmp(link_target, exe_path) == 0) {\n LOG_DEBUG(\"Shortcut points to current program\");\n result = 1;\n } else {\n LOG_DEBUG(\"Shortcut points to another path\");\n result = 2;\n }\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return result;\n}\n\n/**\n * @brief Create or update desktop shortcut\n * \n * @param exe_path Program path\n * @param existing_shortcut_path Existing shortcut path, create new one if NULL\n * @return bool true for successful creation/update, false for failure\n */\nstatic bool CreateOrUpdateDesktopShortcut(const char* exe_path, const char* existing_shortcut_path) {\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char icon_path[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n bool success = false;\n \n // If an existing shortcut path is provided, use it; otherwise create a new shortcut on the user's desktop\n if (existing_shortcut_path && *existing_shortcut_path) {\n LOG_INFO(\"Starting to update desktop shortcut: %s pointing to: %s\", existing_shortcut_path, exe_path);\n strcpy(shortcut_path, existing_shortcut_path);\n } else {\n LOG_INFO(\"Starting to create desktop shortcut, program path: %s\", exe_path);\n \n // Get desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n LOG_DEBUG(\"Desktop path: %s\", desktop_path);\n \n // Build complete shortcut path\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n }\n \n LOG_DEBUG(\"Shortcut path: %s\", shortcut_path);\n \n // Use program path as icon path\n strcpy(icon_path, exe_path);\n \n // Create IShellLink interface\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n \n // Set target path\n hr = psl->lpVtbl->SetPath(psl, exe_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set shortcut target path, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Set working directory (use the directory where the executable is located)\n char work_dir[MAX_PATH];\n strcpy(work_dir, exe_path);\n char* last_slash = strrchr(work_dir, '\\\\');\n if (last_slash) {\n *last_slash = '\\0';\n }\n LOG_DEBUG(\"Working directory: %s\", work_dir);\n \n hr = psl->lpVtbl->SetWorkingDirectory(psl, work_dir);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set working directory, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set icon\n hr = psl->lpVtbl->SetIconLocation(psl, icon_path, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set icon, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set description\n hr = psl->lpVtbl->SetDescription(psl, \"A very useful timer (Pomodoro Clock)\");\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set description, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set window style (normal window)\n psl->lpVtbl->SetShowCmd(psl, SW_SHOWNORMAL);\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Convert to wide characters\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Save shortcut\n hr = ppf->lpVtbl->Save(ppf, wide_path, TRUE);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to save shortcut, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_INFO(\"Desktop shortcut %s successful: %s\", existing_shortcut_path ? \"update\" : \"creation\", shortcut_path);\n success = true;\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return success;\n}\n\n/**\n * @brief Check and create desktop shortcut\n * \n * All installation types will check if the desktop shortcut exists and points to the current program.\n * If the shortcut already exists but points to another program, it will be updated to the current path.\n * But only versions installed from the Windows App Store or WinGet will create a new shortcut.\n * If SHORTCUT_CHECK_DONE=TRUE is marked in the configuration file, no new shortcut will be created even if the shortcut is deleted.\n * \n * @return int 0 means no need to create/update or create/update successful, 1 means failure\n */\nint CheckAndCreateShortcut(void) {\n char exe_path[MAX_PATH];\n char config_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char target_path[MAX_PATH];\n bool shortcut_check_done = false;\n bool isStoreInstall = false;\n \n // Initialize COM library, needed for creating shortcuts later\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM library initialization failed, hr=0x%08X\", (unsigned int)hr);\n return 1;\n }\n \n LOG_DEBUG(\"Starting shortcut check\");\n \n // Read the flag from the configuration file to determine if it has been checked\n GetConfigPath(config_path, MAX_PATH);\n shortcut_check_done = IsShortcutCheckDone();\n \n LOG_DEBUG(\"Configuration path: %s, already checked: %d\", config_path, shortcut_check_done);\n \n // Get current program path\n if (GetModuleFileNameA(NULL, exe_path, MAX_PATH) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n CoUninitialize();\n return 1;\n }\n LOG_DEBUG(\"Program path: %s\", exe_path);\n \n // Check if it's an App Store or WinGet installation (only affects the behavior of creating new shortcuts)\n isStoreInstall = IsStoreOrWingetInstall(exe_path, MAX_PATH);\n LOG_DEBUG(\"Is Store/WinGet installation: %d\", isStoreInstall);\n \n // Check if the shortcut exists and points to the current program\n // Return value: 0=does not exist, 1=exists and points to the current program, 2=exists but points to another path\n int shortcut_status = CheckShortcutTarget(exe_path, shortcut_path, MAX_PATH, target_path, MAX_PATH);\n \n if (shortcut_status == 0) {\n // Shortcut does not exist\n if (shortcut_check_done) {\n // If the configuration has already been marked as checked, don't create it even if there's no shortcut\n LOG_INFO(\"No shortcut found on desktop, but configuration marked as checked, not creating\");\n CoUninitialize();\n return 0;\n } else if (isStoreInstall) {\n // Only first-run Store or WinGet installations create shortcuts\n LOG_INFO(\"No shortcut found on desktop, first run of Store/WinGet installation, starting to create\");\n bool success = CreateOrUpdateDesktopShortcut(exe_path, NULL);\n \n // Mark as checked, regardless of whether creation was successful\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return success ? 0 : 1;\n } else {\n LOG_INFO(\"No shortcut found on desktop, not a Store/WinGet installation, not creating shortcut\");\n \n // Mark as checked\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return 0;\n }\n } else if (shortcut_status == 1) {\n // Shortcut exists and points to the current program, no action needed\n LOG_INFO(\"Desktop shortcut already exists and points to the current program\");\n \n // Mark as checked\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return 0;\n } else if (shortcut_status == 2) {\n // Shortcut exists but points to another program, any installation method will update it\n LOG_INFO(\"Desktop shortcut points to another path: %s, will update to: %s\", target_path, exe_path);\n bool success = CreateOrUpdateDesktopShortcut(exe_path, shortcut_path);\n \n // Mark as checked, regardless of whether the update was successful\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return success ? 0 : 1;\n }\n \n // Should not reach here\n LOG_ERROR(\"Unknown shortcut check status\");\n CoUninitialize();\n return 1;\n} "], ["/Catime/src/log.c", "/**\n * @file log.c\n * @brief Log recording functionality implementation\n * \n * Implements logging functionality, including file writing, error code retrieval, etc.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/log.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n\n// Add check for ARM64 macro\n#ifndef PROCESSOR_ARCHITECTURE_ARM64\n#define PROCESSOR_ARCHITECTURE_ARM64 12\n#endif\n\n// Log file path\nstatic char LOG_FILE_PATH[MAX_PATH] = {0};\nstatic FILE* logFile = NULL;\nstatic CRITICAL_SECTION logCS;\n\n// Log level string representations\nstatic const char* LOG_LEVEL_STRINGS[] = {\n \"DEBUG\",\n \"INFO\",\n \"WARNING\",\n \"ERROR\",\n \"FATAL\"\n};\n\n/**\n * @brief Get operating system version information\n * \n * Use Windows API to get operating system version, version number, build and other information\n */\nstatic void LogSystemInformation(void) {\n // Get system information\n SYSTEM_INFO si;\n GetNativeSystemInfo(&si);\n \n // Use RtlGetVersion to get system version more accurately, because GetVersionEx was changed in newer Windows versions\n typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);\n HMODULE hNtdll = GetModuleHandleW(L\"ntdll.dll\");\n \n DWORD major = 0, minor = 0, build = 0;\n BOOL isWorkstation = TRUE;\n BOOL isServer = FALSE;\n \n if (hNtdll) {\n RtlGetVersionPtr pRtlGetVersion = (RtlGetVersionPtr)GetProcAddress(hNtdll, \"RtlGetVersion\");\n if (pRtlGetVersion) {\n RTL_OSVERSIONINFOW rovi = { 0 };\n rovi.dwOSVersionInfoSize = sizeof(rovi);\n if (pRtlGetVersion(&rovi) == 0) { // STATUS_SUCCESS = 0\n major = rovi.dwMajorVersion;\n minor = rovi.dwMinorVersion;\n build = rovi.dwBuildNumber;\n }\n }\n }\n \n // If the above method fails, try the method below\n if (major == 0) {\n OSVERSIONINFOEXA osvi;\n ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA));\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA);\n \n typedef LONG (WINAPI* PRTLGETVERSION)(OSVERSIONINFOEXW*);\n PRTLGETVERSION pRtlGetVersion;\n pRtlGetVersion = (PRTLGETVERSION)GetProcAddress(GetModuleHandle(TEXT(\"ntdll.dll\")), \"RtlGetVersion\");\n \n if (pRtlGetVersion) {\n pRtlGetVersion((OSVERSIONINFOEXW*)&osvi);\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n // Finally try using GetVersionExA, although it may not be accurate\n if (GetVersionExA((OSVERSIONINFOA*)&osvi)) {\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n WriteLog(LOG_LEVEL_WARNING, \"Unable to get operating system version information\");\n }\n }\n }\n \n // Detect specific Windows version\n const char* windowsVersion = \"Unknown version\";\n \n // Determine specific version based on version number\n if (major == 10) {\n if (build >= 22000) {\n windowsVersion = \"Windows 11\";\n } else {\n windowsVersion = \"Windows 10\";\n }\n } else if (major == 6) {\n if (minor == 3) {\n windowsVersion = \"Windows 8.1\";\n } else if (minor == 2) {\n windowsVersion = \"Windows 8\";\n } else if (minor == 1) {\n windowsVersion = \"Windows 7\";\n } else if (minor == 0) {\n windowsVersion = \"Windows Vista\";\n }\n } else if (major == 5) {\n if (minor == 2) {\n windowsVersion = \"Windows Server 2003\";\n if (isWorkstation && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {\n windowsVersion = \"Windows XP Professional x64\";\n }\n } else if (minor == 1) {\n windowsVersion = \"Windows XP\";\n } else if (minor == 0) {\n windowsVersion = \"Windows 2000\";\n }\n }\n \n WriteLog(LOG_LEVEL_INFO, \"Operating System: %s (%d.%d) Build %d %s\", \n windowsVersion,\n major, minor, \n build, \n isWorkstation ? \"Workstation\" : \"Server\");\n \n // CPU architecture\n const char* arch;\n switch (si.wProcessorArchitecture) {\n case PROCESSOR_ARCHITECTURE_AMD64:\n arch = \"x64 (AMD64)\";\n break;\n case PROCESSOR_ARCHITECTURE_INTEL:\n arch = \"x86 (Intel)\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM:\n arch = \"ARM\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM64:\n arch = \"ARM64\";\n break;\n default:\n arch = \"Unknown\";\n break;\n }\n WriteLog(LOG_LEVEL_INFO, \"CPU Architecture: %s\", arch);\n \n // System memory information\n MEMORYSTATUSEX memInfo;\n memInfo.dwLength = sizeof(MEMORYSTATUSEX);\n if (GlobalMemoryStatusEx(&memInfo)) {\n WriteLog(LOG_LEVEL_INFO, \"Physical Memory: %.2f GB / %.2f GB (%d%% used)\", \n (memInfo.ullTotalPhys - memInfo.ullAvailPhys) / (1024.0 * 1024 * 1024), \n memInfo.ullTotalPhys / (1024.0 * 1024 * 1024),\n memInfo.dwMemoryLoad);\n }\n \n // Don't get screen resolution information as it's not accurate and not necessary for debugging\n \n // Check if UAC is enabled\n BOOL uacEnabled = FALSE;\n HANDLE hToken;\n if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {\n TOKEN_ELEVATION_TYPE elevationType;\n DWORD dwSize;\n if (GetTokenInformation(hToken, TokenElevationType, &elevationType, sizeof(elevationType), &dwSize)) {\n uacEnabled = (elevationType != TokenElevationTypeDefault);\n }\n CloseHandle(hToken);\n }\n WriteLog(LOG_LEVEL_INFO, \"UAC Status: %s\", uacEnabled ? \"Enabled\" : \"Disabled\");\n \n // Check if running as administrator\n BOOL isAdmin = FALSE;\n SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;\n PSID AdministratorsGroup;\n if (AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup)) {\n if (CheckTokenMembership(NULL, AdministratorsGroup, &isAdmin)) {\n WriteLog(LOG_LEVEL_INFO, \"Administrator Privileges: %s\", isAdmin ? \"Yes\" : \"No\");\n }\n FreeSid(AdministratorsGroup);\n }\n}\n\n/**\n * @brief Get log file path\n * \n * Build log filename based on config file path\n * \n * @param logPath Log path buffer\n * @param size Buffer size\n */\nstatic void GetLogFilePath(char* logPath, size_t size) {\n char configPath[MAX_PATH] = {0};\n \n // Get directory containing config file\n GetConfigPath(configPath, MAX_PATH);\n \n // Determine config file directory\n char* lastSeparator = strrchr(configPath, '\\\\');\n if (lastSeparator) {\n size_t dirLen = lastSeparator - configPath + 1;\n \n // Copy directory part\n strncpy(logPath, configPath, dirLen);\n \n // Use simple log filename\n _snprintf_s(logPath + dirLen, size - dirLen, _TRUNCATE, \"Catime_Logs.log\");\n } else {\n // If config directory can't be determined, use current directory\n _snprintf_s(logPath, size, _TRUNCATE, \"Catime_Logs.log\");\n }\n}\n\nBOOL InitializeLogSystem(void) {\n InitializeCriticalSection(&logCS);\n \n GetLogFilePath(LOG_FILE_PATH, MAX_PATH);\n \n // Open file in write mode each startup, which clears existing content\n logFile = fopen(LOG_FILE_PATH, \"w\");\n if (!logFile) {\n // Failed to create log file\n return FALSE;\n }\n \n // Record log system initialization information\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n // First record software version\n WriteLog(LOG_LEVEL_INFO, \"Catime Version: %s\", CATIME_VERSION);\n // Then record system environment information (before any possible errors)\n WriteLog(LOG_LEVEL_INFO, \"-----------------System Information-----------------\");\n LogSystemInformation();\n WriteLog(LOG_LEVEL_INFO, \"-----------------Application Information-----------------\");\n WriteLog(LOG_LEVEL_INFO, \"Log system initialization complete, Catime started\");\n \n return TRUE;\n}\n\nvoid WriteLog(LogLevel level, const char* format, ...) {\n if (!logFile) {\n return;\n }\n \n EnterCriticalSection(&logCS);\n \n // Get current time\n time_t now;\n struct tm local_time;\n char timeStr[32] = {0};\n \n time(&now);\n localtime_s(&local_time, &now);\n strftime(timeStr, sizeof(timeStr), \"%Y-%m-%d %H:%M:%S\", &local_time);\n \n // Write log header\n fprintf(logFile, \"[%s] [%s] \", timeStr, LOG_LEVEL_STRINGS[level]);\n \n // Format and write log content\n va_list args;\n va_start(args, format);\n vfprintf(logFile, format, args);\n va_end(args);\n \n // New line\n fprintf(logFile, \"\\n\");\n \n // Flush buffer immediately to ensure logs are saved even if program crashes\n fflush(logFile);\n \n LeaveCriticalSection(&logCS);\n}\n\nvoid GetLastErrorDescription(DWORD errorCode, char* buffer, int bufferSize) {\n if (!buffer || bufferSize <= 0) {\n return;\n }\n \n LPSTR messageBuffer = NULL;\n DWORD size = FormatMessageA(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | \n FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL,\n errorCode,\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n (LPSTR)&messageBuffer,\n 0, NULL);\n \n if (size > 0) {\n // Remove trailing newlines\n if (size >= 2 && messageBuffer[size-2] == '\\r' && messageBuffer[size-1] == '\\n') {\n messageBuffer[size-2] = '\\0';\n }\n \n strncpy_s(buffer, bufferSize, messageBuffer, _TRUNCATE);\n LocalFree(messageBuffer);\n } else {\n _snprintf_s(buffer, bufferSize, _TRUNCATE, \"Unknown error (code: %lu)\", errorCode);\n }\n}\n\n// Signal handler function - used to handle various C standard signals\nvoid SignalHandler(int signal) {\n char errorMsg[256] = {0};\n \n switch (signal) {\n case SIGFPE:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Floating point exception\");\n break;\n case SIGILL:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Illegal instruction\");\n break;\n case SIGSEGV:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Segmentation fault/memory access error\");\n break;\n case SIGTERM:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Termination signal\");\n break;\n case SIGABRT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Abnormal termination/abort\");\n break;\n case SIGINT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"User interrupt\");\n break;\n default:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Unknown signal\");\n break;\n }\n \n // Record exception information\n if (logFile) {\n fprintf(logFile, \"[FATAL] Fatal signal occurred: %s (signal number: %d)\\n\", \n errorMsg, signal);\n fflush(logFile);\n \n // Close log file\n fclose(logFile);\n logFile = NULL;\n }\n \n // Display error message box\n MessageBox(NULL, \"The program encountered a serious error. Please check the log file for detailed information.\", \"Fatal Error\", MB_ICONERROR | MB_OK);\n \n // Terminate program\n exit(signal);\n}\n\nvoid SetupExceptionHandler(void) {\n // Set up standard C signal handlers\n signal(SIGFPE, SignalHandler); // Floating point exception\n signal(SIGILL, SignalHandler); // Illegal instruction\n signal(SIGSEGV, SignalHandler); // Segmentation fault\n signal(SIGTERM, SignalHandler); // Termination signal\n signal(SIGABRT, SignalHandler); // Abnormal termination\n signal(SIGINT, SignalHandler); // User interrupt\n}\n\n// Call this function when program exits to clean up log resources\nvoid CleanupLogSystem(void) {\n if (logFile) {\n WriteLog(LOG_LEVEL_INFO, \"Catime exited normally\");\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n fclose(logFile);\n logFile = NULL;\n }\n \n DeleteCriticalSection(&logCS);\n}\n"], ["/Catime/src/window_procedure.c", "/**\n * @file window_procedure.c\n * @brief Window message processing implementation\n * \n * This file implements the message processing callback function for the application's main window,\n * handling all message events for the window.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\" \n#include \"../include/window.h\" \n#include \"../include/startup.h\" \n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/window_events.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/drawing.h\"\n#include \"../include/timer_events.h\"\n#include \"../include/tray_events.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/notification.h\" // Add notification header\n\n// Variables imported from main.c\nextern char inputText[256];\nextern int elapsed_time;\nextern int message_shown;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void PauseMediaPlayback(void);\n\n// Add these external variable declarations at the beginning of the file\nextern int POMODORO_TIMES[10]; // Pomodoro time array\nextern int POMODORO_TIMES_COUNT; // Number of pomodoro time options\nextern int current_pomodoro_time_index; // Current pomodoro time index\nextern int complete_pomodoro_cycles; // Completed pomodoro cycles\n\n// If ShowInputDialog function needs to be declared, add at the beginning\nextern BOOL ShowInputDialog(HWND hwnd, char* text);\n\n// Modify to match the correct function declaration in config.h\nextern void WriteConfigPomodoroTimeOptions(int* times, int count);\n\n// If the function doesn't exist, use an existing similar function\n// For example, modify calls to WriteConfigPomodoroTimeOptions to WriteConfigPomodoroTimes\n\n// Add at the beginning of the file\ntypedef struct {\n const wchar_t* title;\n const wchar_t* prompt;\n const wchar_t* defaultText;\n wchar_t* result;\n size_t maxLen;\n} INPUTBOX_PARAMS;\n\n// Add declaration for ShowPomodoroLoopDialog function at the beginning of the file\nextern void ShowPomodoroLoopDialog(HWND hwndParent);\n\n// Add declaration for OpenUserGuide function\nextern void OpenUserGuide(void);\n\n// Add declaration for OpenSupportPage function\nextern void OpenSupportPage(void);\n\n// Add declaration for OpenFeedbackPage function\nextern void OpenFeedbackPage(void);\n\n// Helper function: Check if a string contains only spaces\nstatic BOOL isAllSpacesOnly(const char* str) {\n for (int i = 0; str[i]; i++) {\n if (!isspace((unsigned char)str[i])) {\n return FALSE;\n }\n }\n return TRUE;\n}\n\n/**\n * @brief Input dialog callback function\n * @param hwndDlg Dialog handle\n * @param uMsg Message\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return Processing result\n */\nINT_PTR CALLBACK InputBoxProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {\n static wchar_t* result;\n static size_t maxLen;\n \n switch (uMsg) {\n case WM_INITDIALOG: {\n // Get passed parameters\n INPUTBOX_PARAMS* params = (INPUTBOX_PARAMS*)lParam;\n result = params->result;\n maxLen = params->maxLen;\n \n // Set dialog title\n SetWindowTextW(hwndDlg, params->title);\n \n // Set prompt message\n SetDlgItemTextW(hwndDlg, IDC_STATIC_PROMPT, params->prompt);\n \n // Set default text\n SetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, params->defaultText);\n \n // Select text\n SendDlgItemMessageW(hwndDlg, IDC_EDIT_INPUT, EM_SETSEL, 0, -1);\n \n // Set focus\n SetFocus(GetDlgItem(hwndDlg, IDC_EDIT_INPUT));\n return FALSE;\n }\n \n case WM_COMMAND:\n switch (LOWORD(wParam)) {\n case IDOK: {\n // Get input text\n GetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, result, (int)maxLen);\n EndDialog(hwndDlg, TRUE);\n return TRUE;\n }\n \n case IDCANCEL:\n // Cancel operation\n EndDialog(hwndDlg, FALSE);\n return TRUE;\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display input dialog\n * @param hwndParent Parent window handle\n * @param title Dialog title\n * @param prompt Prompt message\n * @param defaultText Default text\n * @param result Result buffer\n * @param maxLen Maximum buffer length\n * @return TRUE if successful, FALSE if canceled\n */\nBOOL InputBox(HWND hwndParent, const wchar_t* title, const wchar_t* prompt, \n const wchar_t* defaultText, wchar_t* result, size_t maxLen) {\n // Prepare parameters to pass to dialog\n INPUTBOX_PARAMS params;\n params.title = title;\n params.prompt = prompt;\n params.defaultText = defaultText;\n params.result = result;\n params.maxLen = maxLen;\n \n // Display modal dialog\n return DialogBoxParamW(GetModuleHandle(NULL), \n MAKEINTRESOURCEW(IDD_INPUTBOX), \n hwndParent, \n InputBoxProc, \n (LPARAM)¶ms) == TRUE;\n}\n\nvoid ExitProgram(HWND hwnd) {\n RemoveTrayIcon();\n\n PostQuitMessage(0);\n}\n\n#define HOTKEY_ID_SHOW_TIME 100 // Hotkey ID to show current time\n#define HOTKEY_ID_COUNT_UP 101 // Hotkey ID for count up timer\n#define HOTKEY_ID_COUNTDOWN 102 // Hotkey ID for countdown timer\n#define HOTKEY_ID_QUICK_COUNTDOWN1 103 // Hotkey ID for quick countdown 1\n#define HOTKEY_ID_QUICK_COUNTDOWN2 104 // Hotkey ID for quick countdown 2\n#define HOTKEY_ID_QUICK_COUNTDOWN3 105 // Hotkey ID for quick countdown 3\n#define HOTKEY_ID_POMODORO 106 // Hotkey ID for pomodoro timer\n#define HOTKEY_ID_TOGGLE_VISIBILITY 107 // Hotkey ID for hide/show\n#define HOTKEY_ID_EDIT_MODE 108 // Hotkey ID for edit mode\n#define HOTKEY_ID_PAUSE_RESUME 109 // Hotkey ID for pause/resume\n#define HOTKEY_ID_RESTART_TIMER 110 // Hotkey ID for restart timer\n#define HOTKEY_ID_CUSTOM_COUNTDOWN 111 // Hotkey ID for custom countdown\n\n/**\n * @brief Register global hotkeys\n * @param hwnd Window handle\n * \n * Reads and registers global hotkey settings from the configuration file for quickly switching between\n * displaying current time, count up timer, and default countdown.\n * If a hotkey is already registered, it will be unregistered before re-registering.\n * If a hotkey cannot be registered (possibly because it's being used by another program),\n * that hotkey setting will be set to none and the configuration file will be updated.\n * \n * @return BOOL Whether at least one hotkey was successfully registered\n */\nBOOL RegisterGlobalHotkeys(HWND hwnd) {\n // First unregister all previously registered hotkeys\n UnregisterGlobalHotkeys(hwnd);\n \n // Use new function to read hotkey configuration\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n BOOL success = FALSE;\n BOOL configChanged = FALSE;\n \n // Register show current time hotkey\n if (showTimeHotkey != 0) {\n BYTE vk = LOBYTE(showTimeHotkey); // Virtual key code\n BYTE mod = HIBYTE(showTimeHotkey); // Modifier keys\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n showTimeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register count up hotkey\n if (countUpHotkey != 0) {\n BYTE vk = LOBYTE(countUpHotkey);\n BYTE mod = HIBYTE(countUpHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNT_UP, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countUpHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register countdown hotkey\n if (countdownHotkey != 0) {\n BYTE vk = LOBYTE(countdownHotkey);\n BYTE mod = HIBYTE(countdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 1 hotkey\n if (quickCountdown1Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown1Hotkey);\n BYTE mod = HIBYTE(quickCountdown1Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown1Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 2 hotkey\n if (quickCountdown2Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown2Hotkey);\n BYTE mod = HIBYTE(quickCountdown2Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown2Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 3 hotkey\n if (quickCountdown3Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown3Hotkey);\n BYTE mod = HIBYTE(quickCountdown3Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown3Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pomodoro hotkey\n if (pomodoroHotkey != 0) {\n BYTE vk = LOBYTE(pomodoroHotkey);\n BYTE mod = HIBYTE(pomodoroHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_POMODORO, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pomodoroHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register hide/show window hotkey\n if (toggleVisibilityHotkey != 0) {\n BYTE vk = LOBYTE(toggleVisibilityHotkey);\n BYTE mod = HIBYTE(toggleVisibilityHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n toggleVisibilityHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register edit mode hotkey\n if (editModeHotkey != 0) {\n BYTE vk = LOBYTE(editModeHotkey);\n BYTE mod = HIBYTE(editModeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n editModeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pause/resume hotkey\n if (pauseResumeHotkey != 0) {\n BYTE vk = LOBYTE(pauseResumeHotkey);\n BYTE mod = HIBYTE(pauseResumeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pauseResumeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register restart timer hotkey\n if (restartTimerHotkey != 0) {\n BYTE vk = LOBYTE(restartTimerHotkey);\n BYTE mod = HIBYTE(restartTimerHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n restartTimerHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // If any hotkey registration failed, update config file\n if (configChanged) {\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n \n // Check if custom countdown hotkey was cleared, if so, update config\n if (customCountdownHotkey == 0) {\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", \"None\");\n }\n }\n \n // Added after reading hotkey configuration\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Added after registering countdown hotkey\n // Register custom countdown hotkey\n if (customCountdownHotkey != 0) {\n BYTE vk = LOBYTE(customCountdownHotkey);\n BYTE mod = HIBYTE(customCountdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n customCountdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n return success;\n}\n\n/**\n * @brief Unregister global hotkeys\n * @param hwnd Window handle\n * \n * Unregister all previously registered global hotkeys.\n */\nvoid UnregisterGlobalHotkeys(HWND hwnd) {\n // Unregister all previously registered hotkeys\n UnregisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNT_UP);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3);\n UnregisterHotKey(hwnd, HOTKEY_ID_POMODORO);\n UnregisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY);\n UnregisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE);\n UnregisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME);\n UnregisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER);\n UnregisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN);\n}\n\n/**\n * @brief Main window message processing callback function\n * @param hwnd Window handle\n * @param msg Message type\n * @param wp Message parameter (specific meaning depends on message type)\n * @param lp Message parameter (specific meaning depends on message type)\n * @return LRESULT Message processing result\n * \n * Handles all message events for the main window, including:\n * - Window creation/destruction\n * - Mouse events (dragging, wheel scaling)\n * - Timer events\n * - System tray interaction\n * - Drawing events\n * - Menu command processing\n */\nLRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)\n{\n static char time_text[50];\n UINT uID;\n UINT uMouseMsg;\n\n // Check if this is a TaskbarCreated message\n // TaskbarCreated is a system message broadcasted when Windows Explorer restarts\n // At this time all tray icons are destroyed and need to be recreated by applications\n // Handling this message solves the issue of the tray icon disappearing while the program is still running\n if (msg == WM_TASKBARCREATED) {\n // Explorer has restarted, need to recreate the tray icon\n RecreateTaskbarIcon(hwnd, GetModuleHandle(NULL));\n return 0;\n }\n\n switch(msg)\n {\n case WM_CREATE: {\n // Register global hotkeys when window is created\n RegisterGlobalHotkeys(hwnd);\n HandleWindowCreate(hwnd);\n break;\n }\n\n case WM_SETCURSOR: {\n // When in edit mode, always use default arrow cursor\n if (CLOCK_EDIT_MODE && LOWORD(lp) == HTCLIENT) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE; // Indicates we've handled this message\n }\n \n // Also use default arrow cursor when handling tray icon operations\n if (LOWORD(lp) == HTCLIENT || msg == CLOCK_WM_TRAYICON) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE;\n }\n break;\n }\n\n case WM_LBUTTONDOWN: {\n StartDragWindow(hwnd);\n break;\n }\n\n case WM_LBUTTONUP: {\n EndDragWindow(hwnd);\n break;\n }\n\n case WM_MOUSEWHEEL: {\n int delta = GET_WHEEL_DELTA_WPARAM(wp);\n HandleScaleWindow(hwnd, delta);\n break;\n }\n\n case WM_MOUSEMOVE: {\n if (HandleDragWindow(hwnd)) {\n return 0;\n }\n break;\n }\n\n case WM_PAINT: {\n PAINTSTRUCT ps;\n BeginPaint(hwnd, &ps);\n HandleWindowPaint(hwnd, &ps);\n EndPaint(hwnd, &ps);\n break;\n }\n case WM_TIMER: {\n if (HandleTimerEvent(hwnd, wp)) {\n break;\n }\n break;\n }\n case WM_DESTROY: {\n // Unregister global hotkeys when window is destroyed\n UnregisterGlobalHotkeys(hwnd);\n HandleWindowDestroy(hwnd);\n return 0;\n }\n case CLOCK_WM_TRAYICON: {\n HandleTrayIconMessage(hwnd, (UINT)wp, (UINT)lp);\n break;\n }\n case WM_COMMAND: {\n // Handle preset color options (ID: 201 ~ 201+COLOR_OPTIONS_COUNT-1)\n if (LOWORD(wp) >= 201 && LOWORD(wp) < 201 + COLOR_OPTIONS_COUNT) {\n int colorIndex = LOWORD(wp) - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n // Update current color\n strncpy(CLOCK_TEXT_COLOR, COLOR_OPTIONS[colorIndex].hexColor, \n sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n \n // Write to config file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n \n // Redraw window to show new color\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n WORD cmd = LOWORD(wp);\n switch (cmd) {\n case 101: { \n if (CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_LAST_TIME_UPDATE = 0;\n KillTimer(hwnd, 1);\n }\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n // Handle quick time options (102-102+MAX_TIME_OPTIONS)\n case 102: case 103: case 104: case 105: case 106:\n case 107: case 108: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n int index = cmd - 102;\n if (index >= 0 && index < time_options_count) {\n int minutes = time_options[index];\n if (minutes > 0) {\n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = minutes * 60; // Convert to seconds\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n break;\n }\n // Handle exit option\n case 109: {\n ExitProgram(hwnd);\n break;\n }\n case CLOCK_IDC_MODIFY_TIME_OPTIONS: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_SHORTCUT_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_SHORTCUT_DIALOG);\n\n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n // If input is empty or contains only spaces, exit the loop\n if (inputText[0] == '\\0' || isAllSpaces) {\n break;\n }\n\n char* token = strtok(inputText, \" \");\n char options[256] = {0};\n int valid = 1;\n int count = 0;\n \n while (token && count < MAX_TIME_OPTIONS) {\n int num = atoi(token);\n if (num <= 0) {\n valid = 0;\n break;\n }\n \n if (count > 0) {\n strcat(options, \",\");\n }\n strcat(options, token);\n count++;\n token = strtok(NULL, \" \");\n }\n\n if (valid && count > 0) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigTimeOptions(options);\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd,\n GetLocalizedString(\n L\"请输入用空格分隔的数字\\n\"\n L\"例如: 25 10 5\",\n L\"Enter numbers separated by spaces\\n\"\n L\"Example: 25 10 5\"),\n GetLocalizedString(L\"无效输入\", L\"Invalid Input\"), \n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_MODIFY_DEFAULT_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_STARTUP_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_STARTUP_DIALOG);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case 200: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // First, stop all timers to ensure no timer events will be processed\n KillTimer(hwnd, 1);\n \n // Unregister all global hotkeys to ensure they don't remain active after reset\n UnregisterGlobalHotkeys(hwnd);\n \n // Fully reset timer state - critical part\n // Import all timer state variables that need to be reset\n extern int elapsed_time; // from main.c\n extern int countdown_elapsed_time; // from timer.c\n extern int countup_elapsed_time; // from timer.c\n extern BOOL message_shown; // from main.c \n extern BOOL countdown_message_shown;// from timer.c\n extern BOOL countup_message_shown; // from timer.c\n \n // Import high-precision timer initialization function from timer.c\n extern BOOL InitializeHighPrecisionTimer(void);\n extern void ResetTimer(void); // Use a dedicated reset function\n extern void ReadNotificationMessagesConfig(void); // Read notification message configuration\n \n // Reset all timer state variables - order matters!\n CLOCK_TOTAL_TIME = 25 * 60; // 1. First set total time to 25 minutes\n elapsed_time = 0; // 2. Reset elapsed_time in main.c\n countdown_elapsed_time = 0; // 3. Reset countdown_elapsed_time in timer.c\n countup_elapsed_time = 0; // 4. Reset countup_elapsed_time in timer.c\n message_shown = FALSE; // 5. Reset message status\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set timer state to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Call the dedicated timer reset function - this is crucial!\n // This function reinitializes the high-precision timer and resets all timing states\n ResetTimer();\n \n // Reset UI state\n CLOCK_EDIT_MODE = FALSE;\n SetClickThrough(hwnd, TRUE);\n SendMessage(hwnd, WM_SETREDRAW, FALSE, 0);\n \n // Reset file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n \n // Default language initialization\n AppLanguage defaultLanguage;\n LANGID langId = GetUserDefaultUILanguage();\n WORD primaryLangId = PRIMARYLANGID(langId);\n WORD subLangId = SUBLANGID(langId);\n \n switch (primaryLangId) {\n case LANG_CHINESE:\n defaultLanguage = (subLangId == SUBLANG_CHINESE_SIMPLIFIED) ? \n APP_LANG_CHINESE_SIMP : APP_LANG_CHINESE_TRAD;\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n break;\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n break;\n }\n \n if (CURRENT_LANGUAGE != defaultLanguage) {\n CURRENT_LANGUAGE = defaultLanguage;\n }\n \n // Delete and recreate the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure the file is closed and deleted\n FILE* test = fopen(config_path, \"r\");\n if (test) {\n fclose(test);\n remove(config_path);\n }\n \n // Recreate default configuration\n CreateDefaultConfig(config_path);\n \n // Reread the configuration\n ReadConfig();\n \n // Ensure notification messages are reread\n ReadNotificationMessagesConfig();\n \n // Restore default font\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0) { \n LoadFontFromResource(hInstance, fontResources[i].resourceId);\n break;\n }\n }\n \n // Reset window scale\n CLOCK_WINDOW_SCALE = 1.0f;\n CLOCK_FONT_SCALE_FACTOR = 1.0f;\n \n // Recalculate window size\n HDC hdc = GetDC(hwnd);\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE, \n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, FONT_INTERNAL_NAME\n );\n HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);\n \n char time_text[50];\n FormatTime(CLOCK_TOTAL_TIME, time_text);\n SIZE textSize;\n GetTextExtentPoint32(hdc, time_text, strlen(time_text), &textSize);\n \n SelectObject(hdc, hOldFont);\n DeleteObject(hFont);\n ReleaseDC(hwnd, hdc);\n \n // Set default scale based on screen height\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n float defaultScale = (screenHeight * 0.03f) / 20.0f;\n CLOCK_WINDOW_SCALE = defaultScale;\n CLOCK_FONT_SCALE_FACTOR = defaultScale;\n \n // Reset window position\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n textSize.cx * defaultScale, textSize.cy * defaultScale,\n SWP_NOZORDER | SWP_NOACTIVATE\n );\n \n // Ensure window is visible\n ShowWindow(hwnd, SW_SHOW);\n \n // Restart the timer - ensure it's started after all states are reset\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n SendMessage(hwnd, WM_SETREDRAW, TRUE, 0);\n RedrawWindow(hwnd, NULL, NULL, \n RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);\n \n // Reregister default hotkeys\n RegisterGlobalHotkeys(hwnd);\n \n break;\n }\n case CLOCK_IDM_TIMER_PAUSE_RESUME: {\n PauseResumeTimer(hwnd);\n break;\n }\n case CLOCK_IDM_TIMER_RESTART: {\n // Close all notification windows\n CloseAllNotifications();\n RestartTimer(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE: {\n SetLanguage(APP_LANG_CHINESE_SIMP);\n WriteConfigLanguage(APP_LANG_CHINESE_SIMP);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE_TRAD: {\n SetLanguage(APP_LANG_CHINESE_TRAD);\n WriteConfigLanguage(APP_LANG_CHINESE_TRAD);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_ENGLISH: {\n SetLanguage(APP_LANG_ENGLISH);\n WriteConfigLanguage(APP_LANG_ENGLISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_SPANISH: {\n SetLanguage(APP_LANG_SPANISH);\n WriteConfigLanguage(APP_LANG_SPANISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_FRENCH: {\n SetLanguage(APP_LANG_FRENCH);\n WriteConfigLanguage(APP_LANG_FRENCH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_GERMAN: {\n SetLanguage(APP_LANG_GERMAN);\n WriteConfigLanguage(APP_LANG_GERMAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_RUSSIAN: {\n SetLanguage(APP_LANG_RUSSIAN);\n WriteConfigLanguage(APP_LANG_RUSSIAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_PORTUGUESE: {\n SetLanguage(APP_LANG_PORTUGUESE);\n WriteConfigLanguage(APP_LANG_PORTUGUESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_JAPANESE: {\n SetLanguage(APP_LANG_JAPANESE);\n WriteConfigLanguage(APP_LANG_JAPANESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_KOREAN: {\n SetLanguage(APP_LANG_KOREAN);\n WriteConfigLanguage(APP_LANG_KOREAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_ABOUT:\n ShowAboutDialog(hwnd);\n return 0;\n case CLOCK_IDM_TOPMOST: {\n // Toggle the topmost state in configuration\n BOOL newTopmost = !CLOCK_WINDOW_TOPMOST;\n \n // If in edit mode, just update the stored state but don't apply it yet\n if (CLOCK_EDIT_MODE) {\n // Update the configuration and saved state only\n PREVIOUS_TOPMOST_STATE = newTopmost;\n CLOCK_WINDOW_TOPMOST = newTopmost;\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n } else {\n // Not in edit mode, apply it immediately\n SetWindowTopmost(hwnd, newTopmost);\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n }\n break;\n }\n case CLOCK_IDM_COUNTDOWN_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = FALSE; // Switch to countdown mode\n }\n \n // Reset the countdown timer\n extern void ResetTimer(void);\n ResetTimer();\n \n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDC_EDIT_MODE: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n } else {\n StartEditMode(hwnd);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n case CLOCK_IDC_CUSTOMIZE_LEFT: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n char hex_color[10];\n snprintf(hex_color, sizeof(hex_color), \"#%02X%02X%02X\", \n GetRValue(color), GetGValue(color), GetBValue(color));\n WriteConfigColor(hex_color);\n ReadConfig();\n }\n break;\n }\n case CLOCK_IDC_FONT_RECMONO: {\n WriteConfigFont(\"RecMonoCasual Nerd Font Mono Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DEPARTURE: {\n WriteConfigFont(\"DepartureMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_TERMINESS: {\n WriteConfigFont(\"Terminess Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PINYON_SCRIPT: {\n WriteConfigFont(\"Pinyon Script Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ARBUTUS: {\n WriteConfigFont(\"Arbutus Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_BERKSHIRE: {\n WriteConfigFont(\"Berkshire Swash Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CAVEAT: {\n WriteConfigFont(\"Caveat Brush Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CREEPSTER: {\n WriteConfigFont(\"Creepster Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DOTO: { \n WriteConfigFont(\"Doto ExtraBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FOLDIT: {\n WriteConfigFont(\"Foldit SemiBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FREDERICKA: {\n WriteConfigFont(\"Fredericka the Great Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FRIJOLE: {\n WriteConfigFont(\"Frijole Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_GWENDOLYN: {\n WriteConfigFont(\"Gwendolyn Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_HANDJET: {\n WriteConfigFont(\"Handjet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_INKNUT: {\n WriteConfigFont(\"Inknut Antiqua Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARD: {\n WriteConfigFont(\"Jacquard 12 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARDA: {\n WriteConfigFont(\"Jacquarda Bastarda 9 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KAVOON: {\n WriteConfigFont(\"Kavoon Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE: {\n WriteConfigFont(\"Kumar One Outline Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE: {\n WriteConfigFont(\"Kumar One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LAKKI_REDDY: {\n WriteConfigFont(\"Lakki Reddy Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LICORICE: {\n WriteConfigFont(\"Licorice Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MA_SHAN_ZHENG: {\n WriteConfigFont(\"Ma Shan Zheng Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MOIRAI_ONE: {\n WriteConfigFont(\"Moirai One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MYSTERY_QUEST: {\n WriteConfigFont(\"Mystery Quest Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_NOTO_NASTALIQ: {\n WriteConfigFont(\"Noto Nastaliq Urdu Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIEDRA: {\n WriteConfigFont(\"Piedra Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIXELIFY: {\n WriteConfigFont(\"Pixelify Sans Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PRESS_START: {\n WriteConfigFont(\"Press Start 2P Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BUBBLES: {\n WriteConfigFont(\"Rubik Bubbles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BURNED: {\n WriteConfigFont(\"Rubik Burned Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_GLITCH: {\n WriteConfigFont(\"Rubik Glitch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_MARKER_HATCH: {\n WriteConfigFont(\"Rubik Marker Hatch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_PUDDLES: {\n WriteConfigFont(\"Rubik Puddles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_VINYL: {\n WriteConfigFont(\"Rubik Vinyl Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_WET_PAINT: {\n WriteConfigFont(\"Rubik Wet Paint Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUGE_BOOGIE: {\n WriteConfigFont(\"Ruge Boogie Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SEVILLANA: {\n WriteConfigFont(\"Sevillana Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SILKSCREEN: {\n WriteConfigFont(\"Silkscreen Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_STICK: {\n WriteConfigFont(\"Stick Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_UNDERDOG: {\n WriteConfigFont(\"Underdog Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_WALLPOET: {\n WriteConfigFont(\"Wallpoet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_YESTERYEAR: {\n WriteConfigFont(\"Yesteryear Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ZCOOL_KUAILE: {\n WriteConfigFont(\"ZCOOL KuaiLe Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PROFONT: {\n WriteConfigFont(\"ProFont IIx Nerd Font Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DADDYTIME: {\n WriteConfigFont(\"DaddyTimeMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDM_SHOW_CURRENT_TIME: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_SHOW_CURRENT_TIME = !CLOCK_SHOW_CURRENT_TIME;\n if (CLOCK_SHOW_CURRENT_TIME) {\n ShowWindow(hwnd, SW_SHOW); \n \n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1); \n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0; // Ensure total time is reset\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n SetTimer(hwnd, 1, 100, NULL); // Reduce interval to 100ms for higher refresh rate\n } else {\n KillTimer(hwnd, 1); \n // When canceling showing current time, fully reset state instead of restoring previous state\n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0;\n message_shown = 0; // Reset message shown state\n // Set timer with longer interval because second-level updates are no longer needed\n SetTimer(hwnd, 1, 1000, NULL); \n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_24HOUR_FORMAT: { \n CLOCK_USE_24HOUR = !CLOCK_USE_24HOUR;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_SHOW_SECONDS: { \n CLOCK_SHOW_SECONDS = !CLOCK_SHOW_SECONDS;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_RECENT_FILE_1:\n case CLOCK_IDM_RECENT_FILE_2:\n case CLOCK_IDM_RECENT_FILE_3:\n case CLOCK_IDM_RECENT_FILE_4:\n case CLOCK_IDM_RECENT_FILE_5: {\n int index = cmd - CLOCK_IDM_RECENT_FILE_1;\n if (index < CLOCK_RECENT_FILES_COUNT) {\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[index].path, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(CLOCK_RECENT_FILES[index].path);\n \n // Step 2: Update the recent files list (move this file to the top)\n SaveRecentFile(CLOCK_RECENT_FILES[index].path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n \n // Clear invalid file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n \n // Remove this file from the recent files list\n for (int i = index; i < CLOCK_RECENT_FILES_COUNT - 1; i++) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i + 1];\n }\n CLOCK_RECENT_FILES_COUNT--;\n \n // Update recent files list in the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n }\n }\n break;\n }\n case CLOCK_IDM_BROWSE_FILE: {\n wchar_t szFile[MAX_PATH] = {0};\n \n OPENFILENAMEW ofn = {0};\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile) / sizeof(wchar_t);\n ofn.lpstrFilter = L\"所有文件\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n \n if (GetOpenFileNameW(&ofn)) {\n // Convert wide character path to UTF-8 to save in the configuration file\n char utf8Path[MAX_PATH * 3] = {0}; // Larger buffer to accommodate UTF-8 encoding\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n \n if (GetFileAttributesW(szFile) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case CLOCK_IDC_TIMEOUT_BROWSE: {\n OPENFILENAMEW ofn;\n wchar_t szFile[MAX_PATH] = L\"\";\n \n ZeroMemory(&ofn, sizeof(ofn));\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile);\n ofn.lpstrFilter = L\"All Files (*.*)\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n\n if (GetOpenFileNameW(&ofn)) {\n char utf8Path[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, \n utf8Path, \n sizeof(utf8Path), \n NULL, NULL);\n \n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n }\n break;\n }\n case CLOCK_IDM_COUNT_UP: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_COUNT_UP = !CLOCK_COUNT_UP;\n if (CLOCK_COUNT_UP) {\n ShowWindow(hwnd, SW_SHOW);\n \n elapsed_time = 0;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (!CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = TRUE;\n \n // Ensure the timer starts from 0 every time it switches to count-up mode\n countup_elapsed_time = 0;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n } else {\n // Already in count-up mode, so toggle pause/run state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n // Reset the count-up counter\n extern void ResetTimer(void);\n ResetTimer();\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDC_SET_COUNTDOWN_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n \n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n \n CLOCK_DEFAULT_START_TIME = total_seconds;\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_START_SHOW_TIME: {\n WriteConfigStartupMode(\"SHOW_TIME\");\n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_CHECKED);\n break;\n }\n case CLOCK_IDC_START_COUNT_UP: {\n WriteConfigStartupMode(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDC_START_NO_DISPLAY: {\n WriteConfigStartupMode(\"NO_DISPLAY\");\n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n case CLOCK_IDC_AUTO_START: {\n BOOL isEnabled = IsAutoStartEnabled();\n if (isEnabled) {\n if (RemoveShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_UNCHECKED);\n }\n } else {\n if (CreateShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_CHECKED);\n }\n }\n break;\n }\n case CLOCK_IDC_COLOR_VALUE: {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_COLOR_DIALOG), \n hwnd, \n (DLGPROC)ColorDlgProc);\n break;\n }\n case CLOCK_IDC_COLOR_PANEL: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case CLOCK_IDM_POMODORO_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n if (!IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_SHOW);\n }\n \n // Reset timer state\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // Set work time\n CLOCK_TOTAL_TIME = POMODORO_WORK_TIME;\n \n // Initialize Pomodoro phase\n extern void InitializePomodoro(void);\n InitializePomodoro();\n \n // Save original timeout action\n TimeoutActionType originalAction = CLOCK_TIMEOUT_ACTION;\n \n // Force set to show message\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n \n // Start the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Reset message state\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_POMODORO_WORK:\n case CLOCK_IDM_POMODORO_BREAK:\n case CLOCK_IDM_POMODORO_LBREAK:\n // Keep original menu item ID handling\n {\n int selectedIndex = 0;\n if (LOWORD(wp) == CLOCK_IDM_POMODORO_WORK) {\n selectedIndex = 0;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_BREAK) {\n selectedIndex = 1;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_LBREAK) {\n selectedIndex = 2;\n }\n \n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n break;\n\n // Also handle new dynamic ID range\n case 600: case 601: case 602: case 603: case 604:\n case 605: case 606: case 607: case 608: case 609:\n // Handle Pomodoro time setting options (dynamic ID range)\n {\n // Calculate the selected option index\n int selectedIndex = LOWORD(wp) - CLOCK_IDM_POMODORO_TIME_BASE;\n \n if (selectedIndex >= 0 && selectedIndex < POMODORO_TIMES_COUNT) {\n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n }\n break;\n case CLOCK_IDM_POMODORO_LOOP_COUNT:\n ShowPomodoroLoopDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Call ResetTimer to reset the timer state\n extern void ResetTimer(void);\n ResetTimer();\n \n // If currently in Pomodoro mode, reset related states\n if (CLOCK_TOTAL_TIME == POMODORO_WORK_TIME || \n CLOCK_TOTAL_TIME == POMODORO_SHORT_BREAK || \n CLOCK_TOTAL_TIME == POMODORO_LONG_BREAK) {\n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDM_TIMEOUT_SHOW_TIME: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n WriteConfigTimeoutAction(\"SHOW_TIME\");\n break;\n }\n case CLOCK_IDM_TIMEOUT_COUNT_UP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n WriteConfigTimeoutAction(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDM_SHOW_MESSAGE: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n break;\n }\n case CLOCK_IDM_LOCK_SCREEN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n WriteConfigTimeoutAction(\"LOCK\");\n break;\n }\n case CLOCK_IDM_SHUTDOWN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHUTDOWN;\n WriteConfigTimeoutAction(\"SHUTDOWN\");\n break;\n }\n case CLOCK_IDM_RESTART: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RESTART;\n WriteConfigTimeoutAction(\"RESTART\");\n break;\n }\n case CLOCK_IDM_SLEEP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n WriteConfigTimeoutAction(\"SLEEP\");\n break;\n }\n case CLOCK_IDM_RUN_COMMAND: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n WriteConfigTimeoutAction(\"RUN_COMMAND\");\n break;\n }\n case CLOCK_IDM_HTTP_REQUEST: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n WriteConfigTimeoutAction(\"HTTP_REQUEST\");\n break;\n }\n case CLOCK_IDM_CHECK_UPDATE: {\n // Call async update check function - non-silent mode\n CheckForUpdateAsync(hwnd, FALSE);\n break;\n }\n case CLOCK_IDM_OPEN_WEBSITE:\n // Don't set action type immediately, wait for dialog result\n ShowWebsiteDialog(hwnd);\n break;\n \n case CLOCK_IDM_CURRENT_WEBSITE:\n ShowWebsiteDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_COMBINATION:\n ShowPomodoroComboDialog(hwnd);\n break;\n case CLOCK_IDM_NOTIFICATION_CONTENT: {\n ShowNotificationMessagesDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_DISPLAY: {\n ShowNotificationDisplayDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_SETTINGS: {\n ShowNotificationSettingsDialog(hwnd);\n break;\n }\n case CLOCK_IDM_HOTKEY_SETTINGS: {\n ShowHotkeySettingsDialog(hwnd);\n // Register/reregister global hotkeys\n RegisterGlobalHotkeys(hwnd);\n break;\n }\n case CLOCK_IDM_HELP: {\n OpenUserGuide();\n break;\n }\n case CLOCK_IDM_SUPPORT: {\n OpenSupportPage();\n break;\n }\n case CLOCK_IDM_FEEDBACK: {\n OpenFeedbackPage();\n break;\n }\n }\n break;\n\nrefresh_window:\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case WM_WINDOWPOSCHANGED: {\n if (CLOCK_EDIT_MODE) {\n SaveWindowSettings(hwnd);\n }\n break;\n }\n case WM_RBUTTONUP: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_MEASUREITEM:\n {\n LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT)lp;\n if (lpmis->CtlType == ODT_MENU) {\n lpmis->itemHeight = 25;\n lpmis->itemWidth = 100;\n return TRUE;\n }\n return FALSE;\n }\n case WM_DRAWITEM:\n {\n LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT)lp;\n if (lpdis->CtlType == ODT_MENU) {\n int colorIndex = lpdis->itemID - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n const char* hexColor = COLOR_OPTIONS[colorIndex].hexColor;\n int r, g, b;\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n \n HBRUSH hBrush = CreateSolidBrush(RGB(r, g, b));\n HPEN hPen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n \n HGDIOBJ oldBrush = SelectObject(lpdis->hDC, hBrush);\n HGDIOBJ oldPen = SelectObject(lpdis->hDC, hPen);\n \n Rectangle(lpdis->hDC, lpdis->rcItem.left, lpdis->rcItem.top,\n lpdis->rcItem.right, lpdis->rcItem.bottom);\n \n SelectObject(lpdis->hDC, oldPen);\n SelectObject(lpdis->hDC, oldBrush);\n DeleteObject(hPen);\n DeleteObject(hBrush);\n \n if (lpdis->itemState & ODS_SELECTED) {\n DrawFocusRect(lpdis->hDC, &lpdis->rcItem);\n }\n \n return TRUE;\n }\n }\n return FALSE;\n }\n case WM_MENUSELECT: {\n UINT menuItem = LOWORD(wp);\n UINT flags = HIWORD(wp);\n HMENU hMenu = (HMENU)lp;\n\n if (!(flags & MF_POPUP) && hMenu != NULL) {\n int colorIndex = menuItem - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n strncpy(PREVIEW_COLOR, COLOR_OPTIONS[colorIndex].hexColor, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (fontResources[i].menuId == menuItem) {\n strncpy(PREVIEW_FONT_NAME, fontResources[i].fontName, 99);\n PREVIEW_FONT_NAME[99] = '\\0';\n \n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, 99);\n PREVIEW_INTERNAL_NAME[99] = '\\0';\n char* dot = strrchr(PREVIEW_INTERNAL_NAME, '.');\n if (dot) *dot = '\\0';\n \n LoadFontByName((HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), \n fontResources[i].fontName);\n \n IS_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n \n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n } else if (flags & MF_POPUP) {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n break;\n }\n case WM_EXITMENULOOP: {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case WM_RBUTTONDOWN: {\n if (GetKeyState(VK_CONTROL) & 0x8000) {\n // Toggle edit mode\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Entering edit mode\n SetClickThrough(hwnd, FALSE);\n } else {\n // Exiting edit mode\n SetClickThrough(hwnd, TRUE);\n SaveWindowSettings(hwnd); // Save settings when exiting edit mode\n WriteConfigColor(CLOCK_TEXT_COLOR); // Save the current color to config\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n break;\n }\n case WM_CLOSE: {\n SaveWindowSettings(hwnd); // Save window settings before closing\n DestroyWindow(hwnd); // Close the window\n break;\n }\n case WM_LBUTTONDBLCLK: {\n if (!CLOCK_EDIT_MODE) {\n // Enter edit mode\n StartEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_HOTKEY: {\n // WM_HOTKEY message's lp contains key information\n if (wp == HOTKEY_ID_SHOW_TIME) {\n ToggleShowTimeMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNT_UP) {\n StartCountUp(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNTDOWN) {\n StartDefaultCountDown(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_CUSTOM_COUNTDOWN) {\n // Check if the input dialog already exists\n if (g_hwndInputDialog != NULL && IsWindow(g_hwndInputDialog)) {\n // The dialog already exists, close it\n SendMessage(g_hwndInputDialog, WM_CLOSE, 0, 0);\n return 0;\n }\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Show input dialog to set countdown\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Clear input text\n memset(inputText, 0, sizeof(inputText));\n \n // Show input dialog\n INT_PTR result = DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), \n hwnd, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n \n // If the dialog has input and was confirmed\n if (inputText[0] != '\\0') {\n // Check if input is valid\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Set countdown state\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n \n // Switch to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Stop and restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN1) {\n // Start quick countdown 1\n StartQuickCountdown1(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN2) {\n // Start quick countdown 2\n StartQuickCountdown2(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN3) {\n // Start quick countdown 3\n StartQuickCountdown3(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_POMODORO) {\n // Start Pomodoro timer\n StartPomodoroTimer(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_TOGGLE_VISIBILITY) {\n // Hide/show window\n if (IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_HIDE);\n } else {\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n }\n return 0;\n } else if (wp == HOTKEY_ID_EDIT_MODE) {\n // Enter edit mode\n ToggleEditMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_PAUSE_RESUME) {\n // Pause/resume timer\n TogglePauseResume(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_RESTART_TIMER) {\n // Close all notification windows\n CloseAllNotifications();\n // Restart current timer\n RestartCurrentTimer(hwnd);\n return 0;\n }\n break;\n }\n // Handle reregistration message after hotkey settings change\n case WM_APP+1: {\n // Only reregister hotkeys, do not open dialog\n RegisterGlobalHotkeys(hwnd);\n return 0;\n }\n default:\n return DefWindowProc(hwnd, msg, wp, lp);\n }\n return 0;\n}\n\n// External variable declarations\nextern int CLOCK_DEFAULT_START_TIME;\nextern int countdown_elapsed_time;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern int CLOCK_TOTAL_TIME;\n\n// Remove menu items\nvoid RemoveMenuItems(HMENU hMenu, int count);\n\n// Add menu item\nvoid AddMenuItem(HMENU hMenu, UINT id, const char* text, BOOL isEnabled);\n\n// Modify menu item text\nvoid ModifyMenuItemText(HMENU hMenu, UINT id, const char* text);\n\n/**\n * @brief Toggle show current time mode\n * @param hwnd Window handle\n */\nvoid ToggleShowTimeMode(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // If not currently in show current time mode, then enable it\n // If already in show current time mode, do nothing (don't turn it off)\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Switch to show current time mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n \n // Reset the timer to ensure the update frequency is correct\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 100, NULL); // Use 100ms update frequency to keep the time display smooth\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n }\n // Already in show current time mode, do nothing\n}\n\n/**\n * @brief Start count up timer\n * @param hwnd Window handle\n */\nvoid StartCountUp(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Declare external variables\n extern int countup_elapsed_time;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Reset count up counter\n countup_elapsed_time = 0;\n \n // Set to count up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start default countdown\n * @param hwnd Window handle\n */\nvoid StartDefaultCountDown(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Set mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n if (CLOCK_DEFAULT_START_TIME > 0) {\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n } else {\n // If no default countdown is set, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, 101, 0);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start Pomodoro timer\n * @param hwnd Window handle\n */\nvoid StartPomodoroTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // If it was previously in show current time mode, stop the old timer\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n }\n \n // Use the Pomodoro menu item command to start the Pomodoro timer\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDM_POMODORO_START, 0);\n}\n\n/**\n * @brief Toggle edit mode\n * @param hwnd Window handle\n */\nvoid ToggleEditMode(HWND hwnd) {\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Record the current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If not currently topmost, set it to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure the window is visible and in the foreground\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n } else {\n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, TRUE);\n \n // If it was not topmost before, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Save window settings and color settings\n SaveWindowSettings(hwnd);\n WriteConfigColor(CLOCK_TEXT_COLOR);\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Pause/resume timer\n * @param hwnd Window handle\n */\nvoid TogglePauseResume(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart the current timer\n * @param hwnd Window handle\n */\nvoid RestartCurrentTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Variables imported from main.c\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Reset message shown state to allow notification and sound to be played again when timer ends\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n if (CLOCK_COUNT_UP) {\n // Reset count up timer\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else {\n // Reset countdown timer\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n }\n CLOCK_IS_PAUSED = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Start quick countdown 1\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown1(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there is at least one preset time option\n if (time_options_count > 0) {\n CLOCK_TOTAL_TIME = time_options[0] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are no preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 2\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown2(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least two preset time options\n if (time_options_count > 1) {\n CLOCK_TOTAL_TIME = time_options[1] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 3\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown3(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least three preset time options\n if (time_options_count > 2) {\n CLOCK_TOTAL_TIME = time_options[2] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n"], ["/Catime/src/timer_events.c", "/**\n * @file timer_events.c\n * @brief Implementation of timer event handling\n * \n * This file implements the functionality related to the application's timer event handling,\n * including countdown and count-up mode event processing.\n */\n\n#include \n#include \n#include \"../include/timer_events.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \"../include/window.h\"\n#include \"audio_player.h\" // Include header reference\n\n// Maximum capacity of Pomodoro time list\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Index of the currently executing Pomodoro time\nint current_pomodoro_time_index = 0;\n\n// Define current_pomodoro_phase variable, which is declared as extern in pomodoro.h\nPOMODORO_PHASE current_pomodoro_phase = POMODORO_PHASE_IDLE;\n\n// Number of completed Pomodoro cycles\nint complete_pomodoro_cycles = 0;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\n\n// Variable declarations imported from main.c, for timeout actions\nextern int elapsed_time;\nextern BOOL message_shown;\n\n// Custom message text imported from config.c\nextern char CLOCK_TIMEOUT_MESSAGE_TEXT[100];\nextern char POMODORO_TIMEOUT_MESSAGE_TEXT[100]; // New Pomodoro-specific prompt\nextern char POMODORO_CYCLE_COMPLETE_TEXT[100];\n\n// Define ClockState type\ntypedef enum {\n CLOCK_STATE_IDLE,\n CLOCK_STATE_COUNTDOWN,\n CLOCK_STATE_COUNTUP,\n CLOCK_STATE_POMODORO\n} ClockState;\n\n// Define PomodoroState type\ntypedef struct {\n BOOL isLastCycle;\n int cycleIndex;\n int totalCycles;\n} PomodoroState;\n\nextern HWND g_hwnd; // Main window handle\nextern ClockState g_clockState;\nextern PomodoroState g_pomodoroState;\n\n// Timer behavior function declarations\nextern void ShowTrayNotification(HWND hwnd, const char* message);\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void OpenFileByPath(const char* filePath);\nextern void OpenWebsite(const char* url);\nextern void SleepComputer(void);\nextern void ShutdownComputer(void);\nextern void RestartComputer(void);\nextern void SetTimeDisplay(void);\nextern void ShowCountUp(HWND hwnd);\n\n// Add external function declaration to the beginning of the file or before the function\nextern void StopNotificationSound(void);\n\n/**\n * @brief Convert UTF-8 encoded char* string to wchar_t* string\n * @param utf8String Input UTF-8 string\n * @return Converted wchar_t* string, memory needs to be freed with free() after use. Returns NULL if conversion fails.\n */\nstatic wchar_t* Utf8ToWideChar(const char* utf8String) {\n if (!utf8String || utf8String[0] == '\\0') {\n return NULL; // Return NULL to handle empty strings or NULL pointers\n }\n int size_needed = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, NULL, 0);\n if (size_needed == 0) {\n // Conversion failed\n return NULL;\n }\n wchar_t* wideString = (wchar_t*)malloc(size_needed * sizeof(wchar_t));\n if (!wideString) {\n // Memory allocation failed\n return NULL;\n }\n int result = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, wideString, size_needed);\n if (result == 0) {\n // Conversion failed\n free(wideString);\n return NULL;\n }\n return wideString;\n}\n\n/**\n * @brief Convert wide character string to UTF-8 encoded regular string and display notification\n * @param hwnd Window handle\n * @param message Wide character string message to display (read from configuration and converted)\n */\nstatic void ShowLocalizedNotification(HWND hwnd, const wchar_t* message) {\n // Don't display if message is empty\n if (!message || message[0] == L'\\0') {\n return;\n }\n\n // Calculate required buffer size\n int size_needed = WideCharToMultiByte(CP_UTF8, 0, message, -1, NULL, 0, NULL, NULL);\n if (size_needed == 0) return; // Conversion failed\n\n // Allocate memory\n char* utf8Msg = (char*)malloc(size_needed);\n if (utf8Msg) {\n // Convert to UTF-8\n int result = WideCharToMultiByte(CP_UTF8, 0, message, -1, utf8Msg, size_needed, NULL, NULL);\n\n if (result > 0) {\n // Display notification using the new ShowNotification function\n ShowNotification(hwnd, utf8Msg);\n \n // If timeout action is MESSAGE, play notification audio\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE) {\n // Read the latest audio settings\n ReadNotificationSoundConfig();\n \n // Play notification audio\n PlayNotificationSound(hwnd);\n }\n }\n\n // Free memory\n free(utf8Msg);\n }\n}\n\n/**\n * @brief Set Pomodoro to work phase\n * \n * Reset all timer counts and set Pomodoro to work phase\n */\nvoid InitializePomodoro(void) {\n // Use existing enum value POMODORO_PHASE_WORK instead of POMODORO_PHASE_RUNNING\n current_pomodoro_phase = POMODORO_PHASE_WORK;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Set initial countdown to the first time value\n if (POMODORO_TIMES_COUNT > 0) {\n CLOCK_TOTAL_TIME = POMODORO_TIMES[0];\n } else {\n // If no time is configured, use default 25 minutes\n CLOCK_TOTAL_TIME = 1500;\n }\n \n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n}\n\n/**\n * @brief Handle timer messages\n * @param hwnd Window handle\n * @param wp Message parameter\n * @return BOOL Whether the message was handled\n */\nBOOL HandleTimerEvent(HWND hwnd, WPARAM wp) {\n if (wp == 1) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // In current time display mode, reset the last displayed second on each timer trigger to ensure the latest time is displayed\n extern int last_displayed_second;\n last_displayed_second = -1; // Force reset of seconds cache to ensure the latest system time is displayed each time\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n return TRUE;\n }\n\n // If timer is paused, don't update time\n if (CLOCK_IS_PAUSED) {\n return TRUE;\n }\n\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time++;\n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n if (countdown_elapsed_time < CLOCK_TOTAL_TIME) {\n countdown_elapsed_time++;\n if (countdown_elapsed_time >= CLOCK_TOTAL_TIME && !countdown_message_shown) {\n countdown_message_shown = TRUE;\n\n // Re-read message text from config file before displaying notification\n ReadNotificationMessagesConfig();\n // Force re-read notification type config to ensure latest settings are used\n ReadNotificationTypeConfig();\n \n // Variable declaration before branches to ensure availability in all branches\n wchar_t* timeoutMsgW = NULL;\n\n // Check if in Pomodoro mode - must meet all three conditions:\n // 1. Current Pomodoro phase is not IDLE \n // 2. Pomodoro time configuration is valid\n // 3. Current countdown total time matches the time at current index in the Pomodoro time list\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE && \n POMODORO_TIMES_COUNT > 0 && \n current_pomodoro_time_index < POMODORO_TIMES_COUNT &&\n CLOCK_TOTAL_TIME == POMODORO_TIMES[current_pomodoro_time_index]) {\n \n // Use Pomodoro-specific prompt message\n timeoutMsgW = Utf8ToWideChar(POMODORO_TIMEOUT_MESSAGE_TEXT);\n \n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"番茄钟时间到!\"); // Fallback\n }\n \n // Move to next time period\n current_pomodoro_time_index++;\n \n // Check if a complete cycle has been finished\n if (current_pomodoro_time_index >= POMODORO_TIMES_COUNT) {\n // Reset index back to the first time\n current_pomodoro_time_index = 0;\n \n // Increase completed cycle count\n complete_pomodoro_cycles++;\n \n // Check if all configured loop counts have been completed\n if (complete_pomodoro_cycles >= POMODORO_LOOP_COUNT) {\n // All loop counts completed, end Pomodoro\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_TOTAL_TIME = 0;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n \n // Try to read and convert completion message from config\n wchar_t* cycleCompleteMsgW = Utf8ToWideChar(POMODORO_CYCLE_COMPLETE_TEXT);\n // Display completion prompt (using config or default value)\n if (cycleCompleteMsgW) {\n ShowLocalizedNotification(hwnd, cycleCompleteMsgW);\n free(cycleCompleteMsgW); // Free completion message memory\n } else {\n ShowLocalizedNotification(hwnd, L\"所有番茄钟循环完成!\"); // Fallback\n }\n \n // Switch to idle state - add the following code\n CLOCK_COUNT_UP = FALSE; // Ensure not in count-up mode\n CLOCK_SHOW_CURRENT_TIME = FALSE; // Ensure not in current time display mode\n message_shown = TRUE; // Mark message as shown\n \n // Force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n KillTimer(hwnd, 1);\n if (timeoutMsgW) free(timeoutMsgW); // Free timeout message memory\n return TRUE;\n }\n }\n \n // Set countdown for next time period\n CLOCK_TOTAL_TIME = POMODORO_TIMES[current_pomodoro_time_index];\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n \n // If it's the first time period in a new round, display cycle prompt\n if (current_pomodoro_time_index == 0 && complete_pomodoro_cycles > 0) {\n wchar_t cycleMsg[100];\n // GetLocalizedString needs to be reconsidered, or hardcode English/Chinese\n // Temporarily keep the original approach, but ideally should be configurable\n const wchar_t* formatStr = GetLocalizedString(L\"开始第 %d 轮番茄钟\", L\"Starting Pomodoro cycle %d\");\n swprintf(cycleMsg, 100, formatStr, complete_pomodoro_cycles + 1);\n ShowLocalizedNotification(hwnd, cycleMsg); // Call the modified function\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // Not in Pomodoro mode, or switched to normal countdown mode\n // Use normal countdown prompt message\n timeoutMsgW = Utf8ToWideChar(CLOCK_TIMEOUT_MESSAGE_TEXT);\n \n // Only display notification message if timeout action is not open file, lock, shutdown, or restart\n if (CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_OPEN_FILE && \n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_LOCK &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SHUTDOWN &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_RESTART &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SLEEP) {\n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"时间到!\"); // Fallback\n }\n }\n \n // If current mode is not Pomodoro (manually switched to normal countdown), ensure not to return to Pomodoro cycle\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n (current_pomodoro_time_index >= POMODORO_TIMES_COUNT ||\n CLOCK_TOTAL_TIME != POMODORO_TIMES[current_pomodoro_time_index])) {\n // If switched to normal countdown, reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n // If sleep option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute sleep command\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n return TRUE;\n }\n \n // If shutdown option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute shutdown command\n system(\"shutdown /s /t 0\");\n return TRUE;\n }\n \n // If restart option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute restart command\n system(\"shutdown /r /t 0\");\n return TRUE;\n }\n \n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n // Notification already displayed, no additional operation needed\n break;\n case TIMEOUT_ACTION_LOCK:\n LockWorkStation();\n break;\n case TIMEOUT_ACTION_OPEN_FILE: {\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0) {\n wchar_t wPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_FILE_PATH, -1, wPath, MAX_PATH);\n \n HINSTANCE result = ShellExecuteW(NULL, L\"open\", wPath, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)result <= 32) {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"无法打开文件\", L\"Failed to open file\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case TIMEOUT_ACTION_SHOW_TIME:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to count-up mode and reset\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countup_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set Pomodoro state to idle\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n wchar_t wideUrl[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_WEBSITE_URL, -1, wideUrl, MAX_PATH);\n ShellExecuteW(NULL, L\"open\", wideUrl, NULL, NULL, SW_NORMAL);\n }\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n }\n\n // Free converted wide string memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return TRUE;\n }\n return FALSE;\n}\n\nvoid OnTimerTimeout(HWND hwnd) {\n // Execute different behaviors based on timeout action\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE: {\n char utf8Msg[256] = {0};\n \n // Select different prompt messages based on current state\n if (g_clockState == CLOCK_STATE_POMODORO) {\n // Check if Pomodoro has completed all cycles\n if (g_pomodoroState.isLastCycle && g_pomodoroState.cycleIndex >= g_pomodoroState.totalCycles - 1) {\n strncpy(utf8Msg, POMODORO_CYCLE_COMPLETE_TEXT, sizeof(utf8Msg) - 1);\n } else {\n strncpy(utf8Msg, POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n } else {\n strncpy(utf8Msg, CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n \n utf8Msg[sizeof(utf8Msg) - 1] = '\\0'; // Ensure string ends with null character\n \n // Display custom prompt message\n ShowNotification(hwnd, utf8Msg);\n \n // Read latest audio settings and play alert sound\n ReadNotificationSoundConfig();\n PlayNotificationSound(hwnd);\n \n break;\n }\n case TIMEOUT_ACTION_RUN_COMMAND: {\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n case TIMEOUT_ACTION_HTTP_REQUEST: {\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n\n }\n}\n\n// Add missing global variable definitions (if not defined elsewhere)\n#ifndef STUB_VARIABLES_DEFINED\n#define STUB_VARIABLES_DEFINED\n// Main window handle\nHWND g_hwnd = NULL;\n// Current clock state\nClockState g_clockState = CLOCK_STATE_IDLE;\n// Pomodoro state\nPomodoroState g_pomodoroState = {FALSE, 0, 1};\n#endif\n\n// Add stub function definitions if needed\n#ifndef STUB_FUNCTIONS_DEFINED\n#define STUB_FUNCTIONS_DEFINED\n__attribute__((weak)) void SleepComputer(void) {\n // This is a weak symbol definition, if there's an actual implementation elsewhere, that implementation will be used\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n}\n\n__attribute__((weak)) void ShutdownComputer(void) {\n system(\"shutdown /s /t 0\");\n}\n\n__attribute__((weak)) void RestartComputer(void) {\n system(\"shutdown /r /t 0\");\n}\n\n__attribute__((weak)) void SetTimeDisplay(void) {\n // Stub implementation for setting time display\n}\n\n__attribute__((weak)) void ShowCountUp(HWND hwnd) {\n // Stub implementation for showing count-up\n}\n#endif\n"], ["/Catime/src/audio_player.c", "/**\n * @file audio_player.c\n * @brief Audio playback functionality handler\n */\n\n#include \n#include \n#include \n#include \"../libs/miniaudio/miniaudio.h\"\n\n#include \"config.h\"\n\nextern char NOTIFICATION_SOUND_FILE[MAX_PATH];\nextern int NOTIFICATION_SOUND_VOLUME;\n\ntypedef void (*AudioPlaybackCompleteCallback)(HWND hwnd);\n\nstatic ma_engine g_audioEngine;\nstatic ma_sound g_sound;\nstatic ma_bool32 g_engineInitialized = MA_FALSE;\nstatic ma_bool32 g_soundInitialized = MA_FALSE;\n\nstatic AudioPlaybackCompleteCallback g_audioCompleteCallback = NULL;\nstatic HWND g_audioCallbackHwnd = NULL;\nstatic UINT_PTR g_audioTimerId = 0;\n\nstatic ma_bool32 g_isPlaying = MA_FALSE;\nstatic ma_bool32 g_isPaused = MA_FALSE;\n\nstatic void CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime);\n\n/**\n * @brief Initialize audio engine\n */\nstatic BOOL InitializeAudioEngine() {\n if (g_engineInitialized) {\n return TRUE;\n }\n\n ma_result result = ma_engine_init(NULL, &g_audioEngine);\n if (result != MA_SUCCESS) {\n return FALSE;\n }\n\n g_engineInitialized = MA_TRUE;\n return TRUE;\n}\n\n/**\n * @brief Clean up audio engine resources\n */\nstatic void UninitializeAudioEngine() {\n if (g_engineInitialized) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n ma_engine_uninit(&g_audioEngine);\n g_engineInitialized = MA_FALSE;\n }\n}\n\n/**\n * @brief Check if a file exists\n */\nstatic BOOL FileExists(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2);\n\n DWORD dwAttrib = GetFileAttributesW(wFilePath);\n return (dwAttrib != INVALID_FILE_ATTRIBUTES &&\n !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));\n}\n\n/**\n * @brief Show error message dialog\n */\nstatic void ShowErrorMessage(HWND hwnd, const wchar_t* errorMsg) {\n MessageBoxW(hwnd, errorMsg, L\"Audio Playback Error\", MB_ICONERROR | MB_OK);\n}\n\n/**\n * @brief Timer callback to check if audio playback is complete\n */\nstatic void CALLBACK CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n if (g_engineInitialized && g_soundInitialized) {\n if (!ma_sound_is_playing(&g_sound) && !g_isPaused) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n } else {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n}\n\n/**\n * @brief System beep playback completion callback timer function\n */\nstatic void CALLBACK SystemBeepDoneCallback(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n}\n\n/**\n * @brief Set audio playback volume\n * @param volume Volume percentage (0-100)\n */\nvoid SetAudioVolume(int volume) {\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n\n if (g_engineInitialized) {\n float volFloat = (float)volume / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volFloat);\n\n if (g_soundInitialized && g_isPlaying) {\n ma_sound_set_volume(&g_sound, volFloat);\n }\n }\n}\n\n/**\n * @brief Play audio file using miniaudio\n */\nstatic BOOL PlayAudioWithMiniaudio(HWND hwnd, const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (!g_engineInitialized) {\n if (!InitializeAudioEngine()) {\n return FALSE;\n }\n }\n\n float volume = (float)NOTIFICATION_SOUND_VOLUME / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volume);\n\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n if (MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (UTF-8->Unicode): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n wchar_t shortPath[MAX_PATH] = {0};\n DWORD shortPathLen = GetShortPathNameW(wFilePath, shortPath, MAX_PATH);\n if (shortPathLen == 0 || shortPathLen >= MAX_PATH) {\n DWORD error = GetLastError();\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Failed to get short path: %ls\\nError code: %lu\", wFilePath, error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n char asciiPath[MAX_PATH] = {0};\n if (WideCharToMultiByte(CP_ACP, 0, shortPath, -1, asciiPath, MAX_PATH, NULL, NULL) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (Short Path->ASCII): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n return FALSE;\n }\n\n ma_result result = ma_sound_init_from_file(&g_audioEngine, asciiPath, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n char utf8Path[MAX_PATH * 4] = {0};\n WideCharToMultiByte(CP_UTF8, 0, wFilePath, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n\n result = ma_sound_init_from_file(&g_audioEngine, utf8Path, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Unable to load audio file: %ls\\nError code: %d\", wFilePath, result);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n }\n\n g_soundInitialized = MA_TRUE;\n\n if (ma_sound_start(&g_sound) != MA_SUCCESS) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n ShowErrorMessage(hwnd, L\"Cannot start audio playback\");\n return FALSE;\n }\n\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1001, 500, (TIMERPROC)CheckAudioPlaybackComplete);\n\n return TRUE;\n}\n\n/**\n * @brief Validate if file path is legal\n */\nstatic BOOL IsValidFilePath(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (strchr(filePath, '=') != NULL) return FALSE;\n\n if (strlen(filePath) >= MAX_PATH) return FALSE;\n\n return TRUE;\n}\n\n/**\n * @brief Clean up audio resources\n */\nvoid CleanupAudioResources(void) {\n PlaySound(NULL, NULL, SND_PURGE);\n\n if (g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n if (g_audioTimerId != 0 && g_audioCallbackHwnd != NULL) {\n KillTimer(g_audioCallbackHwnd, g_audioTimerId);\n g_audioTimerId = 0;\n }\n\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n}\n\n/**\n * @brief Set audio playback completion callback function\n */\nvoid SetAudioPlaybackCompleteCallback(HWND hwnd, AudioPlaybackCompleteCallback callback) {\n g_audioCallbackHwnd = hwnd;\n g_audioCompleteCallback = callback;\n}\n\n/**\n * @brief Play notification audio\n */\nBOOL PlayNotificationSound(HWND hwnd) {\n CleanupAudioResources();\n\n g_audioCallbackHwnd = hwnd;\n\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (!IsValidFilePath(NOTIFICATION_SOUND_FILE)) {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Invalid audio file path:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (FileExists(NOTIFICATION_SOUND_FILE)) {\n if (PlayAudioWithMiniaudio(hwnd, NOTIFICATION_SOUND_FILE)) {\n return TRUE;\n }\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n } else {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Cannot find the configured audio file:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Pause currently playing notification audio\n */\nBOOL PauseNotificationSound(void) {\n if (g_isPlaying && !g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n g_isPaused = MA_TRUE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Resume previously paused notification audio\n */\nBOOL ResumeNotificationSound(void) {\n if (g_isPlaying && g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_start(&g_sound);\n g_isPaused = MA_FALSE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Stop playing notification audio\n */\nvoid StopNotificationSound(void) {\n CleanupAudioResources();\n}"], ["/Catime/src/dialog_language.c", "/**\n * @file dialog_language.c\n * @brief Dialog multi-language support module implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \"../include/dialog_language.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\ntypedef struct {\n int dialogID;\n wchar_t* titleKey;\n} DialogTitleEntry;\n\ntypedef struct {\n int dialogID;\n int controlID;\n wchar_t* textKey;\n wchar_t* fallbackText;\n} SpecialControlEntry;\n\ntypedef struct {\n HWND hwndDlg;\n int dialogID;\n} EnumChildWindowsData;\n\nstatic DialogTitleEntry g_dialogTitles[] = {\n {IDD_ABOUT_DIALOG, L\"About\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, L\"Notification Settings\"},\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, L\"Set Pomodoro Loop Count\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, L\"Set Pomodoro Time Combination\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, L\"Set Pomodoro Time\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, L\"Countdown Presets\"},\n {CLOCK_IDD_WEBSITE_DIALOG, L\"Open Website\"},\n {CLOCK_IDD_DIALOG1, L\"Set Countdown\"},\n {IDD_NO_UPDATE_DIALOG, L\"Update Check\"},\n {IDD_UPDATE_DIALOG, L\"Update Available\"}\n};\n\nstatic SpecialControlEntry g_specialControls[] = {\n {IDD_ABOUT_DIALOG, IDC_ABOUT_TITLE, L\"关于\", L\"About\"},\n {IDD_ABOUT_DIALOG, IDC_VERSION_TEXT, L\"Version: %hs\", L\"Version: %hs\"},\n {IDD_ABOUT_DIALOG, IDC_BUILD_DATE, L\"构建日期:\", L\"Build Date:\"},\n {IDD_ABOUT_DIALOG, IDC_COPYRIGHT, L\"COPYRIGHT_TEXT\", L\"COPYRIGHT_TEXT\"},\n {IDD_ABOUT_DIALOG, IDC_CREDITS, L\"鸣谢\", L\"Credits\"},\n\n {IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT, L\"NoUpdateRequired\", L\"You are already using the latest version!\"},\n\n {IDD_UPDATE_DIALOG, IDC_UPDATE_TEXT, L\"CurrentVersion: %s\\nNewVersion: %s\", L\"Current Version: %s\\nNew Version: %s\"},\n {IDD_UPDATE_DIALOG, IDC_UPDATE_EXIT_TEXT, L\"The application will exit now\", L\"The application will exit now\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_CONTENT_GROUP, L\"Notification Content\", L\"Notification Content\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL1, L\"Countdown timeout message:\", L\"Countdown timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL2, L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL3, L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_DISPLAY_GROUP, L\"Notification Display\", L\"Notification Display\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TIME_LABEL, L\"Notification display time:\", L\"Notification display time:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_LABEL, L\"Maximum notification opacity (1-100%):\", L\"Maximum notification opacity (1-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_DISABLE_NOTIFICATION_CHECK, L\"Disable notifications\", L\"Disable notifications\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_METHOD_GROUP, L\"Notification Method\", L\"Notification Method\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_CATIME, L\"Catime notification window\", L\"Catime notification window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_OS, L\"System notification\", L\"System notification\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, L\"System modal window\", L\"System modal window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_SOUND_LABEL, L\"Sound (supports .mp3/.wav/.flac):\", L\"Sound (supports .mp3/.wav/.flac):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_LABEL, L\"Volume (0-100%):\", L\"Volume (0-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_TEXT, L\"100%\", L\"100%\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_TEXT, L\"100%\", L\"100%\"},\n\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_STATIC,\n L\"25=25 minutes\\\\n25h=25 hours\\\\n25s=25 seconds\\\\n25 30=25 minutes 30 seconds\\\\n25 30m=25 hours 30 minutes\\\\n1 30 20=1 hour 30 minutes 20 seconds\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\"},\n\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter pomodoro time sequence, separated by spaces:\\\\n\\\\n25m = 25 minutes\\\\n30s = 30 seconds\\\\n1h30m = 1 hour 30 minutes\\\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\",\n L\"Enter pomodoro time sequence, separated by spaces:\\n\\n25m = 25 minutes\\n30s = 30 seconds\\n1h30m = 1 hour 30 minutes\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\"},\n\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter the website URL to open when the countdown ends:\\\\nExample: https://github.com/vladelaina/Catime\",\n L\"Enter the website URL to open when the countdown ends:\\nExample: https://github.com/vladelaina/Catime\"},\n\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_STATIC,\n L\"CountdownPresetDialogStaticText\",\n L\"Enter numbers (minutes), separated by spaces\\n\\n25 10 5\\n\\nThis will create options for 25 minutes, 10 minutes, and 5 minutes\"},\n\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_STATIC,\n L\"CountdownDialogStaticText\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\\n17 20t=Countdown to 17:20\\n9 9 9t=Countdown to 09:09:09\"}\n};\n\nstatic SpecialControlEntry g_specialButtons[] = {\n {IDD_UPDATE_DIALOG, IDYES, L\"Yes\", L\"Yes\"},\n {IDD_UPDATE_DIALOG, IDNO, L\"No\", L\"No\"},\n {IDD_UPDATE_DIALOG, IDOK, L\"OK\", L\"OK\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_TEST_SOUND_BUTTON, L\"Test\", L\"Test\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_OPEN_SOUND_DIR_BUTTON, L\"Audio folder\", L\"Audio folder\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDOK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDCANCEL, L\"Cancel\", L\"Cancel\"},\n\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"}\n};\n\n#define DIALOG_TITLES_COUNT (sizeof(g_dialogTitles) / sizeof(g_dialogTitles[0]))\n#define SPECIAL_CONTROLS_COUNT (sizeof(g_specialControls) / sizeof(g_specialControls[0]))\n#define SPECIAL_BUTTONS_COUNT (sizeof(g_specialButtons) / sizeof(g_specialButtons[0]))\n\n/**\n * @brief Find localized text for special controls\n */\nstatic const wchar_t* FindSpecialControlText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_CONTROLS_COUNT; i++) {\n if (g_specialControls[i].dialogID == dialogID &&\n g_specialControls[i].controlID == controlID) {\n const wchar_t* localizedText = GetLocalizedString(NULL, g_specialControls[i].textKey);\n if (localizedText) {\n return localizedText;\n } else {\n return g_specialControls[i].fallbackText;\n }\n }\n }\n return NULL;\n}\n\n/**\n * @brief Find localized text for special buttons\n */\nstatic const wchar_t* FindSpecialButtonText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_BUTTONS_COUNT; i++) {\n if (g_specialButtons[i].dialogID == dialogID &&\n g_specialButtons[i].controlID == controlID) {\n return GetLocalizedString(NULL, g_specialButtons[i].textKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get localized text for dialog title\n */\nstatic const wchar_t* GetDialogTitleText(int dialogID) {\n for (int i = 0; i < DIALOG_TITLES_COUNT; i++) {\n if (g_dialogTitles[i].dialogID == dialogID) {\n return GetLocalizedString(NULL, g_dialogTitles[i].titleKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get original text of a control for translation lookup\n */\nstatic BOOL GetControlOriginalText(HWND hwndCtl, wchar_t* buffer, int bufferSize) {\n wchar_t className[256];\n GetClassNameW(hwndCtl, className, 256);\n\n if (wcscmp(className, L\"Button\") == 0 ||\n wcscmp(className, L\"Static\") == 0 ||\n wcscmp(className, L\"ComboBox\") == 0 ||\n wcscmp(className, L\"Edit\") == 0) {\n return GetWindowTextW(hwndCtl, buffer, bufferSize) > 0;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Process special control text settings, such as line breaks\n */\nstatic BOOL ProcessSpecialControlText(HWND hwndCtl, const wchar_t* localizedText, int dialogID, int controlID) {\n if ((dialogID == CLOCK_IDD_POMODORO_COMBO_DIALOG ||\n dialogID == CLOCK_IDD_POMODORO_TIME_DIALOG ||\n dialogID == CLOCK_IDD_WEBSITE_DIALOG ||\n dialogID == CLOCK_IDD_SHORTCUT_DIALOG ||\n dialogID == CLOCK_IDD_DIALOG1) &&\n controlID == CLOCK_IDC_STATIC) {\n wchar_t processedText[1024];\n const wchar_t* src = localizedText;\n wchar_t* dst = processedText;\n\n while (*src) {\n if (src[0] == L'\\\\' && src[1] == L'n') {\n *dst++ = L'\\n';\n src += 2;\n }\n else if (src[0] == L'\\n') {\n *dst++ = L'\\n';\n src++;\n }\n else {\n *dst++ = *src++;\n }\n }\n *dst = L'\\0';\n\n SetWindowTextW(hwndCtl, processedText);\n return TRUE;\n }\n\n if (controlID == IDC_VERSION_TEXT && dialogID == IDD_ABOUT_DIALOG) {\n wchar_t versionText[256];\n const wchar_t* localizedVersionFormat = GetLocalizedString(NULL, L\"Version: %hs\");\n if (localizedVersionFormat) {\n StringCbPrintfW(versionText, sizeof(versionText), localizedVersionFormat, CATIME_VERSION);\n } else {\n StringCbPrintfW(versionText, sizeof(versionText), localizedText, CATIME_VERSION);\n }\n SetWindowTextW(hwndCtl, versionText);\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Dialog child window enumeration callback function\n */\nstatic BOOL CALLBACK EnumChildProc(HWND hwndCtl, LPARAM lParam) {\n EnumChildWindowsData* data = (EnumChildWindowsData*)lParam;\n HWND hwndDlg = data->hwndDlg;\n int dialogID = data->dialogID;\n\n int controlID = GetDlgCtrlID(hwndCtl);\n if (controlID == 0) {\n return TRUE;\n }\n\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n if (ProcessSpecialControlText(hwndCtl, specialText, dialogID, controlID)) {\n return TRUE;\n }\n SetWindowTextW(hwndCtl, specialText);\n return TRUE;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n SetWindowTextW(hwndCtl, buttonText);\n return TRUE;\n }\n\n wchar_t originalText[512] = {0};\n if (GetControlOriginalText(hwndCtl, originalText, 512) && originalText[0] != L'\\0') {\n const wchar_t* localizedText = GetLocalizedString(NULL, originalText);\n if (localizedText && wcscmp(localizedText, originalText) != 0) {\n SetWindowTextW(hwndCtl, localizedText);\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Initialize dialog multi-language support\n */\nBOOL InitDialogLanguageSupport(void) {\n return TRUE;\n}\n\n/**\n * @brief Apply multi-language support to dialog\n */\nBOOL ApplyDialogLanguage(HWND hwndDlg, int dialogID) {\n if (!hwndDlg) return FALSE;\n\n const wchar_t* titleText = GetDialogTitleText(dialogID);\n if (titleText) {\n SetWindowTextW(hwndDlg, titleText);\n }\n\n EnumChildWindowsData data = {\n .hwndDlg = hwndDlg,\n .dialogID = dialogID\n };\n\n EnumChildWindows(hwndDlg, EnumChildProc, (LPARAM)&data);\n\n return TRUE;\n}\n\n/**\n * @brief Get localized text for dialog element\n */\nconst wchar_t* GetDialogLocalizedString(int dialogID, int controlID) {\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n return specialText;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n return buttonText;\n }\n\n if (controlID == -1) {\n return GetDialogTitleText(dialogID);\n }\n\n return NULL;\n}"], ["/Catime/src/color.c", "/**\n * @file color.c\n * @brief Color processing functionality implementation\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/color.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n\nPredefinedColor* COLOR_OPTIONS = NULL;\nsize_t COLOR_OPTIONS_COUNT = 0;\nchar PREVIEW_COLOR[10] = \"\";\nBOOL IS_COLOR_PREVIEWING = FALSE;\nchar CLOCK_TEXT_COLOR[10] = \"#FFFFFF\";\n\nvoid GetConfigPath(char* path, size_t size);\nvoid CreateDefaultConfig(const char* config_path);\nvoid ReadConfig(void);\nvoid WriteConfig(const char* config_path);\nvoid replaceBlackColor(const char* color, char* output, size_t output_size);\n\nstatic const CSSColor CSS_COLORS[] = {\n {\"white\", \"#FFFFFF\"},\n {\"black\", \"#000000\"},\n {\"red\", \"#FF0000\"},\n {\"lime\", \"#00FF00\"},\n {\"blue\", \"#0000FF\"},\n {\"yellow\", \"#FFFF00\"},\n {\"cyan\", \"#00FFFF\"},\n {\"magenta\", \"#FF00FF\"},\n {\"silver\", \"#C0C0C0\"},\n {\"gray\", \"#808080\"},\n {\"maroon\", \"#800000\"},\n {\"olive\", \"#808000\"},\n {\"green\", \"#008000\"},\n {\"purple\", \"#800080\"},\n {\"teal\", \"#008080\"},\n {\"navy\", \"#000080\"},\n {\"orange\", \"#FFA500\"},\n {\"pink\", \"#FFC0CB\"},\n {\"brown\", \"#A52A2A\"},\n {\"violet\", \"#EE82EE\"},\n {\"indigo\", \"#4B0082\"},\n {\"gold\", \"#FFD700\"},\n {\"coral\", \"#FF7F50\"},\n {\"salmon\", \"#FA8072\"},\n {\"khaki\", \"#F0E68C\"},\n {\"plum\", \"#DDA0DD\"},\n {\"azure\", \"#F0FFFF\"},\n {\"ivory\", \"#FFFFF0\"},\n {\"wheat\", \"#F5DEB3\"},\n {\"snow\", \"#FFFAFA\"}\n};\n\n#define CSS_COLORS_COUNT (sizeof(CSS_COLORS) / sizeof(CSS_COLORS[0]))\n\nstatic const char* DEFAULT_COLOR_OPTIONS[] = {\n \"#FFFFFF\",\n \"#F9DB91\",\n \"#F4CAE0\",\n \"#FFB6C1\",\n \"#A8E7DF\",\n \"#A3CFB3\",\n \"#92CBFC\",\n \"#BDA5E7\",\n \"#9370DB\",\n \"#8C92CF\",\n \"#72A9A5\",\n \"#EB99A7\",\n \"#EB96BD\",\n \"#FFAE8B\",\n \"#FF7F50\",\n \"#CA6174\"\n};\n\n#define DEFAULT_COLOR_OPTIONS_COUNT (sizeof(DEFAULT_COLOR_OPTIONS) / sizeof(DEFAULT_COLOR_OPTIONS[0]))\n\nWNDPROC g_OldEditProc;\n\n#include \n\nCOLORREF ShowColorDialog(HWND hwnd) {\n CHOOSECOLOR cc = {0};\n static COLORREF acrCustClr[16] = {0};\n static DWORD rgbCurrent;\n\n int r, g, b;\n if (CLOCK_TEXT_COLOR[0] == '#') {\n sscanf(CLOCK_TEXT_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n } else {\n sscanf(CLOCK_TEXT_COLOR, \"%d,%d,%d\", &r, &g, &b);\n }\n rgbCurrent = RGB(r, g, b);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT && i < 16; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n if (hexColor[0] == '#') {\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n acrCustClr[i] = RGB(r, g, b);\n }\n }\n\n cc.lStructSize = sizeof(CHOOSECOLOR);\n cc.hwndOwner = hwnd;\n cc.lpCustColors = acrCustClr;\n cc.rgbResult = rgbCurrent;\n cc.Flags = CC_FULLOPEN | CC_RGBINIT | CC_ENABLEHOOK;\n cc.lpfnHook = ColorDialogHookProc;\n\n if (ChooseColor(&cc)) {\n COLORREF finalColor;\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n int r, g, b;\n sscanf(PREVIEW_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n finalColor = RGB(r, g, b);\n } else {\n finalColor = cc.rgbResult;\n }\n\n char tempColor[10];\n snprintf(tempColor, sizeof(tempColor), \"#%02X%02X%02X\",\n GetRValue(finalColor),\n GetGValue(finalColor),\n GetBValue(finalColor));\n\n char finalColorStr[10];\n replaceBlackColor(tempColor, finalColorStr, sizeof(finalColorStr));\n\n strncpy(CLOCK_TEXT_COLOR, finalColorStr, sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n\n IS_COLOR_PREVIEWING = FALSE;\n\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return finalColor;\n }\n\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return (COLORREF)-1;\n}\n\nUINT_PTR CALLBACK ColorDialogHookProc(HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HWND hwndParent;\n static CHOOSECOLOR* pcc;\n static BOOL isColorLocked = FALSE;\n static DWORD rgbCurrent;\n static COLORREF lastCustomColors[16] = {0};\n\n switch (msg) {\n case WM_INITDIALOG:\n pcc = (CHOOSECOLOR*)lParam;\n hwndParent = pcc->hwndOwner;\n rgbCurrent = pcc->rgbResult;\n isColorLocked = FALSE;\n \n for (int i = 0; i < 16; i++) {\n lastCustomColors[i] = pcc->lpCustColors[i];\n }\n return TRUE;\n\n case WM_LBUTTONDOWN:\n case WM_RBUTTONDOWN:\n isColorLocked = !isColorLocked;\n \n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n \n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n \n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n \n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n\n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_MOUSEMOVE:\n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n\n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n\n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n\n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n \n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n \n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_COMMAND:\n if (HIWORD(wParam) == BN_CLICKED) {\n switch (LOWORD(wParam)) {\n case IDOK: {\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n } else {\n snprintf(PREVIEW_COLOR, sizeof(PREVIEW_COLOR), \"#%02X%02X%02X\",\n GetRValue(pcc->rgbResult),\n GetGValue(pcc->rgbResult),\n GetBValue(pcc->rgbResult));\n }\n break;\n }\n \n case IDCANCEL:\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n break;\n }\n }\n break;\n\n case WM_CTLCOLORBTN:\n case WM_CTLCOLOREDIT:\n case WM_CTLCOLORSTATIC:\n if (pcc) {\n BOOL colorsChanged = FALSE;\n for (int i = 0; i < 16; i++) {\n if (lastCustomColors[i] != pcc->lpCustColors[i]) {\n colorsChanged = TRUE;\n lastCustomColors[i] = pcc->lpCustColors[i];\n \n char colorStr[20];\n snprintf(colorStr, sizeof(colorStr), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n \n }\n }\n \n if (colorsChanged) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n ClearColorOptions();\n \n for (int i = 0; i < 16; i++) {\n if (pcc->lpCustColors[i] != 0) {\n char hexColor[10];\n snprintf(hexColor, sizeof(hexColor), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n AddColorOption(hexColor);\n }\n }\n \n WriteConfig(config_path);\n }\n }\n break;\n }\n return 0;\n}\n\nvoid InitializeDefaultLanguage(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n ClearColorOptions();\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n CreateDefaultConfig(config_path);\n file = fopen(config_path, \"r\");\n }\n\n if (file) {\n char line[1024];\n BOOL found_colors = FALSE;\n\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"COLOR_OPTIONS=\", 13) == 0) {\n ClearColorOptions();\n\n char* colors = line + 13;\n while (*colors == '=' || *colors == ' ') {\n colors++;\n }\n\n char* newline = strchr(colors, '\\n');\n if (newline) *newline = '\\0';\n\n char* token = strtok(colors, \",\");\n while (token) {\n while (*token == ' ') token++;\n char* end = token + strlen(token) - 1;\n while (end > token && *end == ' ') {\n *end = '\\0';\n end--;\n }\n\n if (*token) {\n if (token[0] != '#') {\n char colorWithHash[10];\n snprintf(colorWithHash, sizeof(colorWithHash), \"#%s\", token);\n AddColorOption(colorWithHash);\n } else {\n AddColorOption(token);\n }\n }\n token = strtok(NULL, \",\");\n }\n found_colors = TRUE;\n break;\n }\n }\n fclose(file);\n\n if (!found_colors || COLOR_OPTIONS_COUNT == 0) {\n for (size_t i = 0; i < DEFAULT_COLOR_OPTIONS_COUNT; i++) {\n AddColorOption(DEFAULT_COLOR_OPTIONS[i]);\n }\n }\n }\n}\n\n/**\n * @brief Add color option\n */\nvoid AddColorOption(const char* hexColor) {\n if (!hexColor || !*hexColor) {\n return;\n }\n\n char normalizedColor[10];\n const char* hex = (hexColor[0] == '#') ? hexColor + 1 : hexColor;\n\n size_t len = strlen(hex);\n if (len != 6) {\n return;\n }\n\n for (int i = 0; i < 6; i++) {\n if (!isxdigit((unsigned char)hex[i])) {\n return;\n }\n }\n\n unsigned int color;\n if (sscanf(hex, \"%x\", &color) != 1) {\n return;\n }\n\n snprintf(normalizedColor, sizeof(normalizedColor), \"#%06X\", color);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (strcasecmp(normalizedColor, COLOR_OPTIONS[i].hexColor) == 0) {\n return;\n }\n }\n\n PredefinedColor* newArray = realloc(COLOR_OPTIONS,\n (COLOR_OPTIONS_COUNT + 1) * sizeof(PredefinedColor));\n if (newArray) {\n COLOR_OPTIONS = newArray;\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = _strdup(normalizedColor);\n COLOR_OPTIONS_COUNT++;\n }\n}\n\n/**\n * @brief Clear all color options\n */\nvoid ClearColorOptions(void) {\n if (COLOR_OPTIONS) {\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n free((void*)COLOR_OPTIONS[i].hexColor);\n }\n free(COLOR_OPTIONS);\n COLOR_OPTIONS = NULL;\n COLOR_OPTIONS_COUNT = 0;\n }\n}\n\n/**\n * @brief Write color to configuration file\n */\nvoid WriteConfigColor(const char* color_input) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"CLOCK_TEXT_COLOR=\", 17) == 0) {\n strcat(new_config, \"CLOCK_TEXT_COLOR=\");\n strcat(new_config, color_input);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n ReadConfig();\n}\n\n/**\n * @brief Normalize color format\n */\nvoid normalizeColor(const char* input, char* output, size_t output_size) {\n while (isspace(*input)) input++;\n\n char color[32];\n strncpy(color, input, sizeof(color)-1);\n color[sizeof(color)-1] = '\\0';\n for (char* p = color; *p; p++) {\n *p = tolower(*p);\n }\n\n for (size_t i = 0; i < CSS_COLORS_COUNT; i++) {\n if (strcmp(color, CSS_COLORS[i].name) == 0) {\n strncpy(output, CSS_COLORS[i].hex, output_size);\n return;\n }\n }\n\n char cleaned[32] = {0};\n int j = 0;\n for (int i = 0; color[i]; i++) {\n if (!isspace(color[i]) && color[i] != ',' && color[i] != '(' && color[i] != ')') {\n cleaned[j++] = color[i];\n }\n }\n cleaned[j] = '\\0';\n\n if (cleaned[0] == '#') {\n memmove(cleaned, cleaned + 1, strlen(cleaned));\n }\n\n if (strlen(cleaned) == 3) {\n snprintf(output, output_size, \"#%c%c%c%c%c%c\",\n cleaned[0], cleaned[0], cleaned[1], cleaned[1], cleaned[2], cleaned[2]);\n return;\n }\n\n if (strlen(cleaned) == 6 && strspn(cleaned, \"0123456789abcdefABCDEF\") == 6) {\n snprintf(output, output_size, \"#%s\", cleaned);\n return;\n }\n\n int r = -1, g = -1, b = -1;\n char* rgb_str = color;\n\n if (strncmp(rgb_str, \"rgb\", 3) == 0) {\n rgb_str += 3;\n while (*rgb_str && (*rgb_str == '(' || isspace(*rgb_str))) rgb_str++;\n }\n\n if (sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d %d %d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d|%d|%d\", &r, &g, &b) == 3) {\n\n if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) {\n snprintf(output, output_size, \"#%02X%02X%02X\", r, g, b);\n return;\n }\n }\n\n strncpy(output, input, output_size);\n}\n\n/**\n * @brief Check if color is valid\n */\nBOOL isValidColor(const char* input) {\n if (!input || !*input) return FALSE;\n\n char normalized[32];\n normalizeColor(input, normalized, sizeof(normalized));\n\n if (normalized[0] != '#' || strlen(normalized) != 7) {\n return FALSE;\n }\n\n for (int i = 1; i < 7; i++) {\n if (!isxdigit((unsigned char)normalized[i])) {\n return FALSE;\n }\n }\n\n int r, g, b;\n if (sscanf(normalized + 1, \"%02x%02x%02x\", &r, &g, &b) == 3) {\n return (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255);\n }\n\n return FALSE;\n}\n\n/**\n * @brief Color edit box subclass procedure\n */\nLRESULT CALLBACK ColorEditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_KEYDOWN:\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n case WM_COMMAND:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n return 0;\n }\n }\n break;\n\n case WM_CHAR:\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n }\n\n return result;\n\n case WM_PASTE:\n case WM_CUT: {\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n }\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n\n return result;\n }\n }\n\n return CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Color settings dialog procedure\n */\nINT_PTR CALLBACK ColorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit) {\n g_OldEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC,\n (LONG_PTR)ColorEditSubclassProc);\n\n if (CLOCK_TEXT_COLOR[0] != '\\0') {\n SetWindowTextA(hwndEdit, CLOCK_TEXT_COLOR);\n }\n }\n return TRUE;\n }\n\n case WM_COMMAND: {\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n char color[32];\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, color, sizeof(color));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; color[i]; i++) {\n if (!isspace((unsigned char)color[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (color[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n\n if (isValidColor(color)) {\n char normalized_color[10];\n normalizeColor(color, normalized_color, sizeof(normalized_color));\n strncpy(CLOCK_TEXT_COLOR, normalized_color, sizeof(CLOCK_TEXT_COLOR)-1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR)-1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n }\n return FALSE;\n}\n\n/**\n * @brief Replace pure black color with near-black\n */\nvoid replaceBlackColor(const char* color, char* output, size_t output_size) {\n if (color && (strcasecmp(color, \"#000000\") == 0)) {\n strncpy(output, \"#000001\", output_size);\n output[output_size - 1] = '\\0';\n } else {\n strncpy(output, color, output_size);\n output[output_size - 1] = '\\0';\n }\n}"], ["/Catime/src/window.c", "/**\n * @file window.c\n * @brief Window management functionality implementation\n * \n * This file implements the functionality related to application window management,\n * including window creation, position adjustment, transparency, click-through, and drag functionality.\n */\n\n#include \"../include/window.h\"\n#include \"../include/timer.h\"\n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n\n// Forward declaration of WindowProcedure (defined in main.c)\nextern LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\n\n// Add declaration for SetProcessDPIAware function\n#ifndef _INC_WINUSER\n// If not included by windows.h, add SetProcessDPIAware function declaration\nWINUSERAPI BOOL WINAPI SetProcessDPIAware(VOID);\n#endif\n\n// Window size and position variables\nint CLOCK_BASE_WINDOW_WIDTH = 200;\nint CLOCK_BASE_WINDOW_HEIGHT = 100;\nfloat CLOCK_WINDOW_SCALE = 1.0f;\nint CLOCK_WINDOW_POS_X = 100;\nint CLOCK_WINDOW_POS_Y = 100;\n\n// Window state variables\nBOOL CLOCK_EDIT_MODE = FALSE;\nBOOL CLOCK_IS_DRAGGING = FALSE;\nPOINT CLOCK_LAST_MOUSE_POS = {0, 0};\nBOOL CLOCK_WINDOW_TOPMOST = TRUE; // Default topmost\n\n// Text area variables\nRECT CLOCK_TEXT_RECT = {0, 0, 0, 0};\nBOOL CLOCK_TEXT_RECT_VALID = FALSE;\n\n// DWM function pointer type definition\ntypedef HRESULT (WINAPI *pfnDwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);\nstatic pfnDwmEnableBlurBehindWindow _DwmEnableBlurBehindWindow = NULL;\n\n// Window composition attribute type definition\ntypedef enum _WINDOWCOMPOSITIONATTRIB {\n WCA_UNDEFINED = 0,\n WCA_NCRENDERING_ENABLED = 1,\n WCA_NCRENDERING_POLICY = 2,\n WCA_TRANSITIONS_FORCEDISABLED = 3,\n WCA_ALLOW_NCPAINT = 4,\n WCA_CAPTION_BUTTON_BOUNDS = 5,\n WCA_NONCLIENT_RTL_LAYOUT = 6,\n WCA_FORCE_ICONIC_REPRESENTATION = 7,\n WCA_EXTENDED_FRAME_BOUNDS = 8,\n WCA_HAS_ICONIC_BITMAP = 9,\n WCA_THEME_ATTRIBUTES = 10,\n WCA_NCRENDERING_EXILED = 11,\n WCA_NCADORNMENTINFO = 12,\n WCA_EXCLUDED_FROM_LIVEPREVIEW = 13,\n WCA_VIDEO_OVERLAY_ACTIVE = 14,\n WCA_FORCE_ACTIVEWINDOW_APPEARANCE = 15,\n WCA_DISALLOW_PEEK = 16,\n WCA_CLOAK = 17,\n WCA_CLOAKED = 18,\n WCA_ACCENT_POLICY = 19,\n WCA_FREEZE_REPRESENTATION = 20,\n WCA_EVER_UNCLOAKED = 21,\n WCA_VISUAL_OWNER = 22,\n WCA_HOLOGRAPHIC = 23,\n WCA_EXCLUDED_FROM_DDA = 24,\n WCA_PASSIVEUPDATEMODE = 25,\n WCA_USEDARKMODECOLORS = 26,\n WCA_LAST = 27\n} WINDOWCOMPOSITIONATTRIB;\n\ntypedef struct _WINDOWCOMPOSITIONATTRIBDATA {\n WINDOWCOMPOSITIONATTRIB Attrib;\n PVOID pvData;\n SIZE_T cbData;\n} WINDOWCOMPOSITIONATTRIBDATA;\n\nWINUSERAPI BOOL WINAPI SetWindowCompositionAttribute(HWND hwnd, WINDOWCOMPOSITIONATTRIBDATA* pData);\n\ntypedef enum _ACCENT_STATE {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5\n} ACCENT_STATE;\n\ntypedef struct _ACCENT_POLICY {\n ACCENT_STATE AccentState;\n DWORD AccentFlags;\n DWORD GradientColor;\n DWORD AnimationId;\n} ACCENT_POLICY;\n\nvoid SetClickThrough(HWND hwnd, BOOL enable) {\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n // Clear previously set related styles\n exStyle &= ~WS_EX_TRANSPARENT;\n \n if (enable) {\n // Set click-through\n exStyle |= WS_EX_TRANSPARENT;\n \n // If the window is a layered window, ensure it properly handles mouse input\n if (exStyle & WS_EX_LAYERED) {\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n }\n } else {\n // Ensure window receives all mouse input\n if (exStyle & WS_EX_LAYERED) {\n // Maintain transparency but allow receiving mouse input\n SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);\n }\n }\n \n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Update window to apply new style\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n}\n\nBOOL InitDWMFunctions() {\n HMODULE hDwmapi = LoadLibraryA(\"dwmapi.dll\");\n if (hDwmapi) {\n _DwmEnableBlurBehindWindow = (pfnDwmEnableBlurBehindWindow)GetProcAddress(hDwmapi, \"DwmEnableBlurBehindWindow\");\n return _DwmEnableBlurBehindWindow != NULL;\n }\n return FALSE;\n}\n\nvoid SetBlurBehind(HWND hwnd, BOOL enable) {\n if (enable) {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_ENABLE_BLURBEHIND;\n policy.AccentFlags = 0;\n policy.GradientColor = (180 << 24) | 0x00202020; // Changed to dark gray background with 180 transparency\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = TRUE;\n bb.hRgnBlur = NULL;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n } else {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_DISABLED;\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = FALSE;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n }\n}\n\nvoid AdjustWindowPosition(HWND hwnd, BOOL forceOnScreen) {\n if (!forceOnScreen) {\n // Do not force window to be on screen, return directly\n return;\n }\n \n // Original code to ensure window is on screen\n RECT rect;\n GetWindowRect(hwnd, &rect);\n \n int screenWidth = GetSystemMetrics(SM_CXSCREEN);\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n \n int width = rect.right - rect.left;\n int height = rect.bottom - rect.top;\n \n int x = rect.left;\n int y = rect.top;\n \n // Ensure window right edge doesn't exceed screen\n if (x + width > screenWidth) {\n x = screenWidth - width;\n }\n \n // Ensure window bottom edge doesn't exceed screen\n if (y + height > screenHeight) {\n y = screenHeight - height;\n }\n \n // Ensure window left edge doesn't exceed screen\n if (x < 0) {\n x = 0;\n }\n \n // Ensure window top edge doesn't exceed screen\n if (y < 0) {\n y = 0;\n }\n \n // If window position needs adjustment, move the window\n if (x != rect.left || y != rect.top) {\n SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n }\n}\n\nextern void GetConfigPath(char* path, size_t size);\nextern void WriteConfigEditMode(const char* mode);\n\nvoid SaveWindowSettings(HWND hwnd) {\n if (!hwnd) return;\n\n RECT rect;\n if (!GetWindowRect(hwnd, &rect)) return;\n \n CLOCK_WINDOW_POS_X = rect.left;\n CLOCK_WINDOW_POS_Y = rect.top;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n size_t buffer_size = 8192; \n char *config = malloc(buffer_size);\n char *new_config = malloc(buffer_size);\n if (!config || !new_config) {\n if (config) free(config);\n if (new_config) free(new_config);\n fclose(fp);\n return;\n }\n \n config[0] = new_config[0] = '\\0';\n char line[256];\n size_t total_len = 0;\n \n while (fgets(line, sizeof(line), fp)) {\n size_t line_len = strlen(line);\n if (total_len + line_len >= buffer_size - 1) {\n size_t new_size = buffer_size * 2;\n char *temp_config = realloc(config, new_size);\n char *temp_new_config = realloc(new_config, new_size);\n \n if (!temp_config || !temp_new_config) {\n free(config);\n free(new_config);\n fclose(fp);\n return;\n }\n \n config = temp_config;\n new_config = temp_new_config;\n buffer_size = new_size;\n }\n strcat(config, line);\n total_len += line_len;\n }\n fclose(fp);\n \n char *start = config;\n char *end = config + strlen(config);\n BOOL has_window_scale = FALSE;\n size_t new_config_len = 0;\n \n while (start < end) {\n char *newline = strchr(start, '\\n');\n if (!newline) newline = end;\n \n char temp[256] = {0};\n size_t line_len = newline - start;\n if (line_len >= sizeof(temp)) line_len = sizeof(temp) - 1;\n strncpy(temp, start, line_len);\n \n if (strncmp(temp, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len, \n buffer_size - new_config_len, \n \"CLOCK_WINDOW_POS_X=%d\\n\", CLOCK_WINDOW_POS_X);\n } else if (strncmp(temp, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"CLOCK_WINDOW_POS_Y=%d\\n\", CLOCK_WINDOW_POS_Y);\n } else if (strncmp(temp, \"WINDOW_SCALE=\", 13) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n has_window_scale = TRUE;\n } else {\n size_t remaining = buffer_size - new_config_len;\n if (remaining > line_len + 1) {\n strncpy(new_config + new_config_len, start, line_len);\n new_config_len += line_len;\n new_config[new_config_len++] = '\\n';\n }\n }\n \n start = newline + 1;\n if (start > end) break;\n }\n \n if (!has_window_scale && buffer_size - new_config_len > 50) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n }\n \n if (new_config_len < buffer_size) {\n new_config[new_config_len] = '\\0';\n } else {\n new_config[buffer_size - 1] = '\\0';\n }\n \n fp = fopen(config_path, \"w\");\n if (fp) {\n fputs(new_config, fp);\n fclose(fp);\n }\n \n free(config);\n free(new_config);\n}\n\nvoid LoadWindowSettings(HWND hwnd) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n line[strcspn(line, \"\\n\")] = 0;\n \n if (strncmp(line, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n CLOCK_WINDOW_POS_X = atoi(line + 19);\n } else if (strncmp(line, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n CLOCK_WINDOW_POS_Y = atoi(line + 19);\n } else if (strncmp(line, \"WINDOW_SCALE=\", 13) == 0) {\n CLOCK_WINDOW_SCALE = atof(line + 13);\n CLOCK_FONT_SCALE_FACTOR = CLOCK_WINDOW_SCALE;\n }\n }\n fclose(fp);\n \n // Apply position from config file directly, without additional adjustments\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, \n CLOCK_WINDOW_POS_Y,\n (int)(CLOCK_BASE_WINDOW_WIDTH * CLOCK_WINDOW_SCALE),\n (int)(CLOCK_BASE_WINDOW_HEIGHT * CLOCK_WINDOW_SCALE),\n SWP_NOZORDER\n );\n \n // Don't call AdjustWindowPosition to avoid overriding user settings\n}\n\nBOOL HandleMouseWheel(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n // Remove original position calculation logic, directly use window center as scaling reference point\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n // Use window center as scaling reference\n float relativeX = 0.5f;\n float relativeY = 0.5f;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings after resizing\n SaveWindowSettings(hwnd);\n }\n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleMouseMove(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update the position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nHWND CreateMainWindow(HINSTANCE hInstance, int nCmdShow) {\n // Window class registration\n WNDCLASS wc = {0};\n wc.lpfnWndProc = WindowProcedure;\n wc.hInstance = hInstance;\n wc.lpszClassName = \"CatimeWindow\";\n \n if (!RegisterClass(&wc)) {\n MessageBox(NULL, \"Window Registration Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n // Set extended style\n DWORD exStyle = WS_EX_LAYERED | WS_EX_TOOLWINDOW;\n \n // If not in topmost mode, add WS_EX_NOACTIVATE extended style\n if (!CLOCK_WINDOW_TOPMOST) {\n exStyle |= WS_EX_NOACTIVATE;\n }\n \n // Create window\n HWND hwnd = CreateWindowEx(\n exStyle,\n \"CatimeWindow\",\n \"Catime\",\n WS_POPUP,\n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n CLOCK_BASE_WINDOW_WIDTH, CLOCK_BASE_WINDOW_HEIGHT,\n NULL,\n NULL,\n hInstance,\n NULL\n );\n\n if (!hwnd) {\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n EnableWindow(hwnd, TRUE);\n SetFocus(hwnd);\n\n // Set window transparency\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n\n // Set blur effect\n SetBlurBehind(hwnd, FALSE);\n\n // Initialize tray icon\n InitTrayIcon(hwnd, hInstance);\n\n // Show window\n ShowWindow(hwnd, nCmdShow);\n UpdateWindow(hwnd);\n\n // Set window position and parent based on topmost status\n if (CLOCK_WINDOW_TOPMOST) {\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n } else {\n // Find desktop window and set as parent\n HWND hProgman = FindWindow(\"Progman\", NULL);\n if (hProgman != NULL) {\n // Try to find the real desktop window\n HWND hDesktop = hProgman;\n \n // Look for WorkerW window (common in Win10+)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n \n // Set as child window of desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, set to bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n\n return hwnd;\n}\n\nfloat CLOCK_FONT_SCALE_FACTOR = 1.0f;\nint CLOCK_BASE_FONT_SIZE = 24;\n\nBOOL InitializeApplication(HINSTANCE hInstance) {\n // Set DPI awareness mode to Per-Monitor DPI Aware to properly handle scaling when moving window between displays with different DPIs\n // Use newer API SetProcessDpiAwarenessContext if available, otherwise fallback to older APIs\n \n // Define DPI awareness related constants and types\n #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);\n #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n #endif\n \n // Define PROCESS_DPI_AWARENESS enum\n typedef enum {\n PROCESS_DPI_UNAWARE = 0,\n PROCESS_SYSTEM_DPI_AWARE = 1,\n PROCESS_PER_MONITOR_DPI_AWARE = 2\n } PROCESS_DPI_AWARENESS;\n \n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n typedef BOOL(WINAPI* SetProcessDpiAwarenessContextFunc)(DPI_AWARENESS_CONTEXT);\n SetProcessDpiAwarenessContextFunc setProcessDpiAwarenessContextFunc =\n (SetProcessDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetProcessDpiAwarenessContext\");\n \n if (setProcessDpiAwarenessContextFunc) {\n // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 is the latest DPI awareness mode\n // It provides better multi-monitor DPI support\n setProcessDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n } else {\n // Try using older API\n HMODULE hShcore = LoadLibraryA(\"shcore.dll\");\n if (hShcore) {\n typedef HRESULT(WINAPI* SetProcessDpiAwarenessFunc)(PROCESS_DPI_AWARENESS);\n SetProcessDpiAwarenessFunc setProcessDpiAwarenessFunc =\n (SetProcessDpiAwarenessFunc)GetProcAddress(hShcore, \"SetProcessDpiAwareness\");\n \n if (setProcessDpiAwarenessFunc) {\n // PROCESS_PER_MONITOR_DPI_AWARE corresponds to per-monitor DPI awareness\n setProcessDpiAwarenessFunc(PROCESS_PER_MONITOR_DPI_AWARE);\n } else {\n // Finally try the oldest API\n SetProcessDPIAware();\n }\n \n FreeLibrary(hShcore);\n } else {\n // If shcore.dll is not available, use the most basic DPI awareness API\n SetProcessDPIAware();\n }\n }\n }\n \n SetConsoleOutputCP(936);\n SetConsoleCP(936);\n\n // Modified initialization order: read config file first, then initialize other features\n ReadConfig();\n UpdateStartupShortcut();\n InitializeDefaultLanguage();\n\n int defaultFontIndex = -1;\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, FONT_FILE_NAME) == 0) {\n defaultFontIndex = i;\n break;\n }\n }\n\n if (defaultFontIndex != -1) {\n LoadFontFromResource(hInstance, fontResources[defaultFontIndex].resourceId);\n }\n\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n \n return TRUE;\n}\n\nBOOL OpenFileDialog(HWND hwnd, char* filePath, DWORD maxPath) {\n OPENFILENAME ofn = { 0 };\n ofn.lStructSize = sizeof(OPENFILENAME);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFilter = \"All Files\\0*.*\\0\";\n ofn.lpstrFile = filePath;\n ofn.nMaxFile = maxPath;\n ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;\n ofn.lpstrDefExt = \"\";\n \n return GetOpenFileName(&ofn);\n}\n\n// Add function to set window topmost state\nvoid SetWindowTopmost(HWND hwnd, BOOL topmost) {\n CLOCK_WINDOW_TOPMOST = topmost;\n \n // Get current window style\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n if (topmost) {\n // Topmost mode: remove no-activate style (if exists), add topmost style\n exStyle &= ~WS_EX_NOACTIVATE;\n \n // If window was previously set as desktop child window, need to restore\n // First set window as top-level window, clear parent window relationship\n SetParent(hwnd, NULL);\n \n // Reset window owner, ensure Z-order is correct\n SetWindowLongPtr(hwnd, GWLP_HWNDPARENT, 0);\n \n // Set window position to top layer, and force window update\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_FRAMECHANGED);\n } else {\n // Non-topmost mode: add no-activate style to prevent window from gaining focus\n exStyle |= WS_EX_NOACTIVATE;\n \n // Set as child window of desktop\n HWND hProgman = FindWindow(\"Progman\", NULL);\n HWND hDesktop = NULL;\n \n // Try to find the real desktop window\n if (hProgman != NULL) {\n // First try using Progman\n hDesktop = hProgman;\n \n // Look for WorkerW window (more common on Win10)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n // Found the real desktop container\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n }\n \n if (hDesktop != NULL) {\n // Set window as child of desktop, this keeps it on the desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, at least place at bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n \n // Apply new window style\n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Force window update\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n \n // Save window topmost setting\n WriteConfigTopmost(topmost ? \"TRUE\" : \"FALSE\");\n}\n"], ["/Catime/src/config.c", "/**\n * @file config.c\n * @brief Configuration file management module implementation\n */\n\n#include \"../include/config.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define MAX_POMODORO_TIMES 10\n\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nint POMODORO_TIMES[MAX_POMODORO_TIMES] = {1500, 300, 1500, 600};\nint POMODORO_TIMES_COUNT = 4;\n\nchar CLOCK_TIMEOUT_MESSAGE_TEXT[100] = \"时间到啦!\";\nchar POMODORO_TIMEOUT_MESSAGE_TEXT[100] = \"番茄钟时间到!\";\nchar POMODORO_CYCLE_COMPLETE_TEXT[100] = \"所有番茄钟循环完成!\";\n\nint NOTIFICATION_TIMEOUT_MS = 3000;\nint NOTIFICATION_MAX_OPACITY = 95;\nNotificationType NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\nBOOL NOTIFICATION_DISABLED = FALSE;\n\nchar NOTIFICATION_SOUND_FILE[MAX_PATH] = \"\";\nint NOTIFICATION_SOUND_VOLUME = 100;\n\n/** @brief Read string value from INI file */\nDWORD ReadIniString(const char* section, const char* key, const char* defaultValue,\n char* returnValue, DWORD returnSize, const char* filePath) {\n return GetPrivateProfileStringA(section, key, defaultValue, returnValue, returnSize, filePath);\n}\n\n/** @brief Write string value to INI file */\nBOOL WriteIniString(const char* section, const char* key, const char* value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value, filePath);\n}\n\n/** @brief Read integer value from INI */\nint ReadIniInt(const char* section, const char* key, int defaultValue, \n const char* filePath) {\n return GetPrivateProfileIntA(section, key, defaultValue, filePath);\n}\n\n/** @brief Write integer value to INI file */\nBOOL WriteIniInt(const char* section, const char* key, int value,\n const char* filePath) {\n char valueStr[32];\n snprintf(valueStr, sizeof(valueStr), \"%d\", value);\n return WritePrivateProfileStringA(section, key, valueStr, filePath);\n}\n\n/** @brief Write boolean value to INI file */\nBOOL WriteIniBool(const char* section, const char* key, BOOL value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value ? \"TRUE\" : \"FALSE\", filePath);\n}\n\n/** @brief Read boolean value from INI */\nBOOL ReadIniBool(const char* section, const char* key, BOOL defaultValue, \n const char* filePath) {\n char value[8];\n GetPrivateProfileStringA(section, key, defaultValue ? \"TRUE\" : \"FALSE\", \n value, sizeof(value), filePath);\n return _stricmp(value, \"TRUE\") == 0;\n}\n\n/** @brief Check if configuration file exists */\nBOOL FileExists(const char* filePath) {\n return GetFileAttributesA(filePath) != INVALID_FILE_ATTRIBUTES;\n}\n\n/** @brief Get configuration file path */\nvoid GetConfigPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\config.ini\", appdata_path) >= size) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Create default configuration file */\nvoid CreateDefaultConfig(const char* config_path) {\n // Get system default language ID\n LANGID systemLangID = GetUserDefaultUILanguage();\n int defaultLanguage = APP_LANG_ENGLISH; // Default to English\n const char* langName = \"English\"; // Default language name\n \n // Set default language based on system language ID\n switch (PRIMARYLANGID(systemLangID)) {\n case LANG_CHINESE:\n if (SUBLANGID(systemLangID) == SUBLANG_CHINESE_SIMPLIFIED) {\n defaultLanguage = APP_LANG_CHINESE_SIMP;\n langName = \"Chinese_Simplified\";\n } else {\n defaultLanguage = APP_LANG_CHINESE_TRAD;\n langName = \"Chinese_Traditional\";\n }\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n langName = \"Spanish\";\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n langName = \"French\";\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n langName = \"German\";\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n langName = \"Russian\";\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n langName = \"Portuguese\";\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n langName = \"Japanese\";\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n langName = \"Korean\";\n break;\n case LANG_ENGLISH:\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n langName = \"English\";\n break;\n }\n \n // Choose default settings based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", \"TRUE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 1; i <= 5; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n config_path);\n}\n\n/** @brief Extract filename from file path */\nvoid ExtractFileName(const char* path, char* name, size_t nameSize) {\n if (!path || !name || nameSize == 0) return;\n \n // First convert to wide characters to properly handle Unicode paths\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, wPath, MAX_PATH);\n \n // Look for the last backslash or forward slash\n wchar_t* lastSlash = wcsrchr(wPath, L'\\\\');\n if (!lastSlash) lastSlash = wcsrchr(wPath, L'/');\n \n wchar_t wName[MAX_PATH] = {0};\n if (lastSlash) {\n wcscpy(wName, lastSlash + 1);\n } else {\n wcscpy(wName, wPath);\n }\n \n // Convert back to UTF-8\n WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, nameSize, NULL, NULL);\n}\n\n/** @brief Check and create resource folders */\nvoid CheckAndCreateResourceFolders() {\n char config_path[MAX_PATH];\n char base_path[MAX_PATH];\n char resource_path[MAX_PATH];\n char *last_slash;\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Copy configuration file path\n strncpy(base_path, config_path, MAX_PATH - 1);\n base_path[MAX_PATH - 1] = '\\0';\n \n // Find the last slash or backslash, which marks the beginning of the filename\n last_slash = strrchr(base_path, '\\\\');\n if (!last_slash) {\n last_slash = strrchr(base_path, '/');\n }\n \n if (last_slash) {\n // Truncate path to directory part\n *(last_slash + 1) = '\\0';\n \n // Create resources main directory\n snprintf(resource_path, MAX_PATH, \"%sresources\", base_path);\n DWORD attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create resources folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n return;\n }\n }\n \n // Create audio subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\audio\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create audio folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create images subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\images\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create images folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create animations subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\animations\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create animations folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create themes subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\themes\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create themes folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create plug-in subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\plug-in\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create plug-in folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n }\n}\n\n/** @brief Read and parse configuration file */\nvoid ReadConfig() {\n // Check and create resource folders\n CheckAndCreateResourceFolders();\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Check if configuration file exists, create default configuration if it doesn't\n if (!FileExists(config_path)) {\n CreateDefaultConfig(config_path);\n }\n \n // Check configuration file version\n char version[32] = {0};\n BOOL versionMatched = FALSE;\n \n // Read current version information\n ReadIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", \"\", version, sizeof(version), config_path);\n \n // Compare if version matches\n if (strcmp(version, CATIME_VERSION) == 0) {\n versionMatched = TRUE;\n }\n \n // If version doesn't match, recreate the configuration file\n if (!versionMatched) {\n CreateDefaultConfig(config_path);\n }\n\n // Reset time options\n time_options_count = 0;\n memset(time_options, 0, sizeof(time_options));\n \n // Reset recent files count\n CLOCK_RECENT_FILES_COUNT = 0;\n \n // Read basic settings\n // ======== [General] Section ========\n char language[32] = {0};\n ReadIniString(INI_SECTION_GENERAL, \"LANGUAGE\", \"English\", language, sizeof(language), config_path);\n \n // Convert language name to enum value\n int languageSetting = APP_LANG_ENGLISH; // Default to English\n \n if (strcmp(language, \"Chinese_Simplified\") == 0) {\n languageSetting = APP_LANG_CHINESE_SIMP;\n } else if (strcmp(language, \"Chinese_Traditional\") == 0) {\n languageSetting = APP_LANG_CHINESE_TRAD;\n } else if (strcmp(language, \"English\") == 0) {\n languageSetting = APP_LANG_ENGLISH;\n } else if (strcmp(language, \"Spanish\") == 0) {\n languageSetting = APP_LANG_SPANISH;\n } else if (strcmp(language, \"French\") == 0) {\n languageSetting = APP_LANG_FRENCH;\n } else if (strcmp(language, \"German\") == 0) {\n languageSetting = APP_LANG_GERMAN;\n } else if (strcmp(language, \"Russian\") == 0) {\n languageSetting = APP_LANG_RUSSIAN;\n } else if (strcmp(language, \"Portuguese\") == 0) {\n languageSetting = APP_LANG_PORTUGUESE;\n } else if (strcmp(language, \"Japanese\") == 0) {\n languageSetting = APP_LANG_JAPANESE;\n } else if (strcmp(language, \"Korean\") == 0) {\n languageSetting = APP_LANG_KOREAN;\n } else {\n // Try to parse as number (for backward compatibility)\n int langValue = atoi(language);\n if (langValue >= 0 && langValue < APP_LANG_COUNT) {\n languageSetting = langValue;\n } else {\n languageSetting = APP_LANG_ENGLISH; // Default to English\n }\n }\n \n // ======== [Display] Section ========\n ReadIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", CLOCK_TEXT_COLOR, sizeof(CLOCK_TEXT_COLOR), config_path);\n CLOCK_BASE_FONT_SIZE = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n ReadIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", FONT_FILE_NAME, sizeof(FONT_FILE_NAME), config_path);\n \n // Extract internal name from font filename\n size_t font_name_len = strlen(FONT_FILE_NAME);\n if (font_name_len > 4 && strcmp(FONT_FILE_NAME + font_name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = font_name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n CLOCK_WINDOW_POS_X = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n CLOCK_WINDOW_POS_Y = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n \n char scaleStr[16] = {0};\n ReadIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", scaleStr, sizeof(scaleStr), config_path);\n CLOCK_WINDOW_SCALE = atof(scaleStr);\n \n CLOCK_WINDOW_TOPMOST = ReadIniBool(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", TRUE, config_path);\n \n // Check and replace pure black color\n if (strcasecmp(CLOCK_TEXT_COLOR, \"#000000\") == 0) {\n strncpy(CLOCK_TEXT_COLOR, \"#000001\", sizeof(CLOCK_TEXT_COLOR) - 1);\n }\n \n // ======== [Timer] Section ========\n CLOCK_DEFAULT_START_TIME = ReadIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n CLOCK_USE_24HOUR = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", FALSE, config_path);\n CLOCK_SHOW_SECONDS = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", FALSE, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", CLOCK_TIMEOUT_TEXT, sizeof(CLOCK_TIMEOUT_TEXT), config_path);\n \n // Read timeout action\n char timeoutAction[32] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", timeoutAction, sizeof(timeoutAction), config_path);\n \n if (strcmp(timeoutAction, \"MESSAGE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"LOCK\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n } else if (strcmp(timeoutAction, \"SHUTDOWN\") == 0) {\n // Even if SHUTDOWN exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"RESTART\") == 0) {\n // Even if RESTART exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"OPEN_FILE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n } else if (strcmp(timeoutAction, \"SHOW_TIME\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n } else if (strcmp(timeoutAction, \"COUNT_UP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n } else if (strcmp(timeoutAction, \"OPEN_WEBSITE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n } else if (strcmp(timeoutAction, \"SLEEP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n } else if (strcmp(timeoutAction, \"RUN_COMMAND\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n } else if (strcmp(timeoutAction, \"HTTP_REQUEST\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n }\n \n // Read timeout file and website settings\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", CLOCK_TIMEOUT_FILE_PATH, MAX_PATH, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", CLOCK_TIMEOUT_WEBSITE_URL, MAX_PATH, config_path);\n \n // If file path is valid, ensure timeout action is set to open file\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n GetFileAttributesA(CLOCK_TIMEOUT_FILE_PATH) != INVALID_FILE_ATTRIBUTES) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n }\n \n // If URL is valid, ensure timeout action is set to open website\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n }\n \n // Read time options\n char timeOptions[256] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", timeOptions, sizeof(timeOptions), config_path);\n \n char *token = strtok(timeOptions, \",\");\n while (token && time_options_count < MAX_TIME_OPTIONS) {\n while (*token == ' ') token++;\n time_options[time_options_count++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Read startup mode\n ReadIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", CLOCK_STARTUP_MODE, sizeof(CLOCK_STARTUP_MODE), config_path);\n \n // ======== [Pomodoro] Section ========\n char pomodoroTimeOptions[256] = {0};\n ReadIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", pomodoroTimeOptions, sizeof(pomodoroTimeOptions), config_path);\n \n // Reset pomodoro time count\n POMODORO_TIMES_COUNT = 0;\n \n // Parse all pomodoro time values\n token = strtok(pomodoroTimeOptions, \",\");\n while (token && POMODORO_TIMES_COUNT < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[POMODORO_TIMES_COUNT++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Even though we now use a new array to store all times,\n // keep these three variables for backward compatibility\n if (POMODORO_TIMES_COUNT > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (POMODORO_TIMES_COUNT > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (POMODORO_TIMES_COUNT > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[3]; // Note this is the 4th value\n }\n \n // Read pomodoro loop count\n POMODORO_LOOP_COUNT = ReadIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n \n // ======== [Notification] Section ========\n ReadIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", \n CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", \n POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", \n POMODORO_CYCLE_COMPLETE_TEXT, sizeof(POMODORO_CYCLE_COMPLETE_TEXT), config_path);\n \n NOTIFICATION_TIMEOUT_MS = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n NOTIFICATION_MAX_OPACITY = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n \n // Ensure opacity is within valid range (1-100)\n if (NOTIFICATION_MAX_OPACITY < 1) NOTIFICATION_MAX_OPACITY = 1;\n if (NOTIFICATION_MAX_OPACITY > 100) NOTIFICATION_MAX_OPACITY = 100;\n \n char notificationType[32] = {0};\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", \"CATIME\", notificationType, sizeof(notificationType), config_path);\n \n // Set notification type\n if (strcmp(notificationType, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(notificationType, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(notificationType, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Read notification audio file path\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", \n NOTIFICATION_SOUND_FILE, MAX_PATH, config_path);\n \n // Read notification audio volume\n NOTIFICATION_SOUND_VOLUME = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n \n // Read whether to disable notification window\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n \n // Ensure volume is within valid range (0-100)\n if (NOTIFICATION_SOUND_VOLUME < 0) NOTIFICATION_SOUND_VOLUME = 0;\n if (NOTIFICATION_SOUND_VOLUME > 100) NOTIFICATION_SOUND_VOLUME = 100;\n \n // ======== [Colors] Section ========\n char colorOptions[1024] = {0};\n ReadIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n colorOptions, sizeof(colorOptions), config_path);\n \n // Parse color options\n token = strtok(colorOptions, \",\");\n COLOR_OPTIONS_COUNT = 0;\n while (token) {\n COLOR_OPTIONS = realloc(COLOR_OPTIONS, sizeof(PredefinedColor) * (COLOR_OPTIONS_COUNT + 1));\n if (COLOR_OPTIONS) {\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = strdup(token);\n COLOR_OPTIONS_COUNT++;\n }\n token = strtok(NULL, \",\");\n }\n \n // ======== [RecentFiles] Section ========\n // Read recent file records\n for (int i = 1; i <= MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n \n char filePath[MAX_PATH] = {0};\n ReadIniString(INI_SECTION_RECENTFILES, key, \"\", filePath, MAX_PATH, config_path);\n \n if (strlen(filePath) > 0) {\n // Convert to wide characters to properly check if the file exists\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, widePath, MAX_PATH);\n \n // Check if file exists\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n ExtractFileName(filePath, CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, MAX_PATH);\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n \n // ======== [Hotkeys] Section ========\n // Read hotkey configurations from INI file\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n // Read hotkey settings\n char hotkeyStr[32] = {0};\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n showTimeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countUpHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countdownHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown1Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown2Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown3Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pomodoroHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n toggleVisibilityHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n editModeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pauseResumeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n restartTimerHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n customCountdownHotkey = StringToHotkey(hotkeyStr);\n \n last_config_time = time(NULL);\n\n // Apply window position\n HWND hwnd = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwnd) {\n SetWindowPos(hwnd, NULL, CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n\n // Apply language settings\n SetLanguage((AppLanguage)languageSetting);\n}\n\n/** @brief Write timeout action configuration */\nvoid WriteConfigTimeoutAction(const char* action) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n // For shutdown or restart actions, don't write them to the config file, write \"MESSAGE\" instead\n const char* actual_action = action;\n if (strcmp(action, \"RESTART\") == 0 || strcmp(action, \"SHUTDOWN\") == 0 || strcmp(action, \"SLEEP\") == 0) {\n actual_action = \"MESSAGE\";\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write time options configuration */\nvoid WriteConfigTimeOptions(const char* options) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIME_OPTIONS=\", 19) == 0) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Load recently used file records */\nvoid LoadRecentFiles(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) return;\n\n char line[MAX_PATH];\n CLOCK_RECENT_FILES_COUNT = 0;\n\n while (fgets(line, sizeof(line), file)) {\n // Support for the CLOCK_RECENT_FILE_N=path format\n if (strncmp(line, \"CLOCK_RECENT_FILE_\", 18) == 0) {\n char *path = strchr(line + 18, '=');\n if (path) {\n path++; // Skip the equals sign\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n // Also update the old format for compatibility\n else if (strncmp(line, \"CLOCK_RECENT_FILE=\", 18) == 0) {\n char *path = line + 18;\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n\n fclose(file);\n}\n\n/** @brief Save recently used file record */\nvoid SaveRecentFile(const char* filePath) {\n // Check if the file path is valid\n if (!filePath || strlen(filePath) == 0) return;\n \n // Convert to wide characters to check if the file exists\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) == INVALID_FILE_ATTRIBUTES) {\n // File doesn't exist, don't add it\n return;\n }\n \n // Check if the file is already in the list\n int existingIndex = -1;\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n if (strcmp(CLOCK_RECENT_FILES[i].path, filePath) == 0) {\n existingIndex = i;\n break;\n }\n }\n \n if (existingIndex == 0) {\n // File is already at the top of the list, no action needed\n return;\n }\n \n if (existingIndex > 0) {\n // File is in the list, but not at the top, need to move it\n RecentFile temp = CLOCK_RECENT_FILES[existingIndex];\n \n // Move elements backward\n for (int i = existingIndex; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Put it at the first position\n CLOCK_RECENT_FILES[0] = temp;\n } else {\n // File is not in the list, need to add it\n // First ensure the list doesn't exceed 5 items\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n CLOCK_RECENT_FILES_COUNT++;\n }\n \n // Move elements backward\n for (int i = CLOCK_RECENT_FILES_COUNT - 1; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Add new file to the first position\n strncpy(CLOCK_RECENT_FILES[0].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[0].path[MAX_PATH - 1] = '\\0';\n \n // Extract filename\n ExtractFileName(filePath, CLOCK_RECENT_FILES[0].name, MAX_PATH);\n }\n \n // Update configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n WriteConfig(configPath);\n}\n\n/** @brief Convert UTF8 to ANSI encoding */\nchar* UTF8ToANSI(const char* utf8Str) {\n int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, NULL, 0);\n if (wlen == 0) {\n return _strdup(utf8Str);\n }\n\n wchar_t* wstr = (wchar_t*)malloc(sizeof(wchar_t) * wlen);\n if (!wstr) {\n return _strdup(utf8Str);\n }\n\n if (MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, wstr, wlen) == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n int len = WideCharToMultiByte(936, 0, wstr, -1, NULL, 0, NULL, NULL);\n if (len == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n char* str = (char*)malloc(len);\n if (!str) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n if (WideCharToMultiByte(936, 0, wstr, -1, str, len, NULL, NULL) == 0) {\n free(wstr);\n free(str);\n return _strdup(utf8Str);\n }\n\n free(wstr);\n return str;\n}\n\n/** @brief Write pomodoro time settings */\nvoid WriteConfigPomodoroTimes(int work, int short_break, int long_break) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n // Update global variables\n // Maintain backward compatibility, while updating the POMODORO_TIMES array\n POMODORO_WORK_TIME = work;\n POMODORO_SHORT_BREAK = short_break;\n POMODORO_LONG_BREAK = long_break;\n \n // Ensure at least these three time values exist\n POMODORO_TIMES[0] = work;\n if (POMODORO_TIMES_COUNT < 1) POMODORO_TIMES_COUNT = 1;\n \n if (POMODORO_TIMES_COUNT > 1) {\n POMODORO_TIMES[1] = short_break;\n } else if (short_break > 0) {\n POMODORO_TIMES[1] = short_break;\n POMODORO_TIMES_COUNT = 2;\n }\n \n if (POMODORO_TIMES_COUNT > 2) {\n POMODORO_TIMES[2] = long_break;\n } else if (long_break > 0) {\n POMODORO_TIMES[2] = long_break;\n POMODORO_TIMES_COUNT = 3;\n }\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n // Look for POMODORO_TIME_OPTIONS line\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write all pomodoro times\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If POMODORO_TIME_OPTIONS was not found, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro loop count configuration */\nvoid WriteConfigPomodoroLoopCount(int loop_count) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If the key was not found in the configuration file, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n POMODORO_LOOP_COUNT = loop_count;\n}\n\n/** @brief Write window topmost status configuration */\nvoid WriteConfigTopmost(const char* topmost) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"WINDOW_TOPMOST=\", 15) == 0) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write timeout open file path */\nvoid WriteConfigTimeoutFile(const char* filePath) {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n strncpy(CLOCK_TIMEOUT_FILE_PATH, filePath, MAX_PATH - 1);\n CLOCK_TIMEOUT_FILE_PATH[MAX_PATH - 1] = '\\0';\n \n // Use WriteConfig to completely rewrite the configuration file, maintaining structural consistency\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n}\n\n/** @brief Write all configuration settings to file */\nvoid WriteConfig(const char* config_path) {\n // Get the name of the current language\n AppLanguage currentLang = GetCurrentLanguage();\n const char* langName;\n \n switch (currentLang) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n case APP_LANG_ENGLISH:\n default:\n langName = \"English\";\n break;\n }\n \n // Choose string representation based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Read hotkey settings\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0};\n \n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Prepare time options string\n char timeOptionsStr[256] = {0};\n for (int i = 0; i < time_options_count; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", time_options[i]);\n \n if (i > 0) {\n strcat(timeOptionsStr, \",\");\n }\n strcat(timeOptionsStr, buffer);\n }\n \n // Prepare pomodoro time options string\n char pomodoroTimesStr[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", POMODORO_TIMES[i]);\n \n if (i > 0) {\n strcat(pomodoroTimesStr, \",\");\n }\n strcat(pomodoroTimesStr, buffer);\n }\n \n // Prepare color options string\n char colorOptionsStr[1024] = {0};\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (i > 0) {\n strcat(colorOptionsStr, \",\");\n }\n strcat(colorOptionsStr, COLOR_OPTIONS[i].hexColor);\n }\n \n // Determine timeout action string\n const char* timeoutActionStr;\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_LOCK:\n timeoutActionStr = \"LOCK\";\n break;\n case TIMEOUT_ACTION_SHUTDOWN:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RESTART:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_OPEN_FILE:\n timeoutActionStr = \"OPEN_FILE\";\n break;\n case TIMEOUT_ACTION_SHOW_TIME:\n timeoutActionStr = \"SHOW_TIME\";\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n timeoutActionStr = \"COUNT_UP\";\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n timeoutActionStr = \"OPEN_WEBSITE\";\n break;\n case TIMEOUT_ACTION_SLEEP:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n timeoutActionStr = \"RUN_COMMAND\";\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n timeoutActionStr = \"HTTP_REQUEST\";\n break;\n default:\n timeoutActionStr = \"MESSAGE\";\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", IsShortcutCheckDone() ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", CLOCK_TEXT_COLOR, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", CLOCK_BASE_FONT_SIZE, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", FONT_FILE_NAME, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", CLOCK_WINDOW_POS_X, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", CLOCK_WINDOW_POS_Y, config_path);\n \n char scaleStr[16];\n snprintf(scaleStr, sizeof(scaleStr), \"%.2f\", CLOCK_WINDOW_SCALE);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", scaleStr, config_path);\n \n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", CLOCK_WINDOW_TOPMOST ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", CLOCK_DEFAULT_START_TIME, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", CLOCK_USE_24HOUR ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", CLOCK_SHOW_SECONDS ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", CLOCK_TIMEOUT_TEXT, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", timeoutActionStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", CLOCK_TIMEOUT_FILE_PATH, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", CLOCK_TIMEOUT_WEBSITE_URL, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", timeOptionsStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", CLOCK_STARTUP_MODE, config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", pomodoroTimesStr, config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", POMODORO_LOOP_COUNT, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", CLOCK_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", POMODORO_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", POMODORO_CYCLE_COMPLETE_TEXT, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", NOTIFICATION_TIMEOUT_MS, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", NOTIFICATION_MAX_OPACITY, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", NOTIFICATION_SOUND_FILE, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", NOTIFICATION_SOUND_VOLUME, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", NOTIFICATION_DISABLED ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", showTimeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", countUpStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", countdownStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", quickCountdown1Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", quickCountdown2Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", quickCountdown3Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", pomodoroStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", toggleVisibilityStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", editModeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", pauseResumeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", restartTimerStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr, config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, CLOCK_RECENT_FILES[i].path, config_path);\n }\n \n // Clear unused file records\n for (int i = CLOCK_RECENT_FILES_COUNT; i < MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", colorOptionsStr, config_path);\n}\n\n/** @brief Write timeout open website URL */\nvoid WriteConfigTimeoutWebsite(const char* url) {\n // Only set timeout action to open website if a valid URL is provided\n if (url && url[0] != '\\0') {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n strncpy(CLOCK_TIMEOUT_WEBSITE_URL, url, MAX_PATH - 1);\n CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH - 1] = '\\0';\n \n // Then update the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL actionFound = FALSE;\n BOOL urlFound = FALSE;\n \n // Read original configuration file, update timeout action and URL\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n actionFound = TRUE;\n } else if (strncmp(line, \"CLOCK_TIMEOUT_WEBSITE=\", 22) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n urlFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If these items are not in the configuration, add them\n if (!actionFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n }\n if (!urlFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n }\n}\n\n/** @brief Write startup mode configuration */\nvoid WriteConfigStartupMode(const char* mode) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n // Update global variable\n strncpy(CLOCK_STARTUP_MODE, mode, sizeof(CLOCK_STARTUP_MODE) - 1);\n CLOCK_STARTUP_MODE[sizeof(CLOCK_STARTUP_MODE) - 1] = '\\0';\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro time options */\nvoid WriteConfigPomodoroTimeOptions(int* times, int count) {\n if (!times || count <= 0) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL optionsFound = FALSE;\n \n // Read original configuration file, update pomodoro time options\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write new time options\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n optionsFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If this item is not in the configuration, add it\n if (!optionsFound) {\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write notification message configuration */\nvoid WriteConfigNotificationMessages(const char* timeout_msg, const char* pomodoro_msg, const char* cycle_complete_msg) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n // Use standard C file operations instead of Windows API\n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL timeoutFound = FALSE;\n BOOL pomodoroFound = FALSE;\n BOOL cycleFound = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n timeoutFound = TRUE;\n } else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n pomodoroFound = TRUE;\n } else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n cycleFound = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If corresponding items are not found in the configuration, add them\n if (!timeoutFound) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n }\n \n if (!pomodoroFound) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n }\n \n if (!cycleFound) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variables\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, timeout_msg, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, pomodoro_msg, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, cycle_complete_msg, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n}\n\n/** @brief Read notification message text from configuration file */\nvoid ReadNotificationMessagesConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current values in memory or default values\n return;\n }\n\n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[1024];\n BOOL timeoutMsgFound = FALSE;\n BOOL pomodoroTimeoutMsgFound = FALSE;\n BOOL cycleCompleteMsgFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n // Process this line\n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, line + 27, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n timeoutMsgFound = TRUE;\n } \n else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, line + 30, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n pomodoroTimeoutMsgFound = TRUE;\n }\n else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, line + 29, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n cycleCompleteMsgFound = TRUE;\n }\n \n // If all messages have been found, can exit loop early\n if (timeoutMsgFound && pomodoroTimeoutMsgFound && cycleCompleteMsgFound) {\n break;\n }\n }\n \n CloseHandle(hFile);\n \n // If corresponding configuration items are not found in the file, ensure variables have default values\n if (!timeoutMsgFound) {\n strcpy(CLOCK_TIMEOUT_MESSAGE_TEXT, \"时间到啦!\"); // Default value\n }\n if (!pomodoroTimeoutMsgFound) {\n strcpy(POMODORO_TIMEOUT_MESSAGE_TEXT, \"番茄钟时间到!\"); // Default value\n }\n if (!cycleCompleteMsgFound) {\n strcpy(POMODORO_CYCLE_COMPLETE_TEXT, \"所有番茄钟循环完成!\"); // Default value\n }\n}\n\n/** @brief Read notification display time from configuration file */\nvoid ReadNotificationTimeoutConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL timeoutFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n int timeout = atoi(line + 24);\n if (timeout > 0) {\n NOTIFICATION_TIMEOUT_MS = timeout;\n }\n timeoutFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!timeoutFound) {\n NOTIFICATION_TIMEOUT_MS = 3000; // Ensure there's a default value\n }\n}\n\n/** @brief Write notification display time configuration */\nvoid WriteConfigNotificationTimeout(int timeout_ms) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_TIMEOUT_MS = timeout_ms;\n}\n\n/** @brief Read maximum notification opacity from configuration file */\nvoid ReadNotificationOpacityConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL opacityFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n int opacity = atoi(line + 25);\n // Ensure opacity is within valid range (1-100)\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n opacityFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!opacityFound) {\n NOTIFICATION_MAX_OPACITY = 95; // Ensure there's a default value\n }\n}\n\n/** @brief Write maximum notification opacity configuration */\nvoid WriteConfigNotificationOpacity(int opacity) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_MAX_OPACITY = opacity;\n}\n\n/** @brief Read notification type setting from configuration file */\nvoid ReadNotificationTypeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *file = fopen(config_path, \"r\");\n if (file) {\n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n char typeStr[32] = {0};\n sscanf(line + 18, \"%31s\", typeStr);\n \n // Set notification type based on the string\n if (strcmp(typeStr, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(typeStr, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(typeStr, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n // Use default value for invalid type\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n }\n break;\n }\n }\n fclose(file);\n }\n}\n\n/** @brief Write notification type configuration */\nvoid WriteConfigNotificationType(NotificationType type) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure type value is within valid range\n if (type < NOTIFICATION_TYPE_CATIME || type > NOTIFICATION_TYPE_OS) {\n type = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Update global variable\n NOTIFICATION_TYPE = type;\n \n // Convert enum to string\n const char* typeStr;\n switch (type) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Create temporary file path\n char temp_path[MAX_PATH];\n strncpy(temp_path, config_path, MAX_PATH - 5);\n strcat(temp_path, \".tmp\");\n \n FILE *source = fopen(config_path, \"r\");\n FILE *target = fopen(temp_path, \"w\");\n \n if (source && target) {\n char line[256];\n BOOL found = FALSE;\n \n // Copy file content, replace target configuration line\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n found = TRUE;\n } else {\n fputs(line, target);\n }\n }\n \n // If configuration item not found, add it to the end of file\n if (!found) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n }\n \n fclose(source);\n fclose(target);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n } else {\n // Clean up potentially open files\n if (source) fclose(source);\n if (target) fclose(target);\n }\n}\n\n/** @brief Get audio folder path */\nvoid GetAudioFolderPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) >= size) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Read notification audio settings from configuration file */\nvoid ReadNotificationSoundConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[1024];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n char* value = line + 23; // Correct offset, skip \"NOTIFICATION_SOUND_FILE=\"\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Ensure path doesn't contain equals sign\n if (value[0] == '=') {\n value++; // If first character is equals sign, skip it\n }\n \n // Copy to global variable, ensure cleared\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, value, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio configuration */\nvoid WriteConfigNotificationSound(const char* sound_file) {\n if (!sound_file) return;\n \n // Check if the path contains equals sign, remove if present\n char clean_path[MAX_PATH] = {0};\n const char* src = sound_file;\n char* dst = clean_path;\n \n while (*src && (dst - clean_path) < (MAX_PATH - 1)) {\n if (*src != '=') {\n *dst++ = *src;\n }\n src++;\n }\n *dst = '\\0';\n \n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Create temporary file path\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE* source = fopen(config_path, \"r\");\n if (!source) return;\n \n FILE* dest = fopen(temp_path, \"w\");\n if (!dest) {\n fclose(source);\n return;\n }\n \n char line[1024];\n int found = 0;\n \n // Copy file content, replace or add notification audio settings\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n found = 1;\n } else {\n fputs(line, dest);\n }\n }\n \n // If configuration item not found, add to end of file\n if (!found) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n }\n \n fclose(source);\n fclose(dest);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, clean_path, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n}\n\n/** @brief Read notification audio volume from configuration file */\nvoid ReadNotificationVolumeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n int volume = atoi(line + 26);\n if (volume >= 0 && volume <= 100) {\n NOTIFICATION_SOUND_VOLUME = volume;\n }\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio volume configuration */\nvoid WriteConfigNotificationVolume(int volume) {\n // Validate volume range\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n \n // Update global variable\n NOTIFICATION_SOUND_VOLUME = volume;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Read hotkey settings from configuration file */\nvoid ReadConfigHotkeys(WORD* showTimeHotkey, WORD* countUpHotkey, WORD* countdownHotkey,\n WORD* quickCountdown1Hotkey, WORD* quickCountdown2Hotkey, WORD* quickCountdown3Hotkey,\n WORD* pomodoroHotkey, WORD* toggleVisibilityHotkey, WORD* editModeHotkey,\n WORD* pauseResumeHotkey, WORD* restartTimerHotkey)\n{\n // Parameter validation\n if (!showTimeHotkey || !countUpHotkey || !countdownHotkey || \n !quickCountdown1Hotkey || !quickCountdown2Hotkey || !quickCountdown3Hotkey ||\n !pomodoroHotkey || !toggleVisibilityHotkey || !editModeHotkey || \n !pauseResumeHotkey || !restartTimerHotkey) return;\n \n // Initialize to 0 (indicates no hotkey set)\n *showTimeHotkey = 0;\n *countUpHotkey = 0;\n *countdownHotkey = 0;\n *quickCountdown1Hotkey = 0;\n *quickCountdown2Hotkey = 0;\n *quickCountdown3Hotkey = 0;\n *pomodoroHotkey = 0;\n *toggleVisibilityHotkey = 0;\n *editModeHotkey = 0;\n *pauseResumeHotkey = 0;\n *restartTimerHotkey = 0;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *showTimeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countUpHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countdownHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown1Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown2Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown3Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pomodoroHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n char* value = line + 25;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *toggleVisibilityHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *editModeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n char* value = line + 20;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pauseResumeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n char* value = line + 21;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *restartTimerHotkey = StringToHotkey(value);\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write hotkey configuration */\nvoid WriteConfigHotkeys(WORD showTimeHotkey, WORD countUpHotkey, WORD countdownHotkey,\n WORD quickCountdown1Hotkey, WORD quickCountdown2Hotkey, WORD quickCountdown3Hotkey,\n WORD pomodoroHotkey, WORD toggleVisibilityHotkey, WORD editModeHotkey,\n WORD pauseResumeHotkey, WORD restartTimerHotkey) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) {\n // If file doesn't exist, create new file\n file = fopen(config_path, \"w\");\n if (!file) return;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0}; // Add custom countdown hotkey\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n // Get custom countdown hotkey value\n WORD customCountdownHotkey = 0;\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Write hotkey configuration\n fprintf(file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n fprintf(file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n fprintf(file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n fprintf(file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n fprintf(file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n fprintf(file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n fprintf(file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n fprintf(file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n fprintf(file, \"HOTKEY_CUSTOM_COUNTDOWN=%s\\n\", customCountdownStr); // Add new hotkey\n \n fclose(file);\n return;\n }\n \n // File exists, read all lines and update hotkey settings\n char temp_path[MAX_PATH];\n sprintf(temp_path, \"%s.tmp\", config_path);\n FILE* temp_file = fopen(temp_path, \"w\");\n \n if (!temp_file) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL foundShowTime = FALSE;\n BOOL foundCountUp = FALSE;\n BOOL foundCountdown = FALSE;\n BOOL foundQuickCountdown1 = FALSE;\n BOOL foundQuickCountdown2 = FALSE;\n BOOL foundQuickCountdown3 = FALSE;\n BOOL foundPomodoro = FALSE;\n BOOL foundToggleVisibility = FALSE;\n BOOL foundEditMode = FALSE;\n BOOL foundPauseResume = FALSE;\n BOOL foundRestartTimer = FALSE;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n \n // Process each line\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n foundShowTime = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n foundCountUp = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n foundCountdown = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n foundQuickCountdown1 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n foundQuickCountdown2 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n foundQuickCountdown3 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n foundPomodoro = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n foundToggleVisibility = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n foundEditMode = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n foundPauseResume = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n foundRestartTimer = TRUE;\n }\n else {\n // Keep other lines\n fputs(line, temp_file);\n }\n }\n \n // Add hotkey configuration items not found\n if (!foundShowTime) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n }\n if (!foundCountUp) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n }\n if (!foundCountdown) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n }\n if (!foundQuickCountdown1) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n }\n if (!foundQuickCountdown2) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n }\n if (!foundQuickCountdown3) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n }\n if (!foundPomodoro) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n }\n if (!foundToggleVisibility) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n }\n if (!foundEditMode) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n }\n if (!foundPauseResume) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n }\n if (!foundRestartTimer) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n }\n \n fclose(file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Convert hotkey value to readable string */\nvoid HotkeyToString(WORD hotkey, char* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) return;\n \n // 如果热键为0,表示未设置\n if (hotkey == 0) {\n strncpy(buffer, \"None\", bufferSize - 1);\n buffer[bufferSize - 1] = '\\0';\n return;\n }\n \n BYTE vk = LOBYTE(hotkey); // 虚拟键码\n BYTE mod = HIBYTE(hotkey); // 修饰键\n \n buffer[0] = '\\0';\n size_t len = 0;\n \n // 添加修饰键\n if (mod & HOTKEYF_CONTROL) {\n strncpy(buffer, \"Ctrl\", bufferSize - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_SHIFT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Shift\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_ALT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Alt\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n // 添加虚拟键\n if (len > 0 && len < bufferSize - 1 && vk != 0) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n \n // 获取虚拟键名称\n if (vk >= 'A' && vk <= 'Z') {\n // 字母键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= '0' && vk <= '9') {\n // 数字键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= VK_F1 && vk <= VK_F24) {\n // 功能键\n char keyName[4];\n sprintf(keyName, \"F%d\", vk - VK_F1 + 1);\n strncat(buffer, keyName, bufferSize - len - 1);\n } else {\n // 其他特殊键\n switch (vk) {\n case VK_BACK: strncat(buffer, \"Backspace\", bufferSize - len - 1); break;\n case VK_TAB: strncat(buffer, \"Tab\", bufferSize - len - 1); break;\n case VK_RETURN: strncat(buffer, \"Enter\", bufferSize - len - 1); break;\n case VK_ESCAPE: strncat(buffer, \"Esc\", bufferSize - len - 1); break;\n case VK_SPACE: strncat(buffer, \"Space\", bufferSize - len - 1); break;\n case VK_PRIOR: strncat(buffer, \"PageUp\", bufferSize - len - 1); break;\n case VK_NEXT: strncat(buffer, \"PageDown\", bufferSize - len - 1); break;\n case VK_END: strncat(buffer, \"End\", bufferSize - len - 1); break;\n case VK_HOME: strncat(buffer, \"Home\", bufferSize - len - 1); break;\n case VK_LEFT: strncat(buffer, \"Left\", bufferSize - len - 1); break;\n case VK_UP: strncat(buffer, \"Up\", bufferSize - len - 1); break;\n case VK_RIGHT: strncat(buffer, \"Right\", bufferSize - len - 1); break;\n case VK_DOWN: strncat(buffer, \"Down\", bufferSize - len - 1); break;\n case VK_INSERT: strncat(buffer, \"Insert\", bufferSize - len - 1); break;\n case VK_DELETE: strncat(buffer, \"Delete\", bufferSize - len - 1); break;\n case VK_NUMPAD0: strncat(buffer, \"Num0\", bufferSize - len - 1); break;\n case VK_NUMPAD1: strncat(buffer, \"Num1\", bufferSize - len - 1); break;\n case VK_NUMPAD2: strncat(buffer, \"Num2\", bufferSize - len - 1); break;\n case VK_NUMPAD3: strncat(buffer, \"Num3\", bufferSize - len - 1); break;\n case VK_NUMPAD4: strncat(buffer, \"Num4\", bufferSize - len - 1); break;\n case VK_NUMPAD5: strncat(buffer, \"Num5\", bufferSize - len - 1); break;\n case VK_NUMPAD6: strncat(buffer, \"Num6\", bufferSize - len - 1); break;\n case VK_NUMPAD7: strncat(buffer, \"Num7\", bufferSize - len - 1); break;\n case VK_NUMPAD8: strncat(buffer, \"Num8\", bufferSize - len - 1); break;\n case VK_NUMPAD9: strncat(buffer, \"Num9\", bufferSize - len - 1); break;\n case VK_MULTIPLY: strncat(buffer, \"Num*\", bufferSize - len - 1); break;\n case VK_ADD: strncat(buffer, \"Num+\", bufferSize - len - 1); break;\n case VK_SUBTRACT: strncat(buffer, \"Num-\", bufferSize - len - 1); break;\n case VK_DECIMAL: strncat(buffer, \"Num.\", bufferSize - len - 1); break;\n case VK_DIVIDE: strncat(buffer, \"Num/\", bufferSize - len - 1); break;\n case VK_OEM_1: strncat(buffer, \";\", bufferSize - len - 1); break;\n case VK_OEM_PLUS: strncat(buffer, \"=\", bufferSize - len - 1); break;\n case VK_OEM_COMMA: strncat(buffer, \",\", bufferSize - len - 1); break;\n case VK_OEM_MINUS: strncat(buffer, \"-\", bufferSize - len - 1); break;\n case VK_OEM_PERIOD: strncat(buffer, \".\", bufferSize - len - 1); break;\n case VK_OEM_2: strncat(buffer, \"/\", bufferSize - len - 1); break;\n case VK_OEM_3: strncat(buffer, \"`\", bufferSize - len - 1); break;\n case VK_OEM_4: strncat(buffer, \"[\", bufferSize - len - 1); break;\n case VK_OEM_5: strncat(buffer, \"\\\\\", bufferSize - len - 1); break;\n case VK_OEM_6: strncat(buffer, \"]\", bufferSize - len - 1); break;\n case VK_OEM_7: strncat(buffer, \"'\", bufferSize - len - 1); break;\n default: \n // 对于其他未知键,使用十六进制表示\n {\n char keyName[8];\n sprintf(keyName, \"0x%02X\", vk);\n strncat(buffer, keyName, bufferSize - len - 1);\n }\n break;\n }\n }\n}\n\n/** @brief Convert string to hotkey value */\nWORD StringToHotkey(const char* str) {\n if (!str || str[0] == '\\0' || strcmp(str, \"None\") == 0) {\n return 0; // 未设置热键\n }\n \n // 尝试直接解析为数字(兼容旧格式)\n if (isdigit(str[0])) {\n return (WORD)atoi(str);\n }\n \n BYTE vk = 0; // 虚拟键码\n BYTE mod = 0; // 修饰键\n \n // 复制字符串以便使用strtok\n char buffer[256];\n strncpy(buffer, str, sizeof(buffer) - 1);\n buffer[sizeof(buffer) - 1] = '\\0';\n \n // 分割字符串,查找修饰键和主键\n char* token = strtok(buffer, \"+\");\n char* lastToken = NULL;\n \n while (token) {\n if (stricmp(token, \"Ctrl\") == 0) {\n mod |= HOTKEYF_CONTROL;\n } else if (stricmp(token, \"Shift\") == 0) {\n mod |= HOTKEYF_SHIFT;\n } else if (stricmp(token, \"Alt\") == 0) {\n mod |= HOTKEYF_ALT;\n } else {\n // 可能是主键\n lastToken = token;\n }\n token = strtok(NULL, \"+\");\n }\n \n // 解析主键\n if (lastToken) {\n // 检查是否是单个字符的字母或数字\n if (strlen(lastToken) == 1) {\n char ch = toupper(lastToken[0]);\n if ((ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) {\n vk = ch;\n }\n } \n // 检查是否是功能键\n else if (lastToken[0] == 'F' && isdigit(lastToken[1])) {\n int fNum = atoi(lastToken + 1);\n if (fNum >= 1 && fNum <= 24) {\n vk = VK_F1 + fNum - 1;\n }\n }\n // 检查特殊键名\n else if (stricmp(lastToken, \"Backspace\") == 0) vk = VK_BACK;\n else if (stricmp(lastToken, \"Tab\") == 0) vk = VK_TAB;\n else if (stricmp(lastToken, \"Enter\") == 0) vk = VK_RETURN;\n else if (stricmp(lastToken, \"Esc\") == 0) vk = VK_ESCAPE;\n else if (stricmp(lastToken, \"Space\") == 0) vk = VK_SPACE;\n else if (stricmp(lastToken, \"PageUp\") == 0) vk = VK_PRIOR;\n else if (stricmp(lastToken, \"PageDown\") == 0) vk = VK_NEXT;\n else if (stricmp(lastToken, \"End\") == 0) vk = VK_END;\n else if (stricmp(lastToken, \"Home\") == 0) vk = VK_HOME;\n else if (stricmp(lastToken, \"Left\") == 0) vk = VK_LEFT;\n else if (stricmp(lastToken, \"Up\") == 0) vk = VK_UP;\n else if (stricmp(lastToken, \"Right\") == 0) vk = VK_RIGHT;\n else if (stricmp(lastToken, \"Down\") == 0) vk = VK_DOWN;\n else if (stricmp(lastToken, \"Insert\") == 0) vk = VK_INSERT;\n else if (stricmp(lastToken, \"Delete\") == 0) vk = VK_DELETE;\n else if (stricmp(lastToken, \"Num0\") == 0) vk = VK_NUMPAD0;\n else if (stricmp(lastToken, \"Num1\") == 0) vk = VK_NUMPAD1;\n else if (stricmp(lastToken, \"Num2\") == 0) vk = VK_NUMPAD2;\n else if (stricmp(lastToken, \"Num3\") == 0) vk = VK_NUMPAD3;\n else if (stricmp(lastToken, \"Num4\") == 0) vk = VK_NUMPAD4;\n else if (stricmp(lastToken, \"Num5\") == 0) vk = VK_NUMPAD5;\n else if (stricmp(lastToken, \"Num6\") == 0) vk = VK_NUMPAD6;\n else if (stricmp(lastToken, \"Num7\") == 0) vk = VK_NUMPAD7;\n else if (stricmp(lastToken, \"Num8\") == 0) vk = VK_NUMPAD8;\n else if (stricmp(lastToken, \"Num9\") == 0) vk = VK_NUMPAD9;\n else if (stricmp(lastToken, \"Num*\") == 0) vk = VK_MULTIPLY;\n else if (stricmp(lastToken, \"Num+\") == 0) vk = VK_ADD;\n else if (stricmp(lastToken, \"Num-\") == 0) vk = VK_SUBTRACT;\n else if (stricmp(lastToken, \"Num.\") == 0) vk = VK_DECIMAL;\n else if (stricmp(lastToken, \"Num/\") == 0) vk = VK_DIVIDE;\n // 检查十六进制格式\n else if (strncmp(lastToken, \"0x\", 2) == 0) {\n vk = (BYTE)strtol(lastToken, NULL, 16);\n }\n }\n \n return MAKEWORD(vk, mod);\n}\n\n/**\n * @brief Read custom countdown hotkey setting from configuration file\n * @param hotkey Pointer to store the hotkey\n */\nvoid ReadCustomCountdownHotkey(WORD* hotkey) {\n if (!hotkey) return;\n \n *hotkey = 0; // 默认为0(未设置)\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_CUSTOM_COUNTDOWN=\", 24) == 0) {\n char* value = line + 24;\n // 去除末尾的换行符\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // 解析热键字符串\n *hotkey = StringToHotkey(value);\n break;\n }\n }\n \n fclose(file);\n}\n\n/**\n * @brief Write a single configuration item to the configuration file\n * @param key Configuration item key name\n * @param value Configuration item value\n * \n * Adds or updates a single configuration item in the configuration file, automatically selects section based on key name\n */\nvoid WriteConfigKeyValue(const char* key, const char* value) {\n if (!key || !value) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Determine which section to place in based on the key name\n const char* section;\n \n if (strcmp(key, \"CONFIG_VERSION\") == 0 ||\n strcmp(key, \"LANGUAGE\") == 0 ||\n strcmp(key, \"SHORTCUT_CHECK_DONE\") == 0) {\n section = INI_SECTION_GENERAL;\n }\n else if (strncmp(key, \"CLOCK_TEXT_COLOR\", 16) == 0 ||\n strncmp(key, \"FONT_FILE_NAME\", 14) == 0 ||\n strncmp(key, \"CLOCK_BASE_FONT_SIZE\", 20) == 0 ||\n strncmp(key, \"WINDOW_SCALE\", 12) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_X\", 18) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_Y\", 18) == 0 ||\n strncmp(key, \"WINDOW_TOPMOST\", 14) == 0) {\n section = INI_SECTION_DISPLAY;\n }\n else if (strncmp(key, \"CLOCK_DEFAULT_START_TIME\", 24) == 0 ||\n strncmp(key, \"CLOCK_USE_24HOUR\", 16) == 0 ||\n strncmp(key, \"CLOCK_SHOW_SECONDS\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIME_OPTIONS\", 18) == 0 ||\n strncmp(key, \"STARTUP_MODE\", 12) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_TEXT\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_ACTION\", 20) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_FILE\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_WEBSITE\", 21) == 0) {\n section = INI_SECTION_TIMER;\n }\n else if (strncmp(key, \"POMODORO_\", 9) == 0) {\n section = INI_SECTION_POMODORO;\n }\n else if (strncmp(key, \"NOTIFICATION_\", 13) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", 26) == 0) {\n section = INI_SECTION_NOTIFICATION;\n }\n else if (strncmp(key, \"HOTKEY_\", 7) == 0) {\n section = INI_SECTION_HOTKEYS;\n }\n else if (strncmp(key, \"CLOCK_RECENT_FILE\", 17) == 0) {\n section = INI_SECTION_RECENTFILES;\n }\n else if (strncmp(key, \"COLOR_OPTIONS\", 13) == 0) {\n section = INI_SECTION_COLORS;\n }\n else {\n // 其他设置放在OPTIONS节\n section = INI_SECTION_OPTIONS;\n }\n \n // 写入配置\n WriteIniString(section, key, value, config_path);\n}\n\n/** @brief Write current language setting to configuration file */\nvoid WriteConfigLanguage(int language) {\n const char* langName;\n \n // Convert language enum value to readable language name\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_ENGLISH:\n langName = \"English\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n default:\n langName = \"English\"; // Default to English\n break;\n }\n \n WriteConfigKeyValue(\"LANGUAGE\", langName);\n}\n\n/** @brief Determine if shortcut check has been performed */\nbool IsShortcutCheckDone(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n return ReadIniBool(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", FALSE, config_path);\n}\n\n/** @brief Set shortcut check status */\nvoid SetShortcutCheckDone(bool done) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // 使用INI写入方式设置状态\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", done ? \"TRUE\" : \"FALSE\", config_path);\n}\n\n/** @brief Read whether to disable notification setting from configuration file */\nvoid ReadNotificationDisabledConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n}\n\n/** @brief Write whether to disable notification configuration */\nvoid WriteConfigNotificationDisabled(BOOL disabled) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_DISABLED=\", 22) == 0) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If configuration item not found in the configuration, add it\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_DISABLED = disabled;\n}\n"], ["/Catime/src/tray_menu.c", "/**\n * @file tray_menu.c\n * @brief Implementation of system tray menu functionality\n * \n * This file implements the system tray menu functionality for the application, including:\n * - Right-click menu and its submenus\n * - Color selection menu\n * - Font settings menu\n * - Timeout action settings\n * - Pomodoro functionality\n * - Preset time management\n * - Multi-language interface support\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/timer.h\"\n#include \"../resource/resource.h\"\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_USE_24HOUR;\nextern BOOL CLOCK_SHOW_SECONDS;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_EDIT_MODE;\nextern char CLOCK_STARTUP_MODE[20];\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\nextern int time_options[];\nextern int time_options_count;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern char CLOCK_TIMEOUT_FILE_PATH[MAX_PATH];\nextern char CLOCK_TIMEOUT_TEXT[50];\nextern BOOL CLOCK_WINDOW_TOPMOST; ///< Whether the window is always on top\n\n// Add Pomodoro related variable declarations\nextern int POMODORO_WORK_TIME; ///< Work time (seconds)\nextern int POMODORO_SHORT_BREAK; ///< Short break time (seconds)\nextern int POMODORO_LONG_BREAK; ///< Long break time (seconds)\nextern int POMODORO_LOOP_COUNT; ///< Loop count\n\n// Pomodoro time array and count variables\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Add to external variable declaration section\nextern char CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH]; ///< URL for timeout open website\nextern int current_pomodoro_time_index; // Current Pomodoro time index\nextern POMODORO_PHASE current_pomodoro_phase; // Pomodoro phase\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t size);\nextern BOOL IsAutoStartEnabled(void);\nextern void WriteConfigStartupMode(const char* mode);\nextern void ClearColorOptions(void);\nextern void AddColorOption(const char* color);\n/// @}\n\n/**\n * @brief Read timeout action settings from configuration file\n * \n * Read the timeout action settings saved in the configuration file and update the global variable CLOCK_TIMEOUT_ACTION\n */\nvoid ReadTimeoutActionFromConfig() {\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"TIMEOUT_ACTION=\", 15) == 0) {\n int action = 0;\n sscanf(line, \"TIMEOUT_ACTION=%d\", &action);\n CLOCK_TIMEOUT_ACTION = (TimeoutActionType)action;\n break;\n }\n }\n fclose(configFile);\n }\n}\n\n/**\n * @brief Recent file structure\n * \n * Store information about recently used files, including full path and display name\n */\ntypedef struct {\n char path[MAX_PATH]; ///< Full file path\n char name[MAX_PATH]; ///< File display name (may be truncated)\n} RecentFile;\n\nextern RecentFile CLOCK_RECENT_FILES[];\nextern int CLOCK_RECENT_FILES_COUNT;\n\n/**\n * @brief Format Pomodoro time to wide string\n * @param seconds Number of seconds\n * @param buffer Output buffer\n * @param bufferSize Buffer size\n */\nstatic void FormatPomodoroTime(int seconds, wchar_t* buffer, size_t bufferSize) {\n int minutes = seconds / 60;\n int secs = seconds % 60;\n int hours = minutes / 60;\n minutes %= 60;\n \n if (hours > 0) {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d:%02d\", hours, minutes, secs);\n } else {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d\", minutes, secs);\n }\n}\n\n/**\n * @brief Truncate long file names\n * \n * @param fileName Original file name\n * @param truncated Truncated file name buffer\n * @param maxLen Maximum display length (excluding terminator)\n * \n * If the file name exceeds the specified length, it uses the format \"first 12 characters...last 12 characters.extension\" for intelligent truncation.\n * This function preserves the file extension to ensure users can identify the file type.\n */\nvoid TruncateFileName(const wchar_t* fileName, wchar_t* truncated, size_t maxLen) {\n if (!fileName || !truncated || maxLen <= 7) return; // At least need to display \"x...y\"\n \n size_t nameLen = wcslen(fileName);\n if (nameLen <= maxLen) {\n // File name does not exceed the length limit, copy directly\n wcscpy(truncated, fileName);\n return;\n }\n \n // Find the position of the last dot (extension separator)\n const wchar_t* lastDot = wcsrchr(fileName, L'.');\n const wchar_t* fileNameNoExt = fileName;\n const wchar_t* ext = L\"\";\n size_t nameNoExtLen = nameLen;\n size_t extLen = 0;\n \n if (lastDot && lastDot != fileName) {\n // Has valid extension\n ext = lastDot; // Extension including dot\n extLen = wcslen(ext);\n nameNoExtLen = lastDot - fileName; // Length of file name without extension\n }\n \n // If the pure file name length is less than or equal to 27 characters (12+3+12), use the old truncation method\n if (nameNoExtLen <= 27) {\n // Simple truncation of main file name, preserving extension\n wcsncpy(truncated, fileName, maxLen - extLen - 3);\n truncated[maxLen - extLen - 3] = L'\\0';\n wcscat(truncated, L\"...\");\n wcscat(truncated, ext);\n return;\n }\n \n // Use new truncation method: first 12 characters + ... + last 12 characters + extension\n wchar_t buffer[MAX_PATH];\n \n // Copy first 12 characters\n wcsncpy(buffer, fileName, 12);\n buffer[12] = L'\\0';\n \n // Add ellipsis\n wcscat(buffer, L\"...\");\n \n // Copy last 12 characters (excluding extension part)\n wcsncat(buffer, fileName + nameNoExtLen - 12, 12);\n \n // Add extension\n wcscat(buffer, ext);\n \n // Copy result to output buffer\n wcscpy(truncated, buffer);\n}\n\n/**\n * @brief Display color and settings menu\n * \n * @param hwnd Window handle\n * \n * Create and display the application's main settings menu, including:\n * - Edit mode toggle\n * - Timeout action settings\n * - Preset time management\n * - Startup mode settings\n * - Font selection\n * - Color settings\n * - Language selection\n * - Help and about information\n */\nvoid ShowColorMenu(HWND hwnd) {\n // Read timeout action settings from the configuration file before creating the menu\n ReadTimeoutActionFromConfig();\n \n // Set mouse cursor to default arrow to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n HMENU hMenu = CreatePopupMenu();\n \n // Add edit mode option\n AppendMenuW(hMenu, MF_STRING | (CLOCK_EDIT_MODE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_EDIT_MODE, \n GetLocalizedString(L\"编辑模式\", L\"Edit Mode\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Timeout action menu\n HMENU hTimeoutMenu = CreatePopupMenu();\n \n // 1. Show message\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_SHOW_MESSAGE, \n GetLocalizedString(L\"显示消息\", L\"Show Message\"));\n\n // 2. Show current time\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHOW_TIME ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_SHOW_TIME, \n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n\n // 3. Count up\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_COUNT_UP ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_COUNT_UP, \n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n\n // 4. Lock screen\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_LOCK ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LOCK_SCREEN,\n GetLocalizedString(L\"锁定屏幕\", L\"Lock Screen\"));\n\n // First separator\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // 5. Open file (submenu)\n HMENU hFileMenu = CreatePopupMenu();\n\n // First add recent files list\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n wchar_t wFileName[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[i].name, -1, wFileName, MAX_PATH);\n \n // Truncate long file names\n wchar_t truncatedName[MAX_PATH];\n TruncateFileName(wFileName, truncatedName, 25); // Limit to 25 characters\n \n // Check if this is the currently selected file and the current timeout action is \"open file\"\n BOOL isCurrentFile = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE && \n strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n strcmp(CLOCK_RECENT_FILES[i].path, CLOCK_TIMEOUT_FILE_PATH) == 0);\n \n // Use menu item check state to indicate selection\n AppendMenuW(hFileMenu, MF_STRING | (isCurrentFile ? MF_CHECKED : 0), \n CLOCK_IDM_RECENT_FILE_1 + i, truncatedName);\n }\n \n // Add separator if there are recent files\n if (CLOCK_RECENT_FILES_COUNT > 0) {\n AppendMenuW(hFileMenu, MF_SEPARATOR, 0, NULL);\n }\n\n // Finally add \"Browse...\" option\n AppendMenuW(hFileMenu, MF_STRING, CLOCK_IDM_BROWSE_FILE,\n GetLocalizedString(L\"浏览...\", L\"Browse...\"));\n\n // Add \"Open File\" as a submenu to the timeout action menu\n AppendMenuW(hTimeoutMenu, MF_POPUP | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE ? MF_CHECKED : MF_UNCHECKED), \n (UINT_PTR)hFileMenu, \n GetLocalizedString(L\"打开文件/软件\", L\"Open File/Software\"));\n\n // 6. Open website\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_WEBSITE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_OPEN_WEBSITE,\n GetLocalizedString(L\"打开网站\", L\"Open Website\"));\n\n // Second separator\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // Add a non-selectable hint option\n AppendMenuW(hTimeoutMenu, MF_STRING | MF_GRAYED | MF_DISABLED, \n 0, // Use ID 0 to indicate non-selectable menu item\n GetLocalizedString(L\"以下超时动作为一次性\", L\"Following actions are one-time only\"));\n\n // 7. Shutdown\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHUTDOWN,\n GetLocalizedString(L\"关机\", L\"Shutdown\"));\n\n // 8. Restart\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RESTART,\n GetLocalizedString(L\"重启\", L\"Restart\"));\n\n // 9. Sleep\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SLEEP,\n GetLocalizedString(L\"睡眠\", L\"Sleep\"));\n\n // Third separator and Advanced menu\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // Create Advanced submenu\n HMENU hAdvancedMenu = CreatePopupMenu();\n\n // Add \"Run Command\" option\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RUN_COMMAND,\n GetLocalizedString(L\"运行命令\", L\"Run Command\"));\n\n // Add \"HTTP Request\" option\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_HTTP_REQUEST,\n GetLocalizedString(L\"HTTP 请求\", L\"HTTP Request\"));\n\n // Check if any advanced option is selected to determine if the Advanced submenu should be checked\n BOOL isAdvancedOptionSelected = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ||\n CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST);\n\n // Add Advanced submenu to timeout menu - mark as checked if any advanced option is selected\n AppendMenuW(hTimeoutMenu, MF_POPUP | (isAdvancedOptionSelected ? MF_CHECKED : MF_UNCHECKED),\n (UINT_PTR)hAdvancedMenu,\n GetLocalizedString(L\"高级\", L\"Advanced\"));\n\n // Add timeout action menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeoutMenu, \n GetLocalizedString(L\"超时动作\", L\"Timeout Action\"));\n\n // Preset management menu\n HMENU hTimeOptionsMenu = CreatePopupMenu();\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDC_MODIFY_TIME_OPTIONS,\n GetLocalizedString(L\"倒计时预设\", L\"Modify Quick Countdown Options\"));\n \n // Startup settings submenu\n HMENU hStartupSettingsMenu = CreatePopupMenu();\n\n // Read current startup mode\n char currentStartupMode[20] = \"COUNTDOWN\";\n char configPath[MAX_PATH]; \n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\"); \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(configFile);\n }\n \n // Add startup mode options\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNTDOWN\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_SET_COUNTDOWN_TIME,\n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNT_UP\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_COUNT_UP,\n GetLocalizedString(L\"正计时\", L\"Stopwatch\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"SHOW_TIME\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_SHOW_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"NO_DISPLAY\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_NO_DISPLAY,\n GetLocalizedString(L\"不显示\", L\"No Display\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_SEPARATOR, 0, NULL);\n\n // Add auto-start option\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (IsAutoStartEnabled() ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_AUTO_START,\n GetLocalizedString(L\"开机自启动\", L\"Start with Windows\"));\n\n // Add startup settings menu to preset management menu\n AppendMenuW(hTimeOptionsMenu, MF_POPUP, (UINT_PTR)hStartupSettingsMenu,\n GetLocalizedString(L\"启动设置\", L\"Startup Settings\"));\n\n // Add notification settings menu - changed to direct menu item, no longer using submenu\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDM_NOTIFICATION_SETTINGS,\n GetLocalizedString(L\"通知设置\", L\"Notification Settings\"));\n\n // Add preset management menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeOptionsMenu,\n GetLocalizedString(L\"预设管理\", L\"Preset Management\"));\n \n AppendMenuW(hTimeOptionsMenu, MF_STRING | (CLOCK_WINDOW_TOPMOST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TOPMOST,\n GetLocalizedString(L\"置顶\", L\"Always on Top\"));\n\n // Add \"Hotkey Settings\" option after preset management menu\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_HOTKEY_SETTINGS,\n GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Font menu\n HMENU hMoreFontsMenu = CreatePopupMenu();\n HMENU hFontSubMenu = CreatePopupMenu();\n \n // First add commonly used fonts to the main menu\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n // These fonts are kept in the main menu\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n \n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayName[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayName, 100);\n wchar_t* dot = wcsstr(wDisplayName, L\".ttf\");\n if (dot) *dot = L'\\0';\n \n AppendMenuW(hFontSubMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayName);\n }\n }\n\n AppendMenuW(hFontSubMenu, MF_SEPARATOR, 0, NULL);\n\n // Add other fonts to the \"More\" submenu\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n // Exclude fonts already added to the main menu\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n continue;\n }\n\n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayNameMore[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayNameMore, 100);\n wchar_t* dot = wcsstr(wDisplayNameMore, L\".ttf\");\n if (dot) *dot = L'\\0';\n \n AppendMenuW(hMoreFontsMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayNameMore);\n }\n\n // Add \"More\" submenu to main font menu\n AppendMenuW(hFontSubMenu, MF_POPUP, (UINT_PTR)hMoreFontsMenu, GetLocalizedString(L\"更多\", L\"More\"));\n\n // Color menu\n HMENU hColorSubMenu = CreatePopupMenu();\n // Preset color option menu IDs start from 201 to 201+COLOR_OPTIONS_COUNT-1\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n \n MENUITEMINFO mii = { sizeof(MENUITEMINFO) };\n mii.fMask = MIIM_STRING | MIIM_ID | MIIM_STATE | MIIM_FTYPE;\n mii.fType = MFT_STRING | MFT_OWNERDRAW;\n mii.fState = strcmp(CLOCK_TEXT_COLOR, hexColor) == 0 ? MFS_CHECKED : MFS_UNCHECKED;\n mii.wID = 201 + i; // Preset color menu item IDs start from 201\n mii.dwTypeData = (LPSTR)hexColor;\n \n InsertMenuItem(hColorSubMenu, i, TRUE, &mii);\n }\n AppendMenuW(hColorSubMenu, MF_SEPARATOR, 0, NULL);\n\n // Custom color options\n HMENU hCustomizeMenu = CreatePopupMenu();\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_VALUE, \n GetLocalizedString(L\"颜色值\", L\"Color Value\"));\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_PANEL, \n GetLocalizedString(L\"颜色面板\", L\"Color Panel\"));\n\n AppendMenuW(hColorSubMenu, MF_POPUP, (UINT_PTR)hCustomizeMenu, \n GetLocalizedString(L\"自定义\", L\"Customize\"));\n\n // Add font and color menus to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hFontSubMenu, \n GetLocalizedString(L\"字体\", L\"Font\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hColorSubMenu, \n GetLocalizedString(L\"颜色\", L\"Color\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // About menu\n HMENU hAboutMenu = CreatePopupMenu();\n\n // Add \"About\" menu item here\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_ABOUT, GetLocalizedString(L\"关于\", L\"About\"));\n\n // Add separator\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n\n // Add \"Support\" option - open sponsorship page\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n \n // Add \"Feedback\" option - open different feedback links based on language\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_FEEDBACK, GetLocalizedString(L\"反馈\", L\"Feedback\"));\n \n // Add separator\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n \n // Add \"Help\" option - open user guide webpage\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_HELP, GetLocalizedString(L\"使用指南\", L\"User Guide\"));\n\n // Add \"Check for Updates\" option\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_CHECK_UPDATE, \n GetLocalizedString(L\"检查更新\", L\"Check for Updates\"));\n\n // Language selection menu\n HMENU hLangMenu = CreatePopupMenu();\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE, L\"简体中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE_TRAD, L\"繁體中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_ENGLISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_ENGLISH, L\"English\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_SPANISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_SPANISH, L\"Español\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_FRENCH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_FRENCH, L\"Français\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_GERMAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_GERMAN, L\"Deutsch\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_RUSSIAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_RUSSIAN, L\"Русский\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_PORTUGUESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_PORTUGUESE, L\"Português\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_JAPANESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_JAPANESE, L\"日本語\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_KOREAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_KOREAN, L\"한국어\");\n\n AppendMenuW(hAboutMenu, MF_POPUP, (UINT_PTR)hLangMenu, GetLocalizedString(L\"语言\", L\"Language\"));\n\n // Add reset option to the end of the help menu\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, 200,\n GetLocalizedString(L\"重置\", L\"Reset\"));\n\n // Add about menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hAboutMenu,\n GetLocalizedString(L\"帮助\", L\"Help\"));\n\n // Only keep exit option\n AppendMenuW(hMenu, MF_STRING, 109,\n GetLocalizedString(L\"退出\", L\"Exit\"));\n \n // Display menu\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); // This will allow the menu to close automatically when clicking outside\n DestroyMenu(hMenu);\n}\n\n/**\n * @brief Display tray right-click menu\n * \n * @param hwnd Window handle\n * \n * Create and display the system tray right-click menu, dynamically adjusting menu items based on current application state. Includes:\n * - Timer control (pause/resume, restart)\n * - Time display settings (24-hour format, show seconds)\n * - Pomodoro clock settings\n * - Count-up and countdown mode switching\n * - Quick time preset options\n */\nvoid ShowContextMenu(HWND hwnd) {\n // Read timeout action settings from configuration file before creating the menu\n ReadTimeoutActionFromConfig();\n \n // Set mouse cursor to default arrow to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n HMENU hMenu = CreatePopupMenu();\n \n // Timer management menu - added at the top\n HMENU hTimerManageMenu = CreatePopupMenu();\n \n // Set conditions for whether submenu items should be enabled\n // Timer options should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress\n // 3. If in countdown mode, the timer hasn't ended yet (countdown elapsed time is less than total time)\n BOOL timerRunning = (!CLOCK_SHOW_CURRENT_TIME && \n (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0 && countdown_elapsed_time < CLOCK_TOTAL_TIME)));\n \n // Pause/Resume text changes based on current state\n const wchar_t* pauseResumeText = CLOCK_IS_PAUSED ? \n GetLocalizedString(L\"继续\", L\"Resume\") : \n GetLocalizedString(L\"暂停\", L\"Pause\");\n \n // Submenu items are disabled based on conditions, but parent menu item remains selectable\n AppendMenuW(hTimerManageMenu, MF_STRING | (timerRunning ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_PAUSE_RESUME, pauseResumeText);\n \n // Restart option should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress (regardless of whether countdown has ended)\n BOOL canRestart = (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0)));\n \n AppendMenuW(hTimerManageMenu, MF_STRING | (canRestart ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_RESTART, \n GetLocalizedString(L\"重新开始\", L\"Start Over\"));\n \n // Add timer management menu to main menu - parent menu item is always enabled\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimerManageMenu,\n GetLocalizedString(L\"计时管理\", L\"Timer Control\"));\n \n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n \n // Time display menu\n HMENU hTimeMenu = CreatePopupMenu();\n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_CURRENT_TIME ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_CURRENT_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_USE_24HOUR ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_24HOUR_FORMAT,\n GetLocalizedString(L\"24小时制\", L\"24-Hour Format\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_SECONDS ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_SECONDS,\n GetLocalizedString(L\"显示秒数\", L\"Show Seconds\"));\n \n AppendMenuW(hMenu, MF_POPUP,\n (UINT_PTR)hTimeMenu,\n GetLocalizedString(L\"时间显示\", L\"Time Display\"));\n\n // Before Pomodoro menu, first read the latest configuration values\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\");\n POMODORO_TIMES_COUNT = 0; // Initialize to 0\n \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n char* options = line + 22;\n char* token;\n int index = 0;\n \n token = strtok(options, \",\");\n while (token && index < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[index++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Set the actual number of time options\n POMODORO_TIMES_COUNT = index;\n \n // Ensure at least one valid value\n if (index > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (index > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (index > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[2];\n }\n }\n else if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n sscanf(line, \"POMODORO_LOOP_COUNT=%d\", &POMODORO_LOOP_COUNT);\n // Ensure loop count is at least 1\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n }\n }\n fclose(configFile);\n }\n\n // Pomodoro menu\n HMENU hPomodoroMenu = CreatePopupMenu();\n \n // Add timeBuffer declaration\n wchar_t timeBuffer[64]; // For storing formatted time string\n \n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_START,\n GetLocalizedString(L\"开始\", L\"Start\"));\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Create menu items for each Pomodoro time\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n FormatPomodoroTime(POMODORO_TIMES[i], timeBuffer, sizeof(timeBuffer)/sizeof(wchar_t));\n \n // Support both old and new ID systems\n UINT menuId;\n if (i == 0) menuId = CLOCK_IDM_POMODORO_WORK;\n else if (i == 1) menuId = CLOCK_IDM_POMODORO_BREAK;\n else if (i == 2) menuId = CLOCK_IDM_POMODORO_LBREAK;\n else menuId = CLOCK_IDM_POMODORO_TIME_BASE + i;\n \n // Check if this is the active Pomodoro phase\n BOOL isCurrentPhase = (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n current_pomodoro_time_index == i &&\n !CLOCK_SHOW_CURRENT_TIME &&\n !CLOCK_COUNT_UP && // Add check for not being in count-up mode\n CLOCK_TOTAL_TIME == POMODORO_TIMES[i]);\n \n // Add check mark if it's the current phase\n AppendMenuW(hPomodoroMenu, MF_STRING | (isCurrentPhase ? MF_CHECKED : MF_UNCHECKED), \n menuId, timeBuffer);\n }\n\n // Add loop count option\n wchar_t menuText[64];\n _snwprintf(menuText, sizeof(menuText)/sizeof(wchar_t),\n GetLocalizedString(L\"循环次数: %d\", L\"Loop Count: %d\"),\n POMODORO_LOOP_COUNT);\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_LOOP_COUNT, menuText);\n\n\n // Add separator\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Add combination option\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_COMBINATION,\n GetLocalizedString(L\"组合\", L\"Combination\"));\n \n // Add Pomodoro menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hPomodoroMenu,\n GetLocalizedString(L\"番茄时钟\", L\"Pomodoro\"));\n\n // Count-up menu - changed to direct click to start\n AppendMenuW(hMenu, MF_STRING | (CLOCK_COUNT_UP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_COUNT_UP_START,\n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n\n // Add \"Set Countdown\" option below Count-up\n AppendMenuW(hMenu, MF_STRING, 101, \n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Add quick time options\n for (int i = 0; i < time_options_count; i++) {\n wchar_t menu_item[20];\n _snwprintf(menu_item, sizeof(menu_item)/sizeof(wchar_t), L\"%d\", time_options[i]);\n AppendMenuW(hMenu, MF_STRING, 102 + i, menu_item);\n }\n\n // Display menu\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); // This will allow the menu to close automatically when clicking outside\n DestroyMenu(hMenu);\n}"], ["/Catime/src/font.c", "/**\n * @file font.c\n * @brief Font management module implementation file\n * \n * This file implements the font management functionality of the application, including font loading, preview,\n * application and configuration file management. Supports loading multiple predefined fonts from resources.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/font.h\"\n#include \"../resource/resource.h\"\n\n/// @name Global font variables\n/// @{\nchar FONT_FILE_NAME[100] = \"Hack Nerd Font.ttf\"; ///< Currently used font file name\nchar FONT_INTERNAL_NAME[100]; ///< Font internal name (without extension)\nchar PREVIEW_FONT_NAME[100] = \"\"; ///< Preview font file name\nchar PREVIEW_INTERNAL_NAME[100] = \"\"; ///< Preview font internal name\nBOOL IS_PREVIEWING = FALSE; ///< Whether font preview is active\n/// @}\n\n/**\n * @brief Font resource array\n * \n * Stores information for all built-in font resources in the application\n */\nFontResource fontResources[] = {\n {CLOCK_IDC_FONT_RECMONO, IDR_FONT_RECMONO, \"RecMonoCasual Nerd Font Mono Essence.ttf\"},\n {CLOCK_IDC_FONT_DEPARTURE, IDR_FONT_DEPARTURE, \"DepartureMono Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_TERMINESS, IDR_FONT_TERMINESS, \"Terminess Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_ARBUTUS, IDR_FONT_ARBUTUS, \"Arbutus Essence.ttf\"},\n {CLOCK_IDC_FONT_BERKSHIRE, IDR_FONT_BERKSHIRE, \"Berkshire Swash Essence.ttf\"},\n {CLOCK_IDC_FONT_CAVEAT, IDR_FONT_CAVEAT, \"Caveat Brush Essence.ttf\"},\n {CLOCK_IDC_FONT_CREEPSTER, IDR_FONT_CREEPSTER, \"Creepster Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTGOTHIC, IDR_FONT_DOTGOTHIC, \"DotGothic16 Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTO, IDR_FONT_DOTO, \"Doto ExtraBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FOLDIT, IDR_FONT_FOLDIT, \"Foldit SemiBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FREDERICKA, IDR_FONT_FREDERICKA, \"Fredericka the Great Essence.ttf\"},\n {CLOCK_IDC_FONT_FRIJOLE, IDR_FONT_FRIJOLE, \"Frijole Essence.ttf\"},\n {CLOCK_IDC_FONT_GWENDOLYN, IDR_FONT_GWENDOLYN, \"Gwendolyn Essence.ttf\"},\n {CLOCK_IDC_FONT_HANDJET, IDR_FONT_HANDJET, \"Handjet Essence.ttf\"},\n {CLOCK_IDC_FONT_INKNUT, IDR_FONT_INKNUT, \"Inknut Antiqua Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARD, IDR_FONT_JACQUARD, \"Jacquard 12 Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARDA, IDR_FONT_JACQUARDA, \"Jacquarda Bastarda 9 Essence.ttf\"},\n {CLOCK_IDC_FONT_KAVOON, IDR_FONT_KAVOON, \"Kavoon Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE, IDR_FONT_KUMAR_ONE_OUTLINE, \"Kumar One Outline Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE, IDR_FONT_KUMAR_ONE, \"Kumar One Essence.ttf\"},\n {CLOCK_IDC_FONT_LAKKI_REDDY, IDR_FONT_LAKKI_REDDY, \"Lakki Reddy Essence.ttf\"},\n {CLOCK_IDC_FONT_LICORICE, IDR_FONT_LICORICE, \"Licorice Essence.ttf\"},\n {CLOCK_IDC_FONT_MA_SHAN_ZHENG, IDR_FONT_MA_SHAN_ZHENG, \"Ma Shan Zheng Essence.ttf\"},\n {CLOCK_IDC_FONT_MOIRAI_ONE, IDR_FONT_MOIRAI_ONE, \"Moirai One Essence.ttf\"},\n {CLOCK_IDC_FONT_MYSTERY_QUEST, IDR_FONT_MYSTERY_QUEST, \"Mystery Quest Essence.ttf\"},\n {CLOCK_IDC_FONT_NOTO_NASTALIQ, IDR_FONT_NOTO_NASTALIQ, \"Noto Nastaliq Urdu Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PIEDRA, IDR_FONT_PIEDRA, \"Piedra Essence.ttf\"},\n {CLOCK_IDC_FONT_PINYON_SCRIPT, IDR_FONT_PINYON_SCRIPT, \"Pinyon Script Essence.ttf\"},\n {CLOCK_IDC_FONT_PIXELIFY, IDR_FONT_PIXELIFY, \"Pixelify Sans Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PRESS_START, IDR_FONT_PRESS_START, \"Press Start 2P Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BUBBLES, IDR_FONT_RUBIK_BUBBLES, \"Rubik Bubbles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BURNED, IDR_FONT_RUBIK_BURNED, \"Rubik Burned Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_GLITCH, IDR_FONT_RUBIK_GLITCH, \"Rubik Glitch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_MARKER_HATCH, IDR_FONT_RUBIK_MARKER_HATCH, \"Rubik Marker Hatch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_PUDDLES, IDR_FONT_RUBIK_PUDDLES, \"Rubik Puddles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_VINYL, IDR_FONT_RUBIK_VINYL, \"Rubik Vinyl Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_WET_PAINT, IDR_FONT_RUBIK_WET_PAINT, \"Rubik Wet Paint Essence.ttf\"},\n {CLOCK_IDC_FONT_RUGE_BOOGIE, IDR_FONT_RUGE_BOOGIE, \"Ruge Boogie Essence.ttf\"},\n {CLOCK_IDC_FONT_SEVILLANA, IDR_FONT_SEVILLANA, \"Sevillana Essence.ttf\"},\n {CLOCK_IDC_FONT_SILKSCREEN, IDR_FONT_SILKSCREEN, \"Silkscreen Essence.ttf\"},\n {CLOCK_IDC_FONT_STICK, IDR_FONT_STICK, \"Stick Essence.ttf\"},\n {CLOCK_IDC_FONT_UNDERDOG, IDR_FONT_UNDERDOG, \"Underdog Essence.ttf\"},\n {CLOCK_IDC_FONT_WALLPOET, IDR_FONT_WALLPOET, \"Wallpoet Essence.ttf\"},\n {CLOCK_IDC_FONT_YESTERYEAR, IDR_FONT_YESTERYEAR, \"Yesteryear Essence.ttf\"},\n {CLOCK_IDC_FONT_ZCOOL_KUAILE, IDR_FONT_ZCOOL_KUAILE, \"ZCOOL KuaiLe Essence.ttf\"},\n {CLOCK_IDC_FONT_PROFONT, IDR_FONT_PROFONT, \"ProFont IIx Nerd Font Essence.ttf\"},\n {CLOCK_IDC_FONT_DADDYTIME, IDR_FONT_DADDYTIME, \"DaddyTimeMono Nerd Font Propo Essence.ttf\"},\n};\n\n/// Number of font resources\nconst int FONT_RESOURCES_COUNT = sizeof(fontResources) / sizeof(FontResource);\n\n/// @name External variable declarations\n/// @{\nextern char CLOCK_TEXT_COLOR[]; ///< Current clock text color\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t maxLen); ///< Get configuration file path\nextern void ReadConfig(void); ///< Read configuration file\nextern int CALLBACK EnumFontFamExProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam); ///< Font enumeration callback function\n/// @}\n\nBOOL LoadFontFromResource(HINSTANCE hInstance, int resourceId) {\n // Find font resource\n HRSRC hResource = FindResource(hInstance, MAKEINTRESOURCE(resourceId), RT_FONT);\n if (hResource == NULL) {\n return FALSE;\n }\n\n // Load resource into memory\n HGLOBAL hMemory = LoadResource(hInstance, hResource);\n if (hMemory == NULL) {\n return FALSE;\n }\n\n // Lock resource\n void* fontData = LockResource(hMemory);\n if (fontData == NULL) {\n return FALSE;\n }\n\n // Get resource size and add font\n DWORD fontLength = SizeofResource(hInstance, hResource);\n DWORD nFonts = 0;\n HANDLE handle = AddFontMemResourceEx(fontData, fontLength, NULL, &nFonts);\n \n if (handle == NULL) {\n return FALSE;\n }\n \n return TRUE;\n}\n\nBOOL LoadFontByName(HINSTANCE hInstance, const char* fontName) {\n // Iterate through the font resource array to find a matching font\n for (int i = 0; i < sizeof(fontResources) / sizeof(FontResource); i++) {\n if (strcmp(fontResources[i].fontName, fontName) == 0) {\n return LoadFontFromResource(hInstance, fontResources[i].resourceId);\n }\n }\n return FALSE;\n}\n\nvoid WriteConfigFont(const char* font_file_name) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Open configuration file for reading\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n // Read the entire configuration file content\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n // Create new configuration file content\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n // Process line by line and replace font settings\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"FONT_FILE_NAME=\", 15) == 0) {\n strcat(new_config, \"FONT_FILE_NAME=\");\n strcat(new_config, font_file_name);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n // Write new configuration content\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n // Re-read configuration\n ReadConfig();\n}\n\nvoid ListAvailableFonts(void) {\n HDC hdc = GetDC(NULL);\n LOGFONT lf;\n memset(&lf, 0, sizeof(LOGFONT));\n lf.lfCharSet = DEFAULT_CHARSET;\n\n // Create temporary font and enumerate fonts\n HFONT hFont = CreateFont(12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n lf.lfCharSet, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, NULL);\n SelectObject(hdc, hFont);\n\n EnumFontFamiliesEx(hdc, &lf, (FONTENUMPROC)EnumFontFamExProc, 0, 0);\n\n // Clean up resources\n DeleteObject(hFont);\n ReleaseDC(NULL, hdc);\n}\n\nint CALLBACK EnumFontFamExProc(\n ENUMLOGFONTEX *lpelfe,\n NEWTEXTMETRICEX *lpntme,\n DWORD FontType,\n LPARAM lParam\n) {\n return 1;\n}\n\nBOOL PreviewFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Save current font name\n strncpy(PREVIEW_FONT_NAME, fontName, sizeof(PREVIEW_FONT_NAME) - 1);\n PREVIEW_FONT_NAME[sizeof(PREVIEW_FONT_NAME) - 1] = '\\0';\n \n // Get internal font name (remove .ttf extension)\n size_t name_len = strlen(PREVIEW_FONT_NAME);\n if (name_len > 4 && strcmp(PREVIEW_FONT_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(PREVIEW_INTERNAL_NAME))\n copy_len = sizeof(PREVIEW_INTERNAL_NAME) - 1;\n \n memcpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, copy_len);\n PREVIEW_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, sizeof(PREVIEW_INTERNAL_NAME) - 1);\n PREVIEW_INTERNAL_NAME[sizeof(PREVIEW_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Load preview font\n if (!LoadFontByName(hInstance, PREVIEW_FONT_NAME)) {\n return FALSE;\n }\n \n IS_PREVIEWING = TRUE;\n return TRUE;\n}\n\nvoid CancelFontPreview(void) {\n IS_PREVIEWING = FALSE;\n PREVIEW_FONT_NAME[0] = '\\0';\n PREVIEW_INTERNAL_NAME[0] = '\\0';\n}\n\nvoid ApplyFontPreview(void) {\n // Check if there is a valid preview font\n if (!IS_PREVIEWING || strlen(PREVIEW_FONT_NAME) == 0) return;\n \n // Update current font\n strncpy(FONT_FILE_NAME, PREVIEW_FONT_NAME, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n strncpy(FONT_INTERNAL_NAME, PREVIEW_INTERNAL_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n \n // Save to configuration file and cancel preview state\n WriteConfigFont(FONT_FILE_NAME);\n CancelFontPreview();\n}\n\nBOOL SwitchFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Load new font\n if (!LoadFontByName(hInstance, fontName)) {\n return FALSE;\n }\n \n // Update font name\n strncpy(FONT_FILE_NAME, fontName, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n // Update internal font name (remove .ttf extension)\n size_t name_len = strlen(FONT_FILE_NAME);\n if (name_len > 4 && strcmp(FONT_FILE_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Write to configuration file\n WriteConfigFont(FONT_FILE_NAME);\n return TRUE;\n}"], ["/Catime/src/hotkey.c", "/**\n * @file hotkey.c\n * @brief Hotkey management implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#if defined _M_IX86\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_IA64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_X64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#else\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#endif\n#include \"../include/hotkey.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../resource/resource.h\"\n\n#ifndef HOTKEYF_SHIFT\n#define HOTKEYF_SHIFT 0x01\n#define HOTKEYF_CONTROL 0x02\n#define HOTKEYF_ALT 0x04\n#endif\n\nstatic WORD g_dlgShowTimeHotkey = 0;\nstatic WORD g_dlgCountUpHotkey = 0;\nstatic WORD g_dlgCountdownHotkey = 0;\nstatic WORD g_dlgCustomCountdownHotkey = 0;\nstatic WORD g_dlgQuickCountdown1Hotkey = 0;\nstatic WORD g_dlgQuickCountdown2Hotkey = 0;\nstatic WORD g_dlgQuickCountdown3Hotkey = 0;\nstatic WORD g_dlgPomodoroHotkey = 0;\nstatic WORD g_dlgToggleVisibilityHotkey = 0;\nstatic WORD g_dlgEditModeHotkey = 0;\nstatic WORD g_dlgPauseResumeHotkey = 0;\nstatic WORD g_dlgRestartTimerHotkey = 0;\n\nstatic WNDPROC g_OldHotkeyDlgProc = NULL;\n\n/**\n * @brief Dialog subclassing procedure\n */\nLRESULT CALLBACK HotkeyDialogSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n if (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN || msg == WM_KEYUP || msg == WM_SYSKEYUP) {\n BYTE vk = (BYTE)wParam;\n if (!(vk == VK_SHIFT || vk == VK_CONTROL || vk == VK_MENU || vk == VK_LWIN || vk == VK_RWIN)) {\n BYTE currentModifiers = 0;\n if (GetKeyState(VK_SHIFT) & 0x8000) currentModifiers |= HOTKEYF_SHIFT;\n if (GetKeyState(VK_CONTROL) & 0x8000) currentModifiers |= HOTKEYF_CONTROL;\n if (msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP || (GetKeyState(VK_MENU) & 0x8000)) {\n currentModifiers |= HOTKEYF_ALT;\n }\n\n WORD currentEventKeyCombination = MAKEWORD(vk, currentModifiers);\n\n const WORD originalHotkeys[] = {\n g_dlgShowTimeHotkey, g_dlgCountUpHotkey, g_dlgCountdownHotkey,\n g_dlgQuickCountdown1Hotkey, g_dlgQuickCountdown2Hotkey, g_dlgQuickCountdown3Hotkey,\n g_dlgPomodoroHotkey, g_dlgToggleVisibilityHotkey, g_dlgEditModeHotkey,\n g_dlgPauseResumeHotkey, g_dlgRestartTimerHotkey\n };\n BOOL isAnOriginalHotkeyEvent = FALSE;\n for (size_t i = 0; i < sizeof(originalHotkeys) / sizeof(originalHotkeys[0]); ++i) {\n if (originalHotkeys[i] != 0 && originalHotkeys[i] == currentEventKeyCombination) {\n isAnOriginalHotkeyEvent = TRUE;\n break;\n }\n }\n\n if (isAnOriginalHotkeyEvent) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n }\n\n switch (msg) {\n case WM_SYSKEYDOWN:\n case WM_SYSKEYUP:\n {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (isHotkeyEditControl) {\n break;\n }\n }\n return 0;\n }\n\n case WM_KEYDOWN:\n case WM_KEYUP:\n {\n BYTE vk_code = (BYTE)wParam;\n if (vk_code == VK_SHIFT || vk_code == VK_CONTROL || vk_code == VK_LWIN || vk_code == VK_RWIN) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n break;\n\n case WM_SYSCOMMAND:\n if ((wParam & 0xFFF0) == SC_KEYMENU) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(g_OldHotkeyDlgProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Show hotkey settings dialog\n */\nvoid ShowHotkeySettingsDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_HOTKEY_DIALOG),\n hwndParent,\n HotkeySettingsDlgProc);\n}\n\n/**\n * @brief Check if a hotkey is a single key\n */\nBOOL IsSingleKey(WORD hotkey) {\n BYTE modifiers = HIBYTE(hotkey);\n\n return modifiers == 0;\n}\n\n/**\n * @brief Check if a hotkey is a standalone letter, number, or symbol\n */\nBOOL IsRestrictedSingleKey(WORD hotkey) {\n if (hotkey == 0) {\n return FALSE;\n }\n\n BYTE vk = LOBYTE(hotkey);\n BYTE modifiers = HIBYTE(hotkey);\n\n if (modifiers != 0) {\n return FALSE;\n }\n\n if (vk >= 'A' && vk <= 'Z') {\n return TRUE;\n }\n\n if (vk >= '0' && vk <= '9') {\n return TRUE;\n }\n\n if (vk >= VK_NUMPAD0 && vk <= VK_NUMPAD9) {\n return TRUE;\n }\n\n switch (vk) {\n case VK_OEM_1:\n case VK_OEM_PLUS:\n case VK_OEM_COMMA:\n case VK_OEM_MINUS:\n case VK_OEM_PERIOD:\n case VK_OEM_2:\n case VK_OEM_3:\n case VK_OEM_4:\n case VK_OEM_5:\n case VK_OEM_6:\n case VK_OEM_7:\n case VK_SPACE:\n case VK_RETURN:\n case VK_ESCAPE:\n case VK_TAB:\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey settings dialog message processing procedure\n */\nINT_PTR CALLBACK HotkeySettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL1,\n GetLocalizedString(L\"显示当前时间:\", L\"Show Current Time:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL2,\n GetLocalizedString(L\"正计时:\", L\"Count Up:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL12,\n GetLocalizedString(L\"倒计时:\", L\"Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL3,\n GetLocalizedString(L\"默认倒计时:\", L\"Default Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL9,\n GetLocalizedString(L\"快捷倒计时1:\", L\"Quick Countdown 1:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL10,\n GetLocalizedString(L\"快捷倒计时2:\", L\"Quick Countdown 2:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL11,\n GetLocalizedString(L\"快捷倒计时3:\", L\"Quick Countdown 3:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL4,\n GetLocalizedString(L\"开始番茄钟:\", L\"Start Pomodoro:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL5,\n GetLocalizedString(L\"隐藏/显示窗口:\", L\"Hide/Show Window:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL6,\n GetLocalizedString(L\"进入编辑模式:\", L\"Enter Edit Mode:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL7,\n GetLocalizedString(L\"暂停/继续计时:\", L\"Pause/Resume Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL8,\n GetLocalizedString(L\"重新开始计时:\", L\"Restart Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_NOTE,\n GetLocalizedString(L\"* 热键将全局生效\", L\"* Hotkeys will work globally\"));\n\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"确定\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"取消\", L\"Cancel\"));\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n ReadConfigHotkeys(&g_dlgShowTimeHotkey, &g_dlgCountUpHotkey, &g_dlgCountdownHotkey,\n &g_dlgQuickCountdown1Hotkey, &g_dlgQuickCountdown2Hotkey, &g_dlgQuickCountdown3Hotkey,\n &g_dlgPomodoroHotkey, &g_dlgToggleVisibilityHotkey, &g_dlgEditModeHotkey,\n &g_dlgPauseResumeHotkey, &g_dlgRestartTimerHotkey);\n\n ReadCustomCountdownHotkey(&g_dlgCustomCountdownHotkey);\n\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_SETHOTKEY, g_dlgShowTimeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_SETHOTKEY, g_dlgCountUpHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_SETHOTKEY, g_dlgCustomCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_SETHOTKEY, g_dlgCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_SETHOTKEY, g_dlgQuickCountdown1Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_SETHOTKEY, g_dlgQuickCountdown2Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_SETHOTKEY, g_dlgQuickCountdown3Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_SETHOTKEY, g_dlgPomodoroHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_SETHOTKEY, g_dlgToggleVisibilityHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_SETHOTKEY, g_dlgEditModeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_SETHOTKEY, g_dlgPauseResumeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_SETHOTKEY, g_dlgRestartTimerHotkey, 0);\n\n UnregisterGlobalHotkeys(GetParent(hwndDlg));\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n SetWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i, 0);\n }\n }\n\n g_OldHotkeyDlgProc = (WNDPROC)SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)HotkeyDialogSubclassProc);\n\n SetFocus(GetDlgItem(hwndDlg, IDCANCEL));\n\n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n \n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n \n case WM_LBUTTONDOWN: {\n POINT pt = {LOWORD(lParam), HIWORD(lParam)};\n HWND hwndHit = ChildWindowFromPoint(hwndDlg, pt);\n\n if (hwndHit != NULL && hwndHit != hwndDlg) {\n int ctrlId = GetDlgCtrlID(hwndHit);\n\n BOOL isHotkeyEdit = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) {\n isHotkeyEdit = TRUE;\n break;\n }\n }\n\n if (!isHotkeyEdit) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n }\n }\n else if (hwndHit == hwndDlg) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND: {\n WORD ctrlId = LOWORD(wParam);\n WORD notifyCode = HIWORD(wParam);\n\n if (notifyCode == EN_CHANGE &&\n (ctrlId == IDC_HOTKEY_EDIT1 || ctrlId == IDC_HOTKEY_EDIT2 ||\n ctrlId == IDC_HOTKEY_EDIT3 || ctrlId == IDC_HOTKEY_EDIT4 ||\n ctrlId == IDC_HOTKEY_EDIT5 || ctrlId == IDC_HOTKEY_EDIT6 ||\n ctrlId == IDC_HOTKEY_EDIT7 || ctrlId == IDC_HOTKEY_EDIT8 ||\n ctrlId == IDC_HOTKEY_EDIT9 || ctrlId == IDC_HOTKEY_EDIT10 ||\n ctrlId == IDC_HOTKEY_EDIT11 || ctrlId == IDC_HOTKEY_EDIT12)) {\n\n WORD newHotkey = (WORD)SendDlgItemMessage(hwndDlg, ctrlId, HKM_GETHOTKEY, 0, 0);\n\n BYTE vk = LOBYTE(newHotkey);\n BYTE modifiers = HIBYTE(newHotkey);\n\n if (vk == 0xE5 && modifiers == HOTKEYF_SHIFT) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0 && IsRestrictedSingleKey(newHotkey)) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0) {\n static const int hotkeyCtrlIds[] = {\n IDC_HOTKEY_EDIT1, IDC_HOTKEY_EDIT2, IDC_HOTKEY_EDIT3,\n IDC_HOTKEY_EDIT9, IDC_HOTKEY_EDIT10, IDC_HOTKEY_EDIT11,\n IDC_HOTKEY_EDIT4, IDC_HOTKEY_EDIT5, IDC_HOTKEY_EDIT6,\n IDC_HOTKEY_EDIT7, IDC_HOTKEY_EDIT8, IDC_HOTKEY_EDIT12\n };\n\n for (int i = 0; i < sizeof(hotkeyCtrlIds) / sizeof(hotkeyCtrlIds[0]); i++) {\n if (hotkeyCtrlIds[i] == ctrlId) {\n continue;\n }\n\n WORD otherHotkey = (WORD)SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_GETHOTKEY, 0, 0);\n\n if (otherHotkey != 0 && otherHotkey == newHotkey) {\n SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_SETHOTKEY, 0, 0);\n }\n }\n }\n\n return TRUE;\n }\n \n switch (LOWORD(wParam)) {\n case IDOK: {\n WORD showTimeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_GETHOTKEY, 0, 0);\n WORD countUpHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_GETHOTKEY, 0, 0);\n WORD customCountdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_GETHOTKEY, 0, 0);\n WORD countdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown1Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown2Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown3Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_GETHOTKEY, 0, 0);\n WORD pomodoroHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_GETHOTKEY, 0, 0);\n WORD toggleVisibilityHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_GETHOTKEY, 0, 0);\n WORD editModeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_GETHOTKEY, 0, 0);\n WORD pauseResumeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_GETHOTKEY, 0, 0);\n WORD restartTimerHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_GETHOTKEY, 0, 0);\n\n WORD* hotkeys[] = {\n &showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey, &customCountdownHotkey\n };\n\n for (int i = 0; i < sizeof(hotkeys) / sizeof(hotkeys[0]); i++) {\n if (LOBYTE(*hotkeys[i]) == 0xE5 && HIBYTE(*hotkeys[i]) == HOTKEYF_SHIFT) {\n *hotkeys[i] = 0;\n continue;\n }\n\n if (*hotkeys[i] != 0 && IsRestrictedSingleKey(*hotkeys[i])) {\n *hotkeys[i] = 0;\n }\n }\n\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n g_dlgCustomCountdownHotkey = customCountdownHotkey;\n char customCountdownStr[64] = {0};\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr);\n\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n\n case IDCANCEL:\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n \n case WM_DESTROY:\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n if (g_OldHotkeyDlgProc) {\n SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)g_OldHotkeyDlgProc);\n g_OldHotkeyDlgProc = NULL;\n }\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n RemoveWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i);\n }\n }\n break;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey control subclass procedure\n */\nLRESULT CALLBACK HotkeyControlSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam,\n LPARAM lParam, UINT_PTR uIdSubclass,\n DWORD_PTR dwRefData) {\n switch (uMsg) {\n case WM_GETDLGCODE:\n return DLGC_WANTALLKEYS | DLGC_WANTCHARS;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(hwndDlg, IDOK));\n return 0;\n }\n }\n break;\n }\n\n return DefSubclassProc(hwnd, uMsg, wParam, lParam);\n}"], ["/Catime/src/timer.c", "/**\n * @file timer.c\n * @brief Implementation of core timer functionality\n * \n * This file contains the implementation of the core timer logic, including time format conversion, \n * input parsing, configuration saving, and other functionalities,\n * while maintaining various timer states and configuration parameters.\n */\n\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n/** @name Timer status flags\n * @{ */\nBOOL CLOCK_IS_PAUSED = FALSE; ///< Timer pause status flag\nBOOL CLOCK_SHOW_CURRENT_TIME = FALSE; ///< Show current time mode flag\nBOOL CLOCK_USE_24HOUR = TRUE; ///< Use 24-hour format flag\nBOOL CLOCK_SHOW_SECONDS = TRUE; ///< Show seconds flag\nBOOL CLOCK_COUNT_UP = FALSE; ///< Countdown/count-up mode flag\nchar CLOCK_STARTUP_MODE[20] = \"COUNTDOWN\"; ///< Startup mode (countdown/count-up)\n/** @} */\n\n/** @name Timer time parameters \n * @{ */\nint CLOCK_TOTAL_TIME = 0; ///< Total timer time (seconds)\nint countdown_elapsed_time = 0; ///< Countdown elapsed time (seconds)\nint countup_elapsed_time = 0; ///< Count-up accumulated time (seconds)\ntime_t CLOCK_LAST_TIME_UPDATE = 0; ///< Last update timestamp\n\n// High-precision timer related variables\nLARGE_INTEGER timer_frequency; ///< High-precision timer frequency\nLARGE_INTEGER timer_last_count; ///< Last timing point\nBOOL high_precision_timer_initialized = FALSE; ///< High-precision timer initialization flag\n/** @} */\n\n/** @name Message status flags\n * @{ */\nBOOL countdown_message_shown = FALSE; ///< Countdown completion message display status\nBOOL countup_message_shown = FALSE; ///< Count-up completion message display status\nint pomodoro_work_cycles = 0; ///< Pomodoro work cycle count\n/** @} */\n\n/** @name Timeout action configuration\n * @{ */\nTimeoutActionType CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE; ///< Timeout action type\nchar CLOCK_TIMEOUT_TEXT[50] = \"\"; ///< Timeout display text\nchar CLOCK_TIMEOUT_FILE_PATH[MAX_PATH] = \"\"; ///< Timeout executable file path\n/** @} */\n\n/** @name Pomodoro time settings\n * @{ */\nint POMODORO_WORK_TIME = 25 * 60; ///< Pomodoro work time (25 minutes)\nint POMODORO_SHORT_BREAK = 5 * 60; ///< Pomodoro short break time (5 minutes)\nint POMODORO_LONG_BREAK = 15 * 60; ///< Pomodoro long break time (15 minutes)\nint POMODORO_LOOP_COUNT = 1; ///< Pomodoro loop count (default 1 time)\n/** @} */\n\n/** @name Preset time options\n * @{ */\nint time_options[MAX_TIME_OPTIONS]; ///< Preset time options array\nint time_options_count = 0; ///< Number of valid preset times\n/** @} */\n\n/** Last displayed time (seconds), used to prevent time display jumping phenomenon */\nint last_displayed_second = -1;\n\n/**\n * @brief Initialize high-precision timer\n * \n * Get system timer frequency and record initial timing point\n * @return BOOL Whether initialization was successful\n */\nBOOL InitializeHighPrecisionTimer(void) {\n if (!QueryPerformanceFrequency(&timer_frequency)) {\n return FALSE; // System does not support high-precision timer\n }\n \n if (!QueryPerformanceCounter(&timer_last_count)) {\n return FALSE; // Failed to get current count\n }\n \n high_precision_timer_initialized = TRUE;\n return TRUE;\n}\n\n/**\n * @brief Calculate milliseconds elapsed since last call\n * \n * Use high-precision timer to calculate exact time interval\n * @return double Elapsed milliseconds\n */\ndouble GetElapsedMilliseconds(void) {\n if (!high_precision_timer_initialized) {\n if (!InitializeHighPrecisionTimer()) {\n return 0.0; // Initialization failed, return 0\n }\n }\n \n LARGE_INTEGER current_count;\n if (!QueryPerformanceCounter(¤t_count)) {\n return 0.0; // Failed to get current count\n }\n \n // Calculate time difference (convert to milliseconds)\n double elapsed = (double)(current_count.QuadPart - timer_last_count.QuadPart) * 1000.0 / (double)timer_frequency.QuadPart;\n \n // Update last timing point\n timer_last_count = current_count;\n \n return elapsed;\n}\n\n/**\n * @brief Update elapsed time for countdown/count-up\n * \n * Use high-precision timer to calculate time elapsed since last call, and update\n * countup_elapsed_time (count-up mode) or countdown_elapsed_time (countdown mode) accordingly.\n * No updates are made in pause state.\n */\nvoid UpdateElapsedTime(void) {\n if (CLOCK_IS_PAUSED) {\n return; // Do not update in pause state\n }\n \n double elapsed_ms = GetElapsedMilliseconds();\n \n if (CLOCK_COUNT_UP) {\n // Count-up mode\n countup_elapsed_time += (int)(elapsed_ms / 1000.0);\n } else {\n // Countdown mode\n countdown_elapsed_time += (int)(elapsed_ms / 1000.0);\n \n // Ensure does not exceed total time\n if (countdown_elapsed_time > CLOCK_TOTAL_TIME) {\n countdown_elapsed_time = CLOCK_TOTAL_TIME;\n }\n }\n}\n\n/**\n * @brief Format display time\n * @param remaining_time Remaining time (seconds)\n * @param[out] time_text Formatted time string output buffer\n * \n * Format time as a string according to current configuration (12/24 hour format, whether to show seconds, countdown/count-up mode).\n * Supports three display modes: current system time, countdown remaining time, count-up accumulated time.\n */\nvoid FormatTime(int remaining_time, char* time_text) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // Get local time\n SYSTEMTIME st;\n GetLocalTime(&st);\n \n // Check time continuity, prevent second jumping display\n if (last_displayed_second != -1) {\n // If not consecutive seconds, and not a cross-minute situation\n if (st.wSecond != (last_displayed_second + 1) % 60 && \n !(last_displayed_second == 59 && st.wSecond == 0)) {\n // Relax conditions, allow larger differences to sync, ensure not lagging behind for long\n if (st.wSecond != last_displayed_second) {\n // Directly use system time seconds\n last_displayed_second = st.wSecond;\n }\n } else {\n // Time is consecutive, normal update\n last_displayed_second = st.wSecond;\n }\n } else {\n // First display, initialize record\n last_displayed_second = st.wSecond;\n }\n \n int hour = st.wHour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, st.wMinute, last_displayed_second);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, st.wMinute);\n }\n return;\n }\n\n if (CLOCK_COUNT_UP) {\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n return;\n }\n\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int remaining = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining <= 0) {\n // Do not return empty string, show 0:00 instead\n sprintf(time_text, \" 0:00\");\n return;\n }\n\n int hours = remaining / 3600;\n int minutes = (remaining % 3600) / 60;\n int seconds = remaining % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n if (minutes >= 10) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n }\n } else {\n if (seconds < 10) {\n sprintf(time_text, \" %d\", seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n }\n}\n\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n */\n\n// Detailed explanation of parsing logic and boundary handling\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n * \n * Parsing process:\n * 1. First check the validity of the input\n * 2. Detect if it's a target time format (ending with 't' or 'T')\n * - If so, calculate seconds from current to target time, if time has passed set to same time tomorrow\n * 3. Otherwise, check if it contains unit identifiers (h/m/s)\n * - If it does, process according to units\n * - If not, decide processing method based on number of space-separated numbers\n * \n * Boundary handling:\n * - Invalid input returns 0\n * - Negative or zero value returns 0\n * - Value exceeding INT_MAX returns 0\n */\nint ParseInput(const char* input, int* total_seconds) {\n if (!isValidInput(input)) return 0;\n\n int total = 0;\n char input_copy[256];\n strncpy(input_copy, input, sizeof(input_copy)-1);\n input_copy[sizeof(input_copy)-1] = '\\0';\n\n // Check if it's a target time format (ending with 't' or 'T')\n int len = strlen(input_copy);\n if (len > 0 && (input_copy[len-1] == 't' || input_copy[len-1] == 'T')) {\n // Remove 't' or 'T' suffix\n input_copy[len-1] = '\\0';\n \n // Get current time\n time_t now = time(NULL);\n struct tm *tm_now = localtime(&now);\n \n // Target time, initialize to current date\n struct tm tm_target = *tm_now;\n \n // Parse target time\n int hour = -1, minute = -1, second = -1;\n int count = 0;\n char *token = strtok(input_copy, \" \");\n \n while (token && count < 3) {\n int value = atoi(token);\n if (count == 0) hour = value;\n else if (count == 1) minute = value;\n else if (count == 2) second = value;\n count++;\n token = strtok(NULL, \" \");\n }\n \n // Set target time, set according to provided values, defaults to 0 if not provided\n if (hour >= 0) {\n tm_target.tm_hour = hour;\n \n // If only hour provided, set minute and second to 0\n if (minute < 0) {\n tm_target.tm_min = 0;\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_min = minute;\n \n // If second not provided, set to 0\n if (second < 0) {\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_sec = second;\n }\n }\n }\n \n // Calculate time difference (seconds)\n time_t target_time = mktime(&tm_target);\n \n // If target time has passed, set to same time tomorrow\n if (target_time <= now) {\n tm_target.tm_mday += 1;\n target_time = mktime(&tm_target);\n }\n \n total = (int)difftime(target_time, now);\n } else {\n // Check if it contains unit identifiers\n BOOL hasUnits = FALSE;\n for (int i = 0; input_copy[i]; i++) {\n char c = tolower((unsigned char)input_copy[i]);\n if (c == 'h' || c == 'm' || c == 's') {\n hasUnits = TRUE;\n break;\n }\n }\n \n if (hasUnits) {\n // For input with units, merge all parts with unit markings\n char* parts[10] = {0}; // Store up to 10 parts\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 10) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n // Process each part\n for (int i = 0; i < part_count; i++) {\n char* part = parts[i];\n int part_len = strlen(part);\n BOOL has_unit = FALSE;\n \n // Check if this part has a unit\n for (int j = 0; j < part_len; j++) {\n char c = tolower((unsigned char)part[j]);\n if (c == 'h' || c == 'm' || c == 's') {\n has_unit = TRUE;\n break;\n }\n }\n \n if (has_unit) {\n // If it has a unit, process according to unit\n char unit = tolower((unsigned char)part[part_len-1]);\n part[part_len-1] = '\\0'; // Remove unit\n int value = atoi(part);\n \n switch (unit) {\n case 'h': total += value * 3600; break;\n case 'm': total += value * 60; break;\n case 's': total += value; break;\n }\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'h') {\n // If next item has h unit, current item is hours\n total += atoi(part) * 3600;\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'm') {\n // If next item has m unit, current item is hours\n total += atoi(part) * 3600;\n } else {\n // Default process as two-segment or three-segment format\n if (part_count == 2) {\n // Two-segment format: first segment is minutes, second segment is seconds\n if (i == 0) total += atoi(part) * 60;\n else total += atoi(part);\n } else if (part_count == 3) {\n // Three-segment format: hour:minute:second\n if (i == 0) total += atoi(part) * 3600;\n else if (i == 1) total += atoi(part) * 60;\n else total += atoi(part);\n } else {\n // Other cases treated as minutes\n total += atoi(part) * 60;\n }\n }\n }\n } else {\n // Processing without units\n char* parts[3] = {0}; // Store up to 3 parts (hour, minute, second)\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 3) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n if (part_count == 1) {\n // Single number, calculate as minutes\n total = atoi(parts[0]) * 60;\n } else if (part_count == 2) {\n // Two numbers: minute:second\n total = atoi(parts[0]) * 60 + atoi(parts[1]);\n } else if (part_count == 3) {\n // Three numbers: hour:minute:second\n total = atoi(parts[0]) * 3600 + atoi(parts[1]) * 60 + atoi(parts[2]);\n }\n }\n }\n\n *total_seconds = total;\n if (*total_seconds <= 0) return 0;\n\n if (*total_seconds > INT_MAX) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Validate if input string is legal\n * @param input Input string to validate\n * @return int Returns 1 if legal, 0 if illegal\n * \n * Valid character check rules:\n * - Only allows digits, spaces, and h/m/s/t unit identifiers at the end (case insensitive)\n * - Must contain at least one digit\n * - Maximum of two space separators\n */\nint isValidInput(const char* input) {\n if (input == NULL || *input == '\\0') {\n return 0;\n }\n\n int len = strlen(input);\n int digitCount = 0;\n\n for (int i = 0; i < len; i++) {\n if (isdigit(input[i])) {\n digitCount++;\n } else if (input[i] == ' ') {\n // Allow any number of spaces\n } else if (i == len - 1 && (input[i] == 'h' || input[i] == 'm' || input[i] == 's' || \n input[i] == 't' || input[i] == 'T' || \n input[i] == 'H' || input[i] == 'M' || input[i] == 'S')) {\n // Allow last character to be h/m/s/t or their uppercase forms\n } else {\n return 0;\n }\n }\n\n if (digitCount == 0) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Reset timer\n * \n * Reset timer state, including pause flag, elapsed time, etc.\n */\nvoid ResetTimer(void) {\n // Reset timing state\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time = 0;\n } else {\n countdown_elapsed_time = 0;\n \n // Ensure countdown total time is not zero, zero would cause timer not to display\n if (CLOCK_TOTAL_TIME <= 0) {\n // If total time is invalid, use default value\n CLOCK_TOTAL_TIME = 60; // Default set to 1 minute\n }\n }\n \n // Cancel pause state\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset message display flags\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Reinitialize high-precision timer\n InitializeHighPrecisionTimer();\n}\n\n/**\n * @brief Toggle timer pause state\n * \n * Toggle timer between pause and continue states\n */\nvoid TogglePauseTimer(void) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n // If resuming from pause state, reinitialize high-precision timer\n if (!CLOCK_IS_PAUSED) {\n InitializeHighPrecisionTimer();\n }\n}\n\n/**\n * @brief Write default startup time to configuration file\n * @param seconds Default startup time (seconds)\n * \n * Use the general path retrieval method in the configuration management module to write to INI format configuration file\n */\nvoid WriteConfigDefaultStartTime(int seconds) {\n char config_path[MAX_PATH];\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Write using INI format\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", seconds, config_path);\n}\n"], ["/Catime/src/language.c", "/**\n * @file language.c\n * @brief Multilingual support module implementation\n * \n * This file implements the multilingual support functionality for the application, \n * including language detection and localized string handling.\n * Translation content is embedded as resources in the executable file.\n */\n\n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\n/// Global language variable, stores the current application language setting\nAppLanguage CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default to English\n\n/// Global hash table for storing translations of the current language\n#define MAX_TRANSLATIONS 200\n#define MAX_STRING_LENGTH 1024\n\n// Language resource IDs (defined in languages.rc)\n#define LANG_EN_INI 1001 // Corresponds to languages/en.ini\n#define LANG_ZH_CN_INI 1002 // Corresponds to languages/zh_CN.ini\n#define LANG_ZH_TW_INI 1003 // Corresponds to languages/zh-Hant.ini\n#define LANG_ES_INI 1004 // Corresponds to languages/es.ini\n#define LANG_FR_INI 1005 // Corresponds to languages/fr.ini\n#define LANG_DE_INI 1006 // Corresponds to languages/de.ini\n#define LANG_RU_INI 1007 // Corresponds to languages/ru.ini\n#define LANG_PT_INI 1008 // Corresponds to languages/pt.ini\n#define LANG_JA_INI 1009 // Corresponds to languages/ja.ini\n#define LANG_KO_INI 1010 // Corresponds to languages/ko.ini\n\n/**\n * @brief Define language string key-value pair structure\n */\ntypedef struct {\n wchar_t english[MAX_STRING_LENGTH]; // English key\n wchar_t translation[MAX_STRING_LENGTH]; // Translated value\n} LocalizedString;\n\nstatic LocalizedString g_translations[MAX_TRANSLATIONS];\nstatic int g_translation_count = 0;\n\n/**\n * @brief Get the resource ID corresponding to a language\n * \n * @param language Language enumeration value\n * @return UINT Corresponding resource ID\n */\nstatic UINT GetLanguageResourceID(AppLanguage language) {\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n return LANG_ZH_CN_INI;\n case APP_LANG_CHINESE_TRAD:\n return LANG_ZH_TW_INI;\n case APP_LANG_SPANISH:\n return LANG_ES_INI;\n case APP_LANG_FRENCH:\n return LANG_FR_INI;\n case APP_LANG_GERMAN:\n return LANG_DE_INI;\n case APP_LANG_RUSSIAN:\n return LANG_RU_INI;\n case APP_LANG_PORTUGUESE:\n return LANG_PT_INI;\n case APP_LANG_JAPANESE:\n return LANG_JA_INI;\n case APP_LANG_KOREAN:\n return LANG_KO_INI;\n case APP_LANG_ENGLISH:\n default:\n return LANG_EN_INI;\n }\n}\n\n/**\n * @brief Convert UTF-8 string to wide character (UTF-16) string\n * \n * @param utf8 UTF-8 string\n * @param wstr Output wide character string buffer\n * @param wstr_size Buffer size (in characters)\n * @return int Number of characters after conversion, returns -1 if failed\n */\nstatic int UTF8ToWideChar(const char* utf8, wchar_t* wstr, int wstr_size) {\n return MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, wstr_size) - 1;\n}\n\n/**\n * @brief Parse a line in an ini file\n * \n * @param line A line from the ini file\n * @return int Whether parsing was successful (1 for success, 0 for failure)\n */\nstatic int ParseIniLine(const wchar_t* line) {\n // Skip empty lines and comment lines\n if (line[0] == L'\\0' || line[0] == L';' || line[0] == L'[') {\n return 0;\n }\n\n // Find content between the first and last quotes as the key\n const wchar_t* key_start = wcschr(line, L'\"');\n if (!key_start) return 0;\n key_start++; // Skip the first quote\n\n const wchar_t* key_end = wcschr(key_start, L'\"');\n if (!key_end) return 0;\n\n // Find content between the first and last quotes after the equal sign as the value\n const wchar_t* value_start = wcschr(key_end + 1, L'=');\n if (!value_start) return 0;\n \n value_start = wcschr(value_start, L'\"');\n if (!value_start) return 0;\n value_start++; // Skip the first quote\n\n const wchar_t* value_end = wcsrchr(value_start, L'\"');\n if (!value_end) return 0;\n\n // Copy key\n size_t key_len = key_end - key_start;\n if (key_len >= MAX_STRING_LENGTH) key_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].english, key_start, key_len);\n g_translations[g_translation_count].english[key_len] = L'\\0';\n\n // Copy value\n size_t value_len = value_end - value_start;\n if (value_len >= MAX_STRING_LENGTH) value_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].translation, value_start, value_len);\n g_translations[g_translation_count].translation[value_len] = L'\\0';\n\n g_translation_count++;\n return 1;\n}\n\n/**\n * @brief Load translations for a specified language from resources\n * \n * @param language Language enumeration value\n * @return int Whether loading was successful\n */\nstatic int LoadLanguageResource(AppLanguage language) {\n UINT resourceID = GetLanguageResourceID(language);\n \n // Reset translation count\n g_translation_count = 0;\n \n // Find resource\n HRSRC hResInfo = FindResource(NULL, MAKEINTRESOURCE(resourceID), RT_RCDATA);\n if (!hResInfo) {\n // If not found, check if it's Chinese and return\n if (language == APP_LANG_CHINESE_SIMP || language == APP_LANG_CHINESE_TRAD) {\n return 0;\n }\n \n // If not Chinese, load English as fallback\n if (language != APP_LANG_ENGLISH) {\n return LoadLanguageResource(APP_LANG_ENGLISH);\n }\n \n return 0;\n }\n \n // Get resource size\n DWORD dwSize = SizeofResource(NULL, hResInfo);\n if (dwSize == 0) {\n return 0;\n }\n \n // Load resource\n HGLOBAL hResData = LoadResource(NULL, hResInfo);\n if (!hResData) {\n return 0;\n }\n \n // Lock resource to get pointer\n const char* pData = (const char*)LockResource(hResData);\n if (!pData) {\n return 0;\n }\n \n // Create memory buffer copy\n char* buffer = (char*)malloc(dwSize + 1);\n if (!buffer) {\n return 0;\n }\n \n // Copy resource data to buffer\n memcpy(buffer, pData, dwSize);\n buffer[dwSize] = '\\0';\n \n // Split by lines and parse\n char* line = strtok(buffer, \"\\r\\n\");\n wchar_t wide_buffer[MAX_STRING_LENGTH];\n \n while (line && g_translation_count < MAX_TRANSLATIONS) {\n // Skip empty lines and BOM markers\n if (line[0] == '\\0' || (line[0] == (char)0xEF && line[1] == (char)0xBB && line[2] == (char)0xBF)) {\n line = strtok(NULL, \"\\r\\n\");\n continue;\n }\n \n // Convert to wide characters\n if (UTF8ToWideChar(line, wide_buffer, MAX_STRING_LENGTH) > 0) {\n ParseIniLine(wide_buffer);\n }\n \n line = strtok(NULL, \"\\r\\n\");\n }\n \n free(buffer);\n return 1;\n}\n\n/**\n * @brief Find corresponding translation in the global translation table\n * \n * @param english English original text\n * @return const wchar_t* Found translation, returns NULL if not found\n */\nstatic const wchar_t* FindTranslation(const wchar_t* english) {\n for (int i = 0; i < g_translation_count; i++) {\n if (wcscmp(english, g_translations[i].english) == 0) {\n return g_translations[i].translation;\n }\n }\n return NULL;\n}\n\n/**\n * @brief Initialize the application language environment\n * \n * Automatically detect and set the current language of the application based on system language.\n * Supports detection of Simplified Chinese, Traditional Chinese, and other preset languages.\n */\nstatic void DetectSystemLanguage() {\n LANGID langID = GetUserDefaultUILanguage();\n switch (PRIMARYLANGID(langID)) {\n case LANG_CHINESE:\n // Distinguish between Simplified and Traditional Chinese\n if (SUBLANGID(langID) == SUBLANG_CHINESE_SIMPLIFIED) {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_SIMP;\n } else {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_TRAD;\n }\n break;\n case LANG_SPANISH:\n CURRENT_LANGUAGE = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n CURRENT_LANGUAGE = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n CURRENT_LANGUAGE = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n CURRENT_LANGUAGE = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n CURRENT_LANGUAGE = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n CURRENT_LANGUAGE = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n CURRENT_LANGUAGE = APP_LANG_KOREAN;\n break;\n default:\n CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default fallback to English\n }\n}\n\n/**\n * @brief Get localized string\n * @param chinese Simplified Chinese version of the string\n * @param english English version of the string\n * @return const wchar_t* Pointer to the string corresponding to the current language\n * \n * Returns the string in the corresponding language based on the current language setting.\n */\nconst wchar_t* GetLocalizedString(const wchar_t* chinese, const wchar_t* english) {\n // Initialize translation resources on first call, but don't automatically detect system language\n static BOOL initialized = FALSE;\n if (!initialized) {\n // No longer call DetectSystemLanguage() to automatically detect system language\n // Instead, use the currently set CURRENT_LANGUAGE value (possibly from a configuration file)\n LoadLanguageResource(CURRENT_LANGUAGE);\n initialized = TRUE;\n }\n\n const wchar_t* translation = NULL;\n\n // If Simplified Chinese and Chinese string is provided, return directly\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP && chinese) {\n return chinese;\n }\n\n // Find translation\n translation = FindTranslation(english);\n if (translation) {\n return translation;\n }\n\n // For Traditional Chinese but no translation found, return Simplified Chinese as a fallback\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD && chinese) {\n return chinese;\n }\n\n // Default to English\n return english;\n}\n\n/**\n * @brief Set application language\n * \n * @param language The language to set\n * @return BOOL Whether the setting was successful\n */\nBOOL SetLanguage(AppLanguage language) {\n if (language < 0 || language >= APP_LANG_COUNT) {\n return FALSE;\n }\n \n CURRENT_LANGUAGE = language;\n g_translation_count = 0; // Clear existing translations\n return LoadLanguageResource(language);\n}\n\n/**\n * @brief Get current application language\n * \n * @return AppLanguage Current language\n */\nAppLanguage GetCurrentLanguage() {\n return CURRENT_LANGUAGE;\n}\n\n/**\n * @brief Get the name of the current language\n * @param buffer Buffer to store the language name\n * @param bufferSize Buffer size (in characters)\n * @return Whether the language name was successfully retrieved\n */\nBOOL GetCurrentLanguageName(wchar_t* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) {\n return FALSE;\n }\n \n // Get current language\n AppLanguage language = GetCurrentLanguage();\n \n // Return corresponding name based on language enumeration\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n wcscpy_s(buffer, bufferSize, L\"zh_CN\");\n break;\n case APP_LANG_CHINESE_TRAD:\n wcscpy_s(buffer, bufferSize, L\"zh-Hant\");\n break;\n case APP_LANG_SPANISH:\n wcscpy_s(buffer, bufferSize, L\"es\");\n break;\n case APP_LANG_FRENCH:\n wcscpy_s(buffer, bufferSize, L\"fr\");\n break;\n case APP_LANG_GERMAN:\n wcscpy_s(buffer, bufferSize, L\"de\");\n break;\n case APP_LANG_RUSSIAN:\n wcscpy_s(buffer, bufferSize, L\"ru\");\n break;\n case APP_LANG_PORTUGUESE:\n wcscpy_s(buffer, bufferSize, L\"pt\");\n break;\n case APP_LANG_JAPANESE:\n wcscpy_s(buffer, bufferSize, L\"ja\");\n break;\n case APP_LANG_KOREAN:\n wcscpy_s(buffer, bufferSize, L\"ko\");\n break;\n case APP_LANG_ENGLISH:\n default:\n wcscpy_s(buffer, bufferSize, L\"en\");\n break;\n }\n \n return TRUE;\n}\n"], ["/Catime/src/tray.c", "/**\n * @file tray.c\n * @brief System tray functionality implementation\n */\n\n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/tray.h\"\n\nNOTIFYICONDATAW nid;\nUINT WM_TASKBARCREATED = 0;\n\n/**\n * @brief Register the TaskbarCreated message\n */\nvoid RegisterTaskbarCreatedMessage() {\n WM_TASKBARCREATED = RegisterWindowMessage(TEXT(\"TaskbarCreated\"));\n}\n\n/**\n * @brief Initialize the system tray icon\n * @param hwnd Window handle\n * @param hInstance Application instance handle\n */\nvoid InitTrayIcon(HWND hwnd, HINSTANCE hInstance) {\n memset(&nid, 0, sizeof(nid));\n nid.cbSize = sizeof(nid);\n nid.uID = CLOCK_ID_TRAY_APP_ICON;\n nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;\n nid.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CATIME));\n nid.hWnd = hwnd;\n nid.uCallbackMessage = CLOCK_WM_TRAYICON;\n \n wchar_t versionText[128] = {0};\n wchar_t versionWide[64] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CATIME_VERSION, -1, versionWide, _countof(versionWide));\n swprintf_s(versionText, _countof(versionText), L\"Catime %s\", versionWide);\n wcscpy_s(nid.szTip, _countof(nid.szTip), versionText);\n \n Shell_NotifyIconW(NIM_ADD, &nid);\n if (WM_TASKBARCREATED == 0) {\n RegisterTaskbarCreatedMessage();\n }\n}\n\n/**\n * @brief Remove the system tray icon\n */\nvoid RemoveTrayIcon(void) {\n Shell_NotifyIconW(NIM_DELETE, &nid);\n}\n\n/**\n * @brief Display a notification in the system tray\n * @param hwnd Window handle\n * @param message Text message to display\n */\nvoid ShowTrayNotification(HWND hwnd, const char* message) {\n NOTIFYICONDATAW nid_notify = {0};\n nid_notify.cbSize = sizeof(NOTIFYICONDATAW);\n nid_notify.hWnd = hwnd;\n nid_notify.uID = CLOCK_ID_TRAY_APP_ICON;\n nid_notify.uFlags = NIF_INFO;\n nid_notify.dwInfoFlags = NIIF_NONE;\n nid_notify.uTimeout = 3000;\n \n MultiByteToWideChar(CP_UTF8, 0, message, -1, nid_notify.szInfo, sizeof(nid_notify.szInfo)/sizeof(WCHAR));\n nid_notify.szInfoTitle[0] = L'\\0';\n \n Shell_NotifyIconW(NIM_MODIFY, &nid_notify);\n}\n\n/**\n * @brief Recreate the taskbar icon\n * @param hwnd Window handle\n * @param hInstance Instance handle\n */\nvoid RecreateTaskbarIcon(HWND hwnd, HINSTANCE hInstance) {\n RemoveTrayIcon();\n InitTrayIcon(hwnd, hInstance);\n}\n\n/**\n * @brief Update the tray icon and menu\n * @param hwnd Window handle\n */\nvoid UpdateTrayIcon(HWND hwnd) {\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n RecreateTaskbarIcon(hwnd, hInstance);\n}"], ["/Catime/src/drawing.c", "/**\n * @file drawing.c\n * @brief Window drawing functionality implementation\n * \n * This file implements the drawing-related functionality of the application window,\n * including text rendering, color settings, and window content drawing.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/drawing.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n\n// Variable imported from window_procedure.c\nextern int elapsed_time;\n\n// Using window drawing related constants defined in resource.h\n\nvoid HandleWindowPaint(HWND hwnd, PAINTSTRUCT *ps) {\n static char time_text[50];\n HDC hdc = ps->hdc;\n RECT rect;\n GetClientRect(hwnd, &rect);\n\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, rect.right, rect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n\n SetGraphicsMode(memDC, GM_ADVANCED);\n SetBkMode(memDC, TRANSPARENT);\n SetStretchBltMode(memDC, HALFTONE);\n SetBrushOrgEx(memDC, 0, 0, NULL);\n\n // Generate display text based on different modes\n if (CLOCK_SHOW_CURRENT_TIME) {\n time_t now = time(NULL);\n struct tm *tm_info = localtime(&now);\n int hour = tm_info->tm_hour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, tm_info->tm_min, tm_info->tm_sec);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, tm_info->tm_min);\n }\n } else if (CLOCK_COUNT_UP) {\n // Count-up mode\n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n } else {\n // Countdown mode\n int remaining_time = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining_time <= 0) {\n // Timeout reached, decide whether to display content based on conditions\n if (CLOCK_TOTAL_TIME == 0 && countdown_elapsed_time == 0) {\n // This is the case after sleep operation, don't display anything\n time_text[0] = '\\0';\n } else if (strcmp(CLOCK_TIMEOUT_TEXT, \"0\") == 0) {\n time_text[0] = '\\0';\n } else if (strlen(CLOCK_TIMEOUT_TEXT) > 0) {\n strncpy(time_text, CLOCK_TIMEOUT_TEXT, sizeof(time_text) - 1);\n time_text[sizeof(time_text) - 1] = '\\0';\n } else {\n time_text[0] = '\\0';\n }\n } else {\n int hours = remaining_time / 3600;\n int minutes = (remaining_time % 3600) / 60;\n int seconds = remaining_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n }\n }\n\n const char* fontToUse = IS_PREVIEWING ? PREVIEW_FONT_NAME : FONT_FILE_NAME;\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE * CLOCK_FONT_SCALE_FACTOR,\n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_TT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, \n VARIABLE_PITCH | FF_SWISS,\n IS_PREVIEWING ? PREVIEW_INTERNAL_NAME : FONT_INTERNAL_NAME\n );\n HFONT oldFont = (HFONT)SelectObject(memDC, hFont);\n\n SetTextAlign(memDC, TA_LEFT | TA_TOP);\n SetTextCharacterExtra(memDC, 0);\n SetMapMode(memDC, MM_TEXT);\n\n DWORD quality = SetICMMode(memDC, ICM_ON);\n SetLayout(memDC, 0);\n\n int r = 255, g = 255, b = 255;\n const char* colorToUse = IS_COLOR_PREVIEWING ? PREVIEW_COLOR : CLOCK_TEXT_COLOR;\n \n if (strlen(colorToUse) > 0) {\n if (colorToUse[0] == '#') {\n if (strlen(colorToUse) == 7) {\n sscanf(colorToUse + 1, \"%02x%02x%02x\", &r, &g, &b);\n }\n } else {\n sscanf(colorToUse, \"%d,%d,%d\", &r, &g, &b);\n }\n }\n SetTextColor(memDC, RGB(r, g, b));\n\n if (CLOCK_EDIT_MODE) {\n HBRUSH hBrush = CreateSolidBrush(RGB(20, 20, 20)); // Dark gray background\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n } else {\n HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0));\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n }\n\n if (strlen(time_text) > 0) {\n SIZE textSize;\n GetTextExtentPoint32(memDC, time_text, strlen(time_text), &textSize);\n\n if (textSize.cx != (rect.right - rect.left) || \n textSize.cy != (rect.bottom - rect.top)) {\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left, windowRect.top,\n textSize.cx + WINDOW_HORIZONTAL_PADDING, \n textSize.cy + WINDOW_VERTICAL_PADDING, \n SWP_NOZORDER | SWP_NOACTIVATE);\n GetClientRect(hwnd, &rect);\n }\n\n \n int x = (rect.right - textSize.cx) / 2;\n int y = (rect.bottom - textSize.cy) / 2;\n\n // If in edit mode, force white text and add outline effect\n if (CLOCK_EDIT_MODE) {\n SetTextColor(memDC, RGB(255, 255, 255));\n \n // Add black outline effect\n SetTextColor(memDC, RGB(0, 0, 0));\n TextOutA(memDC, x-1, y, time_text, strlen(time_text));\n TextOutA(memDC, x+1, y, time_text, strlen(time_text));\n TextOutA(memDC, x, y-1, time_text, strlen(time_text));\n TextOutA(memDC, x, y+1, time_text, strlen(time_text));\n \n // Set back to white for drawing text\n SetTextColor(memDC, RGB(255, 255, 255));\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n } else {\n SetTextColor(memDC, RGB(r, g, b));\n \n for (int i = 0; i < 8; i++) {\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n }\n }\n }\n\n BitBlt(hdc, 0, 0, rect.right, rect.bottom, memDC, 0, 0, SRCCOPY);\n\n SelectObject(memDC, oldFont);\n DeleteObject(hFont);\n SelectObject(memDC, oldBitmap);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n}"], ["/Catime/src/startup.c", "/**\n * @file startup.c\n * @brief Implementation of auto-start functionality\n * \n * This file implements the application's auto-start related functionality,\n * including checking if auto-start is enabled, creating and deleting auto-start shortcuts.\n */\n\n#include \"../include/startup.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/config.h\"\n#include \"../include/timer.h\"\n\n#ifndef CSIDL_STARTUP\n#define CSIDL_STARTUP 0x0007\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern int countup_elapsed_time;\nextern int CLOCK_DEFAULT_START_TIME;\nextern char CLOCK_STARTUP_MODE[20];\n/// @}\n\n/**\n * @brief Check if the application is set to auto-start at system boot\n * @return BOOL Returns TRUE if auto-start is enabled, otherwise FALSE\n */\nBOOL IsAutoStartEnabled(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n return GetFileAttributesW(startupPath) != INVALID_FILE_ATTRIBUTES;\n }\n return FALSE;\n}\n\n/**\n * @brief Create auto-start shortcut\n * @return BOOL Returns TRUE if creation was successful, otherwise FALSE\n */\nBOOL CreateShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n wchar_t exePath[MAX_PATH];\n IShellLinkW* pShellLink = NULL;\n IPersistFile* pPersistFile = NULL;\n BOOL success = FALSE;\n \n GetModuleFileNameW(NULL, exePath, MAX_PATH);\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n HRESULT hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkW, (void**)&pShellLink);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->SetPath(pShellLink, exePath);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->QueryInterface(pShellLink,\n &IID_IPersistFile,\n (void**)&pPersistFile);\n if (SUCCEEDED(hr)) {\n hr = pPersistFile->lpVtbl->Save(pPersistFile, startupPath, TRUE);\n if (SUCCEEDED(hr)) {\n success = TRUE;\n }\n pPersistFile->lpVtbl->Release(pPersistFile);\n }\n }\n pShellLink->lpVtbl->Release(pShellLink);\n }\n }\n \n return success;\n}\n\n/**\n * @brief Delete auto-start shortcut\n * @return BOOL Returns TRUE if deletion was successful, otherwise FALSE\n */\nBOOL RemoveShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n return DeleteFileW(startupPath);\n }\n return FALSE;\n}\n\n/**\n * @brief Update auto-start shortcut\n * \n * Check if auto-start is enabled, if so, delete the old shortcut and create a new one,\n * ensuring that the auto-start functionality works correctly even if the application location changes.\n * \n * @return BOOL Returns TRUE if update was successful, otherwise FALSE\n */\nBOOL UpdateStartupShortcut(void) {\n // If auto-start is already enabled\n if (IsAutoStartEnabled()) {\n // First delete the existing shortcut\n RemoveShortcut();\n // Create a new shortcut\n return CreateShortcut();\n }\n return TRUE; // Auto-start not enabled, considered successful\n}\n\n/**\n * @brief Apply startup mode settings\n * @param hwnd Window handle\n * \n * Initialize the application's display state according to the startup mode settings in the configuration file\n */\nvoid ApplyStartupMode(HWND hwnd) {\n // Read startup mode from configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", CLOCK_STARTUP_MODE);\n break;\n }\n }\n fclose(configFile);\n \n // Apply startup mode\n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n // Set to count-up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n // Set to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n // Set to no display mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n } else { // Default to countdown mode \"COUNTDOWN\"\n // Set to countdown mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n \n // Read default countdown time\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n \n // If countdown is set, start the timer\n if (CLOCK_TOTAL_TIME > 0) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n"], ["/Catime/src/tray_events.c", "/**\n * @file tray_events.c\n * @brief Implementation of system tray event handling module\n * \n * This module implements the event handling functionality for the application's system tray,\n * including response to various mouse events on the tray icon, menu display and control,\n * as well as tray operations related to the timer such as pause/resume and restart.\n * It provides core functionality for users to quickly control the application through the tray icon.\n */\n\n#include \n#include \n#include \"../include/tray_events.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/window_events.h\"\n#include \"../resource/resource.h\"\n\n// Declaration of function to read timeout action from configuration file\nextern void ReadTimeoutActionFromConfig(void);\n\n/**\n * @brief Handle system tray messages\n * @param hwnd Window handle\n * @param uID Tray icon ID\n * @param uMouseMsg Mouse message type\n * \n * Process mouse events for the system tray, displaying different context menus based on the event type:\n * - Left click: Display main function context menu, including timer control functions\n * - Right click: Display color selection menu for quickly changing display color\n * \n * All menu item command processing is implemented in the corresponding menu display module.\n */\nvoid HandleTrayIconMessage(HWND hwnd, UINT uID, UINT uMouseMsg) {\n // Set default cursor to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n if (uMouseMsg == WM_RBUTTONUP) {\n ShowColorMenu(hwnd);\n }\n else if (uMouseMsg == WM_LBUTTONUP) {\n ShowContextMenu(hwnd);\n }\n}\n\n/**\n * @brief Pause or resume timer\n * @param hwnd Window handle\n * \n * Toggle timer pause/resume state based on current status:\n * 1. Check if there is an active timer (countdown or count-up)\n * 2. If timer is active, toggle pause/resume state\n * 3. When paused, record current time point and stop timer\n * 4. When resumed, restart timer\n * 5. Refresh window to reflect new state\n * \n * Note: Can only operate when displaying timer (not current time) and timer is active\n */\nvoid PauseResumeTimer(HWND hwnd) {\n // Check if there is an active timer\n if (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || CLOCK_TOTAL_TIME > 0)) {\n \n // Toggle pause/resume state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n if (CLOCK_IS_PAUSED) {\n // If paused, record current time point\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n // Stop timer\n KillTimer(hwnd, 1);\n \n // Pause playing notification audio (new addition)\n extern BOOL PauseNotificationSound(void);\n PauseNotificationSound();\n } else {\n // If resumed, restart timer\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Resume notification audio (new addition)\n extern BOOL ResumeNotificationSound(void);\n ResumeNotificationSound();\n }\n \n // Update window to reflect new state\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart timer\n * @param hwnd Window handle\n * \n * Reset timer to initial state and continue running, keeping current timer type unchanged:\n * 1. Read current timeout action settings\n * 2. Reset timer progress based on current mode (countdown/count-up)\n * 3. Reset all related timer state variables\n * 4. Cancel pause state, ensure timer is running\n * 5. Refresh window and ensure window is on top after reset\n * \n * This operation does not change the timer mode or total duration, it only resets progress to initial state.\n */\nvoid RestartTimer(HWND hwnd) {\n // Stop any notification audio that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Determine operation based on current mode\n if (!CLOCK_COUNT_UP) {\n // Countdown mode\n if (CLOCK_TOTAL_TIME > 0) {\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n } else {\n // Count-up mode\n countup_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Update window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure window is on top and visible\n HandleWindowReset(hwnd);\n}\n\n/**\n * @brief Set startup mode\n * @param hwnd Window handle\n * @param mode Startup mode (\"COUNTDOWN\"/\"COUNT_UP\"/\"SHOW_TIME\"/\"NO_DISPLAY\")\n * \n * Set the application's default startup mode and save it to the configuration file:\n * 1. Save the selected mode to the configuration file\n * 2. Update menu item checked state to reflect current setting\n * 3. Refresh window display\n * \n * The startup mode determines the default behavior of the application at startup, such as whether to display current time or start timing.\n * The setting will take effect the next time the program starts.\n */\nvoid SetStartupMode(HWND hwnd, const char* mode) {\n // Save startup mode to configuration file\n WriteConfigStartupMode(mode);\n \n // Update menu item checked state\n HMENU hMenu = GetMenu(hwnd);\n if (hMenu) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Open user guide webpage\n * \n * Use ShellExecute to open Catime's user guide webpage,\n * providing detailed software instructions and help documentation for users.\n * URL: https://vladelaina.github.io/Catime/guide\n */\nvoid OpenUserGuide(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/guide\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open support page\n * \n * Use ShellExecute to open Catime's support page,\n * providing channels for users to support the developer.\n * URL: https://vladelaina.github.io/Catime/support\n */\nvoid OpenSupportPage(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open feedback page\n * \n * Open different feedback channels based on current language setting:\n * - Simplified Chinese: Open bilibili private message page\n * - Other languages: Open GitHub Issues page\n */\nvoid OpenFeedbackPage(void) {\n extern AppLanguage CURRENT_LANGUAGE; // Declare external variable\n \n // Choose different feedback links based on language\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP) {\n // Simplified Chinese users open bilibili private message\n ShellExecuteW(NULL, L\"open\", URL_FEEDBACK, NULL, NULL, SW_SHOWNORMAL);\n } else {\n // Users of other languages open GitHub Issues\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime/issues\", NULL, NULL, SW_SHOWNORMAL);\n }\n}"], ["/Catime/src/drag_scale.c", "/**\n * @file drag_scale.c\n * @brief Window dragging and scaling functionality implementation\n * \n * This file implements the dragging and scaling functionality of the application window,\n * including mouse dragging of the window and mouse wheel scaling of the window.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n\n// Add variable to record the topmost state before edit mode\nBOOL PREVIOUS_TOPMOST_STATE = FALSE;\n\nvoid StartDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_IS_DRAGGING = TRUE;\n SetCapture(hwnd);\n GetCursorPos(&CLOCK_LAST_MOUSE_POS);\n }\n}\n\nvoid StartEditMode(HWND hwnd) {\n // Record current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If currently not in topmost state, set to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Then enable edit mode\n CLOCK_EDIT_MODE = TRUE;\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure mouse cursor is default arrow\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n}\n\nvoid EndEditMode(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_EDIT_MODE = FALSE;\n \n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // If previously not in topmost state, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n }\n}\n\nvoid EndDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n CLOCK_IS_DRAGGING = FALSE;\n ReleaseCapture();\n // In edit mode, don't force window to stay on screen, allow dragging out\n AdjustWindowPosition(hwnd, FALSE);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\nBOOL HandleDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleScaleWindow(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings\n SaveWindowSettings(hwnd);\n return TRUE;\n }\n }\n return FALSE;\n}"], ["/Catime/src/media.c", "/**\n * @file media.c\n * @brief Media control functionality implementation\n * \n * This file implements the application's media control related functions,\n * including pause, play and other media control operations.\n */\n\n#include \n#include \"../include/media.h\"\n\n/**\n * @brief Pause media playback\n * \n * Pauses currently playing media by simulating media control key press events.\n * Includes a combination of stop and pause/play operations to ensure the media is properly paused.\n */\nvoid PauseMediaPlayback(void) {\n keybd_event(VK_MEDIA_STOP, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_STOP, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(100);\n}"], ["/Catime/libs/miniaudio/miniaudio.c", "#define MINIAUDIO_IMPLEMENTATION\n#include \"miniaudio.h\"\n"]], "task_instance_info": {"created_time": "2025-08-20 17:54:33", "created_task_model": "DeepSeek-R1", "function_skeleton": "unsigned __stdcall UpdateCheckThreadProc(void* param) {}", "code_description": "This code segment functions to: Execute a background process that validates initialization parameters, coordinates system resource management, and communicates status updates while performing a version verification operation."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nunsigned __stdcall UpdateCheckThreadProc(void* param) {\n UpdateThreadParams* threadParams = (UpdateThreadParams*)param;\n LOG_INFO(\"Update check thread started, silent mode: %s\", \n threadParams->silentCheck ? \"enabled\" : \"disabled\");\n\n BOOL checkResult = CheckForUpdate(threadParams->silentCheck);\n \n if (checkResult) {\n LOG_INFO(\"Update check completed successfully\");\n } else {\n LOG_WARNING(\"Update check failed or no updates available\");\n }\n\n if (IsWindow(threadParams->hwnd)) {\n PostMessage(threadParams->hwnd, WM_UPDATE_CHECK_COMPLETE, \n (WPARAM)checkResult, (LPARAM)0);\n } else {\n LOG_WARNING(\"Target window handle is invalid, cannot post update notification\");\n }\n\n free(threadParams);\n g_bUpdateThreadRunning = FALSE;\n return 0;\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 17-55-07"}, "editdistance_info": {"edit_distance": 23.2673, "calculate_time": "2025-08-20 17:55:07", "true_code_clean": "unsigned __stdcall UpdateCheckThreadProc(void* param) {\n LOG_INFO(\"Update check thread started\");\n UpdateThreadParams* threadParams = (UpdateThreadParams*)param;\n if (!threadParams) {\n LOG_ERROR(\"Thread parameters are null, cannot perform update check\");\n g_bUpdateThreadRunning = FALSE;\n _endthreadex(1);\n return 1;\n }\n HWND hwnd = threadParams->hwnd;\n BOOL silentCheck = threadParams->silentCheck;\n LOG_INFO(\"Thread parameters parsed successfully, window handle: 0x%p, silent check mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n free(threadParams);\n LOG_INFO(\"Thread parameter memory freed\");\n LOG_INFO(\"Starting update check\");\n CheckForUpdateSilent(hwnd, silentCheck);\n LOG_INFO(\"Update check completed\");\n g_bUpdateThreadRunning = FALSE;\n _endthreadex(0);\n return 0;\n}", "predict_code_clean": "unsigned __stdcall UpdateCheckThreadProc(void* param) {\n UpdateThreadParams* threadParams = (UpdateThreadParams*)param;\n LOG_INFO(\"Update check thread started, silent mode: %s\", \n threadParams->silentCheck ? \"enabled\" : \"disabled\");\n BOOL checkResult = CheckForUpdate(threadParams->silentCheck);\n if (checkResult) {\n LOG_INFO(\"Update check completed successfully\");\n } else {\n LOG_WARNING(\"Update check failed or no updates available\");\n }\n if (IsWindow(threadParams->hwnd)) {\n PostMessage(threadParams->hwnd, WM_UPDATE_CHECK_COMPLETE, \n (WPARAM)checkResult, (LPARAM)0);\n } else {\n LOG_WARNING(\"Target window handle is invalid, cannot post update notification\");\n }\n free(threadParams);\n g_bUpdateThreadRunning = FALSE;\n return 0;\n}"}} {"repo_name": "Catime", "file_name": "/Catime/src/tray.c", "inference_info": {"prefix_code": "/**\n * @file tray.c\n * @brief System tray functionality implementation\n */\n\n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/tray.h\"\n\nNOTIFYICONDATAW nid;\nUINT WM_TASKBARCREATED = 0;\n\n/**\n * @brief Register the TaskbarCreated message\n */\nvoid RegisterTaskbarCreatedMessage() {\n WM_TASKBARCREATED = RegisterWindowMessage(TEXT(\"TaskbarCreated\"));\n}\n\n/**\n * @brief Initialize the system tray icon\n * @param hwnd Window handle\n * @param hInstance Application instance handle\n */\n", "suffix_code": "\n\n/**\n * @brief Remove the system tray icon\n */\nvoid RemoveTrayIcon(void) {\n Shell_NotifyIconW(NIM_DELETE, &nid);\n}\n\n/**\n * @brief Display a notification in the system tray\n * @param hwnd Window handle\n * @param message Text message to display\n */\nvoid ShowTrayNotification(HWND hwnd, const char* message) {\n NOTIFYICONDATAW nid_notify = {0};\n nid_notify.cbSize = sizeof(NOTIFYICONDATAW);\n nid_notify.hWnd = hwnd;\n nid_notify.uID = CLOCK_ID_TRAY_APP_ICON;\n nid_notify.uFlags = NIF_INFO;\n nid_notify.dwInfoFlags = NIIF_NONE;\n nid_notify.uTimeout = 3000;\n \n MultiByteToWideChar(CP_UTF8, 0, message, -1, nid_notify.szInfo, sizeof(nid_notify.szInfo)/sizeof(WCHAR));\n nid_notify.szInfoTitle[0] = L'\\0';\n \n Shell_NotifyIconW(NIM_MODIFY, &nid_notify);\n}\n\n/**\n * @brief Recreate the taskbar icon\n * @param hwnd Window handle\n * @param hInstance Instance handle\n */\nvoid RecreateTaskbarIcon(HWND hwnd, HINSTANCE hInstance) {\n RemoveTrayIcon();\n InitTrayIcon(hwnd, hInstance);\n}\n\n/**\n * @brief Update the tray icon and menu\n * @param hwnd Window handle\n */\nvoid UpdateTrayIcon(HWND hwnd) {\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n RecreateTaskbarIcon(hwnd, hInstance);\n}", "middle_code": "void InitTrayIcon(HWND hwnd, HINSTANCE hInstance) {\n memset(&nid, 0, sizeof(nid));\n nid.cbSize = sizeof(nid);\n nid.uID = CLOCK_ID_TRAY_APP_ICON;\n nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;\n nid.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CATIME));\n nid.hWnd = hwnd;\n nid.uCallbackMessage = CLOCK_WM_TRAYICON;\n wchar_t versionText[128] = {0};\n wchar_t versionWide[64] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CATIME_VERSION, -1, versionWide, _countof(versionWide));\n swprintf_s(versionText, _countof(versionText), L\"Catime %s\", versionWide);\n wcscpy_s(nid.szTip, _countof(nid.szTip), versionText);\n Shell_NotifyIconW(NIM_ADD, &nid);\n if (WM_TASKBARCREATED == 0) {\n RegisterTaskbarCreatedMessage();\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/Catime/src/window_procedure.c", "/**\n * @file window_procedure.c\n * @brief Window message processing implementation\n * \n * This file implements the message processing callback function for the application's main window,\n * handling all message events for the window.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\" \n#include \"../include/window.h\" \n#include \"../include/startup.h\" \n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/window_events.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/drawing.h\"\n#include \"../include/timer_events.h\"\n#include \"../include/tray_events.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/notification.h\" // Add notification header\n\n// Variables imported from main.c\nextern char inputText[256];\nextern int elapsed_time;\nextern int message_shown;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void PauseMediaPlayback(void);\n\n// Add these external variable declarations at the beginning of the file\nextern int POMODORO_TIMES[10]; // Pomodoro time array\nextern int POMODORO_TIMES_COUNT; // Number of pomodoro time options\nextern int current_pomodoro_time_index; // Current pomodoro time index\nextern int complete_pomodoro_cycles; // Completed pomodoro cycles\n\n// If ShowInputDialog function needs to be declared, add at the beginning\nextern BOOL ShowInputDialog(HWND hwnd, char* text);\n\n// Modify to match the correct function declaration in config.h\nextern void WriteConfigPomodoroTimeOptions(int* times, int count);\n\n// If the function doesn't exist, use an existing similar function\n// For example, modify calls to WriteConfigPomodoroTimeOptions to WriteConfigPomodoroTimes\n\n// Add at the beginning of the file\ntypedef struct {\n const wchar_t* title;\n const wchar_t* prompt;\n const wchar_t* defaultText;\n wchar_t* result;\n size_t maxLen;\n} INPUTBOX_PARAMS;\n\n// Add declaration for ShowPomodoroLoopDialog function at the beginning of the file\nextern void ShowPomodoroLoopDialog(HWND hwndParent);\n\n// Add declaration for OpenUserGuide function\nextern void OpenUserGuide(void);\n\n// Add declaration for OpenSupportPage function\nextern void OpenSupportPage(void);\n\n// Add declaration for OpenFeedbackPage function\nextern void OpenFeedbackPage(void);\n\n// Helper function: Check if a string contains only spaces\nstatic BOOL isAllSpacesOnly(const char* str) {\n for (int i = 0; str[i]; i++) {\n if (!isspace((unsigned char)str[i])) {\n return FALSE;\n }\n }\n return TRUE;\n}\n\n/**\n * @brief Input dialog callback function\n * @param hwndDlg Dialog handle\n * @param uMsg Message\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return Processing result\n */\nINT_PTR CALLBACK InputBoxProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {\n static wchar_t* result;\n static size_t maxLen;\n \n switch (uMsg) {\n case WM_INITDIALOG: {\n // Get passed parameters\n INPUTBOX_PARAMS* params = (INPUTBOX_PARAMS*)lParam;\n result = params->result;\n maxLen = params->maxLen;\n \n // Set dialog title\n SetWindowTextW(hwndDlg, params->title);\n \n // Set prompt message\n SetDlgItemTextW(hwndDlg, IDC_STATIC_PROMPT, params->prompt);\n \n // Set default text\n SetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, params->defaultText);\n \n // Select text\n SendDlgItemMessageW(hwndDlg, IDC_EDIT_INPUT, EM_SETSEL, 0, -1);\n \n // Set focus\n SetFocus(GetDlgItem(hwndDlg, IDC_EDIT_INPUT));\n return FALSE;\n }\n \n case WM_COMMAND:\n switch (LOWORD(wParam)) {\n case IDOK: {\n // Get input text\n GetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, result, (int)maxLen);\n EndDialog(hwndDlg, TRUE);\n return TRUE;\n }\n \n case IDCANCEL:\n // Cancel operation\n EndDialog(hwndDlg, FALSE);\n return TRUE;\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display input dialog\n * @param hwndParent Parent window handle\n * @param title Dialog title\n * @param prompt Prompt message\n * @param defaultText Default text\n * @param result Result buffer\n * @param maxLen Maximum buffer length\n * @return TRUE if successful, FALSE if canceled\n */\nBOOL InputBox(HWND hwndParent, const wchar_t* title, const wchar_t* prompt, \n const wchar_t* defaultText, wchar_t* result, size_t maxLen) {\n // Prepare parameters to pass to dialog\n INPUTBOX_PARAMS params;\n params.title = title;\n params.prompt = prompt;\n params.defaultText = defaultText;\n params.result = result;\n params.maxLen = maxLen;\n \n // Display modal dialog\n return DialogBoxParamW(GetModuleHandle(NULL), \n MAKEINTRESOURCEW(IDD_INPUTBOX), \n hwndParent, \n InputBoxProc, \n (LPARAM)¶ms) == TRUE;\n}\n\nvoid ExitProgram(HWND hwnd) {\n RemoveTrayIcon();\n\n PostQuitMessage(0);\n}\n\n#define HOTKEY_ID_SHOW_TIME 100 // Hotkey ID to show current time\n#define HOTKEY_ID_COUNT_UP 101 // Hotkey ID for count up timer\n#define HOTKEY_ID_COUNTDOWN 102 // Hotkey ID for countdown timer\n#define HOTKEY_ID_QUICK_COUNTDOWN1 103 // Hotkey ID for quick countdown 1\n#define HOTKEY_ID_QUICK_COUNTDOWN2 104 // Hotkey ID for quick countdown 2\n#define HOTKEY_ID_QUICK_COUNTDOWN3 105 // Hotkey ID for quick countdown 3\n#define HOTKEY_ID_POMODORO 106 // Hotkey ID for pomodoro timer\n#define HOTKEY_ID_TOGGLE_VISIBILITY 107 // Hotkey ID for hide/show\n#define HOTKEY_ID_EDIT_MODE 108 // Hotkey ID for edit mode\n#define HOTKEY_ID_PAUSE_RESUME 109 // Hotkey ID for pause/resume\n#define HOTKEY_ID_RESTART_TIMER 110 // Hotkey ID for restart timer\n#define HOTKEY_ID_CUSTOM_COUNTDOWN 111 // Hotkey ID for custom countdown\n\n/**\n * @brief Register global hotkeys\n * @param hwnd Window handle\n * \n * Reads and registers global hotkey settings from the configuration file for quickly switching between\n * displaying current time, count up timer, and default countdown.\n * If a hotkey is already registered, it will be unregistered before re-registering.\n * If a hotkey cannot be registered (possibly because it's being used by another program),\n * that hotkey setting will be set to none and the configuration file will be updated.\n * \n * @return BOOL Whether at least one hotkey was successfully registered\n */\nBOOL RegisterGlobalHotkeys(HWND hwnd) {\n // First unregister all previously registered hotkeys\n UnregisterGlobalHotkeys(hwnd);\n \n // Use new function to read hotkey configuration\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n BOOL success = FALSE;\n BOOL configChanged = FALSE;\n \n // Register show current time hotkey\n if (showTimeHotkey != 0) {\n BYTE vk = LOBYTE(showTimeHotkey); // Virtual key code\n BYTE mod = HIBYTE(showTimeHotkey); // Modifier keys\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n showTimeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register count up hotkey\n if (countUpHotkey != 0) {\n BYTE vk = LOBYTE(countUpHotkey);\n BYTE mod = HIBYTE(countUpHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNT_UP, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countUpHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register countdown hotkey\n if (countdownHotkey != 0) {\n BYTE vk = LOBYTE(countdownHotkey);\n BYTE mod = HIBYTE(countdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 1 hotkey\n if (quickCountdown1Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown1Hotkey);\n BYTE mod = HIBYTE(quickCountdown1Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown1Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 2 hotkey\n if (quickCountdown2Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown2Hotkey);\n BYTE mod = HIBYTE(quickCountdown2Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown2Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 3 hotkey\n if (quickCountdown3Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown3Hotkey);\n BYTE mod = HIBYTE(quickCountdown3Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown3Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pomodoro hotkey\n if (pomodoroHotkey != 0) {\n BYTE vk = LOBYTE(pomodoroHotkey);\n BYTE mod = HIBYTE(pomodoroHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_POMODORO, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pomodoroHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register hide/show window hotkey\n if (toggleVisibilityHotkey != 0) {\n BYTE vk = LOBYTE(toggleVisibilityHotkey);\n BYTE mod = HIBYTE(toggleVisibilityHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n toggleVisibilityHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register edit mode hotkey\n if (editModeHotkey != 0) {\n BYTE vk = LOBYTE(editModeHotkey);\n BYTE mod = HIBYTE(editModeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n editModeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pause/resume hotkey\n if (pauseResumeHotkey != 0) {\n BYTE vk = LOBYTE(pauseResumeHotkey);\n BYTE mod = HIBYTE(pauseResumeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pauseResumeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register restart timer hotkey\n if (restartTimerHotkey != 0) {\n BYTE vk = LOBYTE(restartTimerHotkey);\n BYTE mod = HIBYTE(restartTimerHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n restartTimerHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // If any hotkey registration failed, update config file\n if (configChanged) {\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n \n // Check if custom countdown hotkey was cleared, if so, update config\n if (customCountdownHotkey == 0) {\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", \"None\");\n }\n }\n \n // Added after reading hotkey configuration\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Added after registering countdown hotkey\n // Register custom countdown hotkey\n if (customCountdownHotkey != 0) {\n BYTE vk = LOBYTE(customCountdownHotkey);\n BYTE mod = HIBYTE(customCountdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n customCountdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n return success;\n}\n\n/**\n * @brief Unregister global hotkeys\n * @param hwnd Window handle\n * \n * Unregister all previously registered global hotkeys.\n */\nvoid UnregisterGlobalHotkeys(HWND hwnd) {\n // Unregister all previously registered hotkeys\n UnregisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNT_UP);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3);\n UnregisterHotKey(hwnd, HOTKEY_ID_POMODORO);\n UnregisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY);\n UnregisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE);\n UnregisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME);\n UnregisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER);\n UnregisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN);\n}\n\n/**\n * @brief Main window message processing callback function\n * @param hwnd Window handle\n * @param msg Message type\n * @param wp Message parameter (specific meaning depends on message type)\n * @param lp Message parameter (specific meaning depends on message type)\n * @return LRESULT Message processing result\n * \n * Handles all message events for the main window, including:\n * - Window creation/destruction\n * - Mouse events (dragging, wheel scaling)\n * - Timer events\n * - System tray interaction\n * - Drawing events\n * - Menu command processing\n */\nLRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)\n{\n static char time_text[50];\n UINT uID;\n UINT uMouseMsg;\n\n // Check if this is a TaskbarCreated message\n // TaskbarCreated is a system message broadcasted when Windows Explorer restarts\n // At this time all tray icons are destroyed and need to be recreated by applications\n // Handling this message solves the issue of the tray icon disappearing while the program is still running\n if (msg == WM_TASKBARCREATED) {\n // Explorer has restarted, need to recreate the tray icon\n RecreateTaskbarIcon(hwnd, GetModuleHandle(NULL));\n return 0;\n }\n\n switch(msg)\n {\n case WM_CREATE: {\n // Register global hotkeys when window is created\n RegisterGlobalHotkeys(hwnd);\n HandleWindowCreate(hwnd);\n break;\n }\n\n case WM_SETCURSOR: {\n // When in edit mode, always use default arrow cursor\n if (CLOCK_EDIT_MODE && LOWORD(lp) == HTCLIENT) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE; // Indicates we've handled this message\n }\n \n // Also use default arrow cursor when handling tray icon operations\n if (LOWORD(lp) == HTCLIENT || msg == CLOCK_WM_TRAYICON) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE;\n }\n break;\n }\n\n case WM_LBUTTONDOWN: {\n StartDragWindow(hwnd);\n break;\n }\n\n case WM_LBUTTONUP: {\n EndDragWindow(hwnd);\n break;\n }\n\n case WM_MOUSEWHEEL: {\n int delta = GET_WHEEL_DELTA_WPARAM(wp);\n HandleScaleWindow(hwnd, delta);\n break;\n }\n\n case WM_MOUSEMOVE: {\n if (HandleDragWindow(hwnd)) {\n return 0;\n }\n break;\n }\n\n case WM_PAINT: {\n PAINTSTRUCT ps;\n BeginPaint(hwnd, &ps);\n HandleWindowPaint(hwnd, &ps);\n EndPaint(hwnd, &ps);\n break;\n }\n case WM_TIMER: {\n if (HandleTimerEvent(hwnd, wp)) {\n break;\n }\n break;\n }\n case WM_DESTROY: {\n // Unregister global hotkeys when window is destroyed\n UnregisterGlobalHotkeys(hwnd);\n HandleWindowDestroy(hwnd);\n return 0;\n }\n case CLOCK_WM_TRAYICON: {\n HandleTrayIconMessage(hwnd, (UINT)wp, (UINT)lp);\n break;\n }\n case WM_COMMAND: {\n // Handle preset color options (ID: 201 ~ 201+COLOR_OPTIONS_COUNT-1)\n if (LOWORD(wp) >= 201 && LOWORD(wp) < 201 + COLOR_OPTIONS_COUNT) {\n int colorIndex = LOWORD(wp) - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n // Update current color\n strncpy(CLOCK_TEXT_COLOR, COLOR_OPTIONS[colorIndex].hexColor, \n sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n \n // Write to config file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n \n // Redraw window to show new color\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n WORD cmd = LOWORD(wp);\n switch (cmd) {\n case 101: { \n if (CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_LAST_TIME_UPDATE = 0;\n KillTimer(hwnd, 1);\n }\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n // Handle quick time options (102-102+MAX_TIME_OPTIONS)\n case 102: case 103: case 104: case 105: case 106:\n case 107: case 108: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n int index = cmd - 102;\n if (index >= 0 && index < time_options_count) {\n int minutes = time_options[index];\n if (minutes > 0) {\n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = minutes * 60; // Convert to seconds\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n break;\n }\n // Handle exit option\n case 109: {\n ExitProgram(hwnd);\n break;\n }\n case CLOCK_IDC_MODIFY_TIME_OPTIONS: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_SHORTCUT_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_SHORTCUT_DIALOG);\n\n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n // If input is empty or contains only spaces, exit the loop\n if (inputText[0] == '\\0' || isAllSpaces) {\n break;\n }\n\n char* token = strtok(inputText, \" \");\n char options[256] = {0};\n int valid = 1;\n int count = 0;\n \n while (token && count < MAX_TIME_OPTIONS) {\n int num = atoi(token);\n if (num <= 0) {\n valid = 0;\n break;\n }\n \n if (count > 0) {\n strcat(options, \",\");\n }\n strcat(options, token);\n count++;\n token = strtok(NULL, \" \");\n }\n\n if (valid && count > 0) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigTimeOptions(options);\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd,\n GetLocalizedString(\n L\"请输入用空格分隔的数字\\n\"\n L\"例如: 25 10 5\",\n L\"Enter numbers separated by spaces\\n\"\n L\"Example: 25 10 5\"),\n GetLocalizedString(L\"无效输入\", L\"Invalid Input\"), \n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_MODIFY_DEFAULT_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_STARTUP_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_STARTUP_DIALOG);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case 200: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // First, stop all timers to ensure no timer events will be processed\n KillTimer(hwnd, 1);\n \n // Unregister all global hotkeys to ensure they don't remain active after reset\n UnregisterGlobalHotkeys(hwnd);\n \n // Fully reset timer state - critical part\n // Import all timer state variables that need to be reset\n extern int elapsed_time; // from main.c\n extern int countdown_elapsed_time; // from timer.c\n extern int countup_elapsed_time; // from timer.c\n extern BOOL message_shown; // from main.c \n extern BOOL countdown_message_shown;// from timer.c\n extern BOOL countup_message_shown; // from timer.c\n \n // Import high-precision timer initialization function from timer.c\n extern BOOL InitializeHighPrecisionTimer(void);\n extern void ResetTimer(void); // Use a dedicated reset function\n extern void ReadNotificationMessagesConfig(void); // Read notification message configuration\n \n // Reset all timer state variables - order matters!\n CLOCK_TOTAL_TIME = 25 * 60; // 1. First set total time to 25 minutes\n elapsed_time = 0; // 2. Reset elapsed_time in main.c\n countdown_elapsed_time = 0; // 3. Reset countdown_elapsed_time in timer.c\n countup_elapsed_time = 0; // 4. Reset countup_elapsed_time in timer.c\n message_shown = FALSE; // 5. Reset message status\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set timer state to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Call the dedicated timer reset function - this is crucial!\n // This function reinitializes the high-precision timer and resets all timing states\n ResetTimer();\n \n // Reset UI state\n CLOCK_EDIT_MODE = FALSE;\n SetClickThrough(hwnd, TRUE);\n SendMessage(hwnd, WM_SETREDRAW, FALSE, 0);\n \n // Reset file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n \n // Default language initialization\n AppLanguage defaultLanguage;\n LANGID langId = GetUserDefaultUILanguage();\n WORD primaryLangId = PRIMARYLANGID(langId);\n WORD subLangId = SUBLANGID(langId);\n \n switch (primaryLangId) {\n case LANG_CHINESE:\n defaultLanguage = (subLangId == SUBLANG_CHINESE_SIMPLIFIED) ? \n APP_LANG_CHINESE_SIMP : APP_LANG_CHINESE_TRAD;\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n break;\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n break;\n }\n \n if (CURRENT_LANGUAGE != defaultLanguage) {\n CURRENT_LANGUAGE = defaultLanguage;\n }\n \n // Delete and recreate the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure the file is closed and deleted\n FILE* test = fopen(config_path, \"r\");\n if (test) {\n fclose(test);\n remove(config_path);\n }\n \n // Recreate default configuration\n CreateDefaultConfig(config_path);\n \n // Reread the configuration\n ReadConfig();\n \n // Ensure notification messages are reread\n ReadNotificationMessagesConfig();\n \n // Restore default font\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0) { \n LoadFontFromResource(hInstance, fontResources[i].resourceId);\n break;\n }\n }\n \n // Reset window scale\n CLOCK_WINDOW_SCALE = 1.0f;\n CLOCK_FONT_SCALE_FACTOR = 1.0f;\n \n // Recalculate window size\n HDC hdc = GetDC(hwnd);\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE, \n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, FONT_INTERNAL_NAME\n );\n HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);\n \n char time_text[50];\n FormatTime(CLOCK_TOTAL_TIME, time_text);\n SIZE textSize;\n GetTextExtentPoint32(hdc, time_text, strlen(time_text), &textSize);\n \n SelectObject(hdc, hOldFont);\n DeleteObject(hFont);\n ReleaseDC(hwnd, hdc);\n \n // Set default scale based on screen height\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n float defaultScale = (screenHeight * 0.03f) / 20.0f;\n CLOCK_WINDOW_SCALE = defaultScale;\n CLOCK_FONT_SCALE_FACTOR = defaultScale;\n \n // Reset window position\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n textSize.cx * defaultScale, textSize.cy * defaultScale,\n SWP_NOZORDER | SWP_NOACTIVATE\n );\n \n // Ensure window is visible\n ShowWindow(hwnd, SW_SHOW);\n \n // Restart the timer - ensure it's started after all states are reset\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n SendMessage(hwnd, WM_SETREDRAW, TRUE, 0);\n RedrawWindow(hwnd, NULL, NULL, \n RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);\n \n // Reregister default hotkeys\n RegisterGlobalHotkeys(hwnd);\n \n break;\n }\n case CLOCK_IDM_TIMER_PAUSE_RESUME: {\n PauseResumeTimer(hwnd);\n break;\n }\n case CLOCK_IDM_TIMER_RESTART: {\n // Close all notification windows\n CloseAllNotifications();\n RestartTimer(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE: {\n SetLanguage(APP_LANG_CHINESE_SIMP);\n WriteConfigLanguage(APP_LANG_CHINESE_SIMP);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE_TRAD: {\n SetLanguage(APP_LANG_CHINESE_TRAD);\n WriteConfigLanguage(APP_LANG_CHINESE_TRAD);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_ENGLISH: {\n SetLanguage(APP_LANG_ENGLISH);\n WriteConfigLanguage(APP_LANG_ENGLISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_SPANISH: {\n SetLanguage(APP_LANG_SPANISH);\n WriteConfigLanguage(APP_LANG_SPANISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_FRENCH: {\n SetLanguage(APP_LANG_FRENCH);\n WriteConfigLanguage(APP_LANG_FRENCH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_GERMAN: {\n SetLanguage(APP_LANG_GERMAN);\n WriteConfigLanguage(APP_LANG_GERMAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_RUSSIAN: {\n SetLanguage(APP_LANG_RUSSIAN);\n WriteConfigLanguage(APP_LANG_RUSSIAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_PORTUGUESE: {\n SetLanguage(APP_LANG_PORTUGUESE);\n WriteConfigLanguage(APP_LANG_PORTUGUESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_JAPANESE: {\n SetLanguage(APP_LANG_JAPANESE);\n WriteConfigLanguage(APP_LANG_JAPANESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_KOREAN: {\n SetLanguage(APP_LANG_KOREAN);\n WriteConfigLanguage(APP_LANG_KOREAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_ABOUT:\n ShowAboutDialog(hwnd);\n return 0;\n case CLOCK_IDM_TOPMOST: {\n // Toggle the topmost state in configuration\n BOOL newTopmost = !CLOCK_WINDOW_TOPMOST;\n \n // If in edit mode, just update the stored state but don't apply it yet\n if (CLOCK_EDIT_MODE) {\n // Update the configuration and saved state only\n PREVIOUS_TOPMOST_STATE = newTopmost;\n CLOCK_WINDOW_TOPMOST = newTopmost;\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n } else {\n // Not in edit mode, apply it immediately\n SetWindowTopmost(hwnd, newTopmost);\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n }\n break;\n }\n case CLOCK_IDM_COUNTDOWN_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = FALSE; // Switch to countdown mode\n }\n \n // Reset the countdown timer\n extern void ResetTimer(void);\n ResetTimer();\n \n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDC_EDIT_MODE: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n } else {\n StartEditMode(hwnd);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n case CLOCK_IDC_CUSTOMIZE_LEFT: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n char hex_color[10];\n snprintf(hex_color, sizeof(hex_color), \"#%02X%02X%02X\", \n GetRValue(color), GetGValue(color), GetBValue(color));\n WriteConfigColor(hex_color);\n ReadConfig();\n }\n break;\n }\n case CLOCK_IDC_FONT_RECMONO: {\n WriteConfigFont(\"RecMonoCasual Nerd Font Mono Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DEPARTURE: {\n WriteConfigFont(\"DepartureMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_TERMINESS: {\n WriteConfigFont(\"Terminess Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PINYON_SCRIPT: {\n WriteConfigFont(\"Pinyon Script Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ARBUTUS: {\n WriteConfigFont(\"Arbutus Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_BERKSHIRE: {\n WriteConfigFont(\"Berkshire Swash Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CAVEAT: {\n WriteConfigFont(\"Caveat Brush Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CREEPSTER: {\n WriteConfigFont(\"Creepster Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DOTO: { \n WriteConfigFont(\"Doto ExtraBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FOLDIT: {\n WriteConfigFont(\"Foldit SemiBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FREDERICKA: {\n WriteConfigFont(\"Fredericka the Great Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FRIJOLE: {\n WriteConfigFont(\"Frijole Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_GWENDOLYN: {\n WriteConfigFont(\"Gwendolyn Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_HANDJET: {\n WriteConfigFont(\"Handjet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_INKNUT: {\n WriteConfigFont(\"Inknut Antiqua Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARD: {\n WriteConfigFont(\"Jacquard 12 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARDA: {\n WriteConfigFont(\"Jacquarda Bastarda 9 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KAVOON: {\n WriteConfigFont(\"Kavoon Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE: {\n WriteConfigFont(\"Kumar One Outline Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE: {\n WriteConfigFont(\"Kumar One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LAKKI_REDDY: {\n WriteConfigFont(\"Lakki Reddy Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LICORICE: {\n WriteConfigFont(\"Licorice Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MA_SHAN_ZHENG: {\n WriteConfigFont(\"Ma Shan Zheng Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MOIRAI_ONE: {\n WriteConfigFont(\"Moirai One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MYSTERY_QUEST: {\n WriteConfigFont(\"Mystery Quest Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_NOTO_NASTALIQ: {\n WriteConfigFont(\"Noto Nastaliq Urdu Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIEDRA: {\n WriteConfigFont(\"Piedra Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIXELIFY: {\n WriteConfigFont(\"Pixelify Sans Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PRESS_START: {\n WriteConfigFont(\"Press Start 2P Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BUBBLES: {\n WriteConfigFont(\"Rubik Bubbles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BURNED: {\n WriteConfigFont(\"Rubik Burned Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_GLITCH: {\n WriteConfigFont(\"Rubik Glitch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_MARKER_HATCH: {\n WriteConfigFont(\"Rubik Marker Hatch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_PUDDLES: {\n WriteConfigFont(\"Rubik Puddles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_VINYL: {\n WriteConfigFont(\"Rubik Vinyl Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_WET_PAINT: {\n WriteConfigFont(\"Rubik Wet Paint Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUGE_BOOGIE: {\n WriteConfigFont(\"Ruge Boogie Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SEVILLANA: {\n WriteConfigFont(\"Sevillana Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SILKSCREEN: {\n WriteConfigFont(\"Silkscreen Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_STICK: {\n WriteConfigFont(\"Stick Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_UNDERDOG: {\n WriteConfigFont(\"Underdog Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_WALLPOET: {\n WriteConfigFont(\"Wallpoet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_YESTERYEAR: {\n WriteConfigFont(\"Yesteryear Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ZCOOL_KUAILE: {\n WriteConfigFont(\"ZCOOL KuaiLe Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PROFONT: {\n WriteConfigFont(\"ProFont IIx Nerd Font Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DADDYTIME: {\n WriteConfigFont(\"DaddyTimeMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDM_SHOW_CURRENT_TIME: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_SHOW_CURRENT_TIME = !CLOCK_SHOW_CURRENT_TIME;\n if (CLOCK_SHOW_CURRENT_TIME) {\n ShowWindow(hwnd, SW_SHOW); \n \n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1); \n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0; // Ensure total time is reset\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n SetTimer(hwnd, 1, 100, NULL); // Reduce interval to 100ms for higher refresh rate\n } else {\n KillTimer(hwnd, 1); \n // When canceling showing current time, fully reset state instead of restoring previous state\n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0;\n message_shown = 0; // Reset message shown state\n // Set timer with longer interval because second-level updates are no longer needed\n SetTimer(hwnd, 1, 1000, NULL); \n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_24HOUR_FORMAT: { \n CLOCK_USE_24HOUR = !CLOCK_USE_24HOUR;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_SHOW_SECONDS: { \n CLOCK_SHOW_SECONDS = !CLOCK_SHOW_SECONDS;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_RECENT_FILE_1:\n case CLOCK_IDM_RECENT_FILE_2:\n case CLOCK_IDM_RECENT_FILE_3:\n case CLOCK_IDM_RECENT_FILE_4:\n case CLOCK_IDM_RECENT_FILE_5: {\n int index = cmd - CLOCK_IDM_RECENT_FILE_1;\n if (index < CLOCK_RECENT_FILES_COUNT) {\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[index].path, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(CLOCK_RECENT_FILES[index].path);\n \n // Step 2: Update the recent files list (move this file to the top)\n SaveRecentFile(CLOCK_RECENT_FILES[index].path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n \n // Clear invalid file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n \n // Remove this file from the recent files list\n for (int i = index; i < CLOCK_RECENT_FILES_COUNT - 1; i++) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i + 1];\n }\n CLOCK_RECENT_FILES_COUNT--;\n \n // Update recent files list in the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n }\n }\n break;\n }\n case CLOCK_IDM_BROWSE_FILE: {\n wchar_t szFile[MAX_PATH] = {0};\n \n OPENFILENAMEW ofn = {0};\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile) / sizeof(wchar_t);\n ofn.lpstrFilter = L\"所有文件\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n \n if (GetOpenFileNameW(&ofn)) {\n // Convert wide character path to UTF-8 to save in the configuration file\n char utf8Path[MAX_PATH * 3] = {0}; // Larger buffer to accommodate UTF-8 encoding\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n \n if (GetFileAttributesW(szFile) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case CLOCK_IDC_TIMEOUT_BROWSE: {\n OPENFILENAMEW ofn;\n wchar_t szFile[MAX_PATH] = L\"\";\n \n ZeroMemory(&ofn, sizeof(ofn));\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile);\n ofn.lpstrFilter = L\"All Files (*.*)\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n\n if (GetOpenFileNameW(&ofn)) {\n char utf8Path[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, \n utf8Path, \n sizeof(utf8Path), \n NULL, NULL);\n \n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n }\n break;\n }\n case CLOCK_IDM_COUNT_UP: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_COUNT_UP = !CLOCK_COUNT_UP;\n if (CLOCK_COUNT_UP) {\n ShowWindow(hwnd, SW_SHOW);\n \n elapsed_time = 0;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (!CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = TRUE;\n \n // Ensure the timer starts from 0 every time it switches to count-up mode\n countup_elapsed_time = 0;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n } else {\n // Already in count-up mode, so toggle pause/run state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n // Reset the count-up counter\n extern void ResetTimer(void);\n ResetTimer();\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDC_SET_COUNTDOWN_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n \n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n \n CLOCK_DEFAULT_START_TIME = total_seconds;\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_START_SHOW_TIME: {\n WriteConfigStartupMode(\"SHOW_TIME\");\n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_CHECKED);\n break;\n }\n case CLOCK_IDC_START_COUNT_UP: {\n WriteConfigStartupMode(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDC_START_NO_DISPLAY: {\n WriteConfigStartupMode(\"NO_DISPLAY\");\n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n case CLOCK_IDC_AUTO_START: {\n BOOL isEnabled = IsAutoStartEnabled();\n if (isEnabled) {\n if (RemoveShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_UNCHECKED);\n }\n } else {\n if (CreateShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_CHECKED);\n }\n }\n break;\n }\n case CLOCK_IDC_COLOR_VALUE: {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_COLOR_DIALOG), \n hwnd, \n (DLGPROC)ColorDlgProc);\n break;\n }\n case CLOCK_IDC_COLOR_PANEL: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case CLOCK_IDM_POMODORO_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n if (!IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_SHOW);\n }\n \n // Reset timer state\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // Set work time\n CLOCK_TOTAL_TIME = POMODORO_WORK_TIME;\n \n // Initialize Pomodoro phase\n extern void InitializePomodoro(void);\n InitializePomodoro();\n \n // Save original timeout action\n TimeoutActionType originalAction = CLOCK_TIMEOUT_ACTION;\n \n // Force set to show message\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n \n // Start the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Reset message state\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_POMODORO_WORK:\n case CLOCK_IDM_POMODORO_BREAK:\n case CLOCK_IDM_POMODORO_LBREAK:\n // Keep original menu item ID handling\n {\n int selectedIndex = 0;\n if (LOWORD(wp) == CLOCK_IDM_POMODORO_WORK) {\n selectedIndex = 0;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_BREAK) {\n selectedIndex = 1;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_LBREAK) {\n selectedIndex = 2;\n }\n \n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n break;\n\n // Also handle new dynamic ID range\n case 600: case 601: case 602: case 603: case 604:\n case 605: case 606: case 607: case 608: case 609:\n // Handle Pomodoro time setting options (dynamic ID range)\n {\n // Calculate the selected option index\n int selectedIndex = LOWORD(wp) - CLOCK_IDM_POMODORO_TIME_BASE;\n \n if (selectedIndex >= 0 && selectedIndex < POMODORO_TIMES_COUNT) {\n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n }\n break;\n case CLOCK_IDM_POMODORO_LOOP_COUNT:\n ShowPomodoroLoopDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Call ResetTimer to reset the timer state\n extern void ResetTimer(void);\n ResetTimer();\n \n // If currently in Pomodoro mode, reset related states\n if (CLOCK_TOTAL_TIME == POMODORO_WORK_TIME || \n CLOCK_TOTAL_TIME == POMODORO_SHORT_BREAK || \n CLOCK_TOTAL_TIME == POMODORO_LONG_BREAK) {\n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDM_TIMEOUT_SHOW_TIME: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n WriteConfigTimeoutAction(\"SHOW_TIME\");\n break;\n }\n case CLOCK_IDM_TIMEOUT_COUNT_UP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n WriteConfigTimeoutAction(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDM_SHOW_MESSAGE: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n break;\n }\n case CLOCK_IDM_LOCK_SCREEN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n WriteConfigTimeoutAction(\"LOCK\");\n break;\n }\n case CLOCK_IDM_SHUTDOWN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHUTDOWN;\n WriteConfigTimeoutAction(\"SHUTDOWN\");\n break;\n }\n case CLOCK_IDM_RESTART: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RESTART;\n WriteConfigTimeoutAction(\"RESTART\");\n break;\n }\n case CLOCK_IDM_SLEEP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n WriteConfigTimeoutAction(\"SLEEP\");\n break;\n }\n case CLOCK_IDM_RUN_COMMAND: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n WriteConfigTimeoutAction(\"RUN_COMMAND\");\n break;\n }\n case CLOCK_IDM_HTTP_REQUEST: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n WriteConfigTimeoutAction(\"HTTP_REQUEST\");\n break;\n }\n case CLOCK_IDM_CHECK_UPDATE: {\n // Call async update check function - non-silent mode\n CheckForUpdateAsync(hwnd, FALSE);\n break;\n }\n case CLOCK_IDM_OPEN_WEBSITE:\n // Don't set action type immediately, wait for dialog result\n ShowWebsiteDialog(hwnd);\n break;\n \n case CLOCK_IDM_CURRENT_WEBSITE:\n ShowWebsiteDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_COMBINATION:\n ShowPomodoroComboDialog(hwnd);\n break;\n case CLOCK_IDM_NOTIFICATION_CONTENT: {\n ShowNotificationMessagesDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_DISPLAY: {\n ShowNotificationDisplayDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_SETTINGS: {\n ShowNotificationSettingsDialog(hwnd);\n break;\n }\n case CLOCK_IDM_HOTKEY_SETTINGS: {\n ShowHotkeySettingsDialog(hwnd);\n // Register/reregister global hotkeys\n RegisterGlobalHotkeys(hwnd);\n break;\n }\n case CLOCK_IDM_HELP: {\n OpenUserGuide();\n break;\n }\n case CLOCK_IDM_SUPPORT: {\n OpenSupportPage();\n break;\n }\n case CLOCK_IDM_FEEDBACK: {\n OpenFeedbackPage();\n break;\n }\n }\n break;\n\nrefresh_window:\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case WM_WINDOWPOSCHANGED: {\n if (CLOCK_EDIT_MODE) {\n SaveWindowSettings(hwnd);\n }\n break;\n }\n case WM_RBUTTONUP: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_MEASUREITEM:\n {\n LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT)lp;\n if (lpmis->CtlType == ODT_MENU) {\n lpmis->itemHeight = 25;\n lpmis->itemWidth = 100;\n return TRUE;\n }\n return FALSE;\n }\n case WM_DRAWITEM:\n {\n LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT)lp;\n if (lpdis->CtlType == ODT_MENU) {\n int colorIndex = lpdis->itemID - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n const char* hexColor = COLOR_OPTIONS[colorIndex].hexColor;\n int r, g, b;\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n \n HBRUSH hBrush = CreateSolidBrush(RGB(r, g, b));\n HPEN hPen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n \n HGDIOBJ oldBrush = SelectObject(lpdis->hDC, hBrush);\n HGDIOBJ oldPen = SelectObject(lpdis->hDC, hPen);\n \n Rectangle(lpdis->hDC, lpdis->rcItem.left, lpdis->rcItem.top,\n lpdis->rcItem.right, lpdis->rcItem.bottom);\n \n SelectObject(lpdis->hDC, oldPen);\n SelectObject(lpdis->hDC, oldBrush);\n DeleteObject(hPen);\n DeleteObject(hBrush);\n \n if (lpdis->itemState & ODS_SELECTED) {\n DrawFocusRect(lpdis->hDC, &lpdis->rcItem);\n }\n \n return TRUE;\n }\n }\n return FALSE;\n }\n case WM_MENUSELECT: {\n UINT menuItem = LOWORD(wp);\n UINT flags = HIWORD(wp);\n HMENU hMenu = (HMENU)lp;\n\n if (!(flags & MF_POPUP) && hMenu != NULL) {\n int colorIndex = menuItem - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n strncpy(PREVIEW_COLOR, COLOR_OPTIONS[colorIndex].hexColor, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (fontResources[i].menuId == menuItem) {\n strncpy(PREVIEW_FONT_NAME, fontResources[i].fontName, 99);\n PREVIEW_FONT_NAME[99] = '\\0';\n \n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, 99);\n PREVIEW_INTERNAL_NAME[99] = '\\0';\n char* dot = strrchr(PREVIEW_INTERNAL_NAME, '.');\n if (dot) *dot = '\\0';\n \n LoadFontByName((HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), \n fontResources[i].fontName);\n \n IS_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n \n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n } else if (flags & MF_POPUP) {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n break;\n }\n case WM_EXITMENULOOP: {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case WM_RBUTTONDOWN: {\n if (GetKeyState(VK_CONTROL) & 0x8000) {\n // Toggle edit mode\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Entering edit mode\n SetClickThrough(hwnd, FALSE);\n } else {\n // Exiting edit mode\n SetClickThrough(hwnd, TRUE);\n SaveWindowSettings(hwnd); // Save settings when exiting edit mode\n WriteConfigColor(CLOCK_TEXT_COLOR); // Save the current color to config\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n break;\n }\n case WM_CLOSE: {\n SaveWindowSettings(hwnd); // Save window settings before closing\n DestroyWindow(hwnd); // Close the window\n break;\n }\n case WM_LBUTTONDBLCLK: {\n if (!CLOCK_EDIT_MODE) {\n // Enter edit mode\n StartEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_HOTKEY: {\n // WM_HOTKEY message's lp contains key information\n if (wp == HOTKEY_ID_SHOW_TIME) {\n ToggleShowTimeMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNT_UP) {\n StartCountUp(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNTDOWN) {\n StartDefaultCountDown(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_CUSTOM_COUNTDOWN) {\n // Check if the input dialog already exists\n if (g_hwndInputDialog != NULL && IsWindow(g_hwndInputDialog)) {\n // The dialog already exists, close it\n SendMessage(g_hwndInputDialog, WM_CLOSE, 0, 0);\n return 0;\n }\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Show input dialog to set countdown\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Clear input text\n memset(inputText, 0, sizeof(inputText));\n \n // Show input dialog\n INT_PTR result = DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), \n hwnd, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n \n // If the dialog has input and was confirmed\n if (inputText[0] != '\\0') {\n // Check if input is valid\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Set countdown state\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n \n // Switch to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Stop and restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN1) {\n // Start quick countdown 1\n StartQuickCountdown1(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN2) {\n // Start quick countdown 2\n StartQuickCountdown2(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN3) {\n // Start quick countdown 3\n StartQuickCountdown3(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_POMODORO) {\n // Start Pomodoro timer\n StartPomodoroTimer(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_TOGGLE_VISIBILITY) {\n // Hide/show window\n if (IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_HIDE);\n } else {\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n }\n return 0;\n } else if (wp == HOTKEY_ID_EDIT_MODE) {\n // Enter edit mode\n ToggleEditMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_PAUSE_RESUME) {\n // Pause/resume timer\n TogglePauseResume(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_RESTART_TIMER) {\n // Close all notification windows\n CloseAllNotifications();\n // Restart current timer\n RestartCurrentTimer(hwnd);\n return 0;\n }\n break;\n }\n // Handle reregistration message after hotkey settings change\n case WM_APP+1: {\n // Only reregister hotkeys, do not open dialog\n RegisterGlobalHotkeys(hwnd);\n return 0;\n }\n default:\n return DefWindowProc(hwnd, msg, wp, lp);\n }\n return 0;\n}\n\n// External variable declarations\nextern int CLOCK_DEFAULT_START_TIME;\nextern int countdown_elapsed_time;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern int CLOCK_TOTAL_TIME;\n\n// Remove menu items\nvoid RemoveMenuItems(HMENU hMenu, int count);\n\n// Add menu item\nvoid AddMenuItem(HMENU hMenu, UINT id, const char* text, BOOL isEnabled);\n\n// Modify menu item text\nvoid ModifyMenuItemText(HMENU hMenu, UINT id, const char* text);\n\n/**\n * @brief Toggle show current time mode\n * @param hwnd Window handle\n */\nvoid ToggleShowTimeMode(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // If not currently in show current time mode, then enable it\n // If already in show current time mode, do nothing (don't turn it off)\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Switch to show current time mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n \n // Reset the timer to ensure the update frequency is correct\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 100, NULL); // Use 100ms update frequency to keep the time display smooth\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n }\n // Already in show current time mode, do nothing\n}\n\n/**\n * @brief Start count up timer\n * @param hwnd Window handle\n */\nvoid StartCountUp(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Declare external variables\n extern int countup_elapsed_time;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Reset count up counter\n countup_elapsed_time = 0;\n \n // Set to count up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start default countdown\n * @param hwnd Window handle\n */\nvoid StartDefaultCountDown(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Set mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n if (CLOCK_DEFAULT_START_TIME > 0) {\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n } else {\n // If no default countdown is set, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, 101, 0);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start Pomodoro timer\n * @param hwnd Window handle\n */\nvoid StartPomodoroTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // If it was previously in show current time mode, stop the old timer\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n }\n \n // Use the Pomodoro menu item command to start the Pomodoro timer\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDM_POMODORO_START, 0);\n}\n\n/**\n * @brief Toggle edit mode\n * @param hwnd Window handle\n */\nvoid ToggleEditMode(HWND hwnd) {\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Record the current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If not currently topmost, set it to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure the window is visible and in the foreground\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n } else {\n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, TRUE);\n \n // If it was not topmost before, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Save window settings and color settings\n SaveWindowSettings(hwnd);\n WriteConfigColor(CLOCK_TEXT_COLOR);\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Pause/resume timer\n * @param hwnd Window handle\n */\nvoid TogglePauseResume(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart the current timer\n * @param hwnd Window handle\n */\nvoid RestartCurrentTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Variables imported from main.c\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Reset message shown state to allow notification and sound to be played again when timer ends\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n if (CLOCK_COUNT_UP) {\n // Reset count up timer\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else {\n // Reset countdown timer\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n }\n CLOCK_IS_PAUSED = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Start quick countdown 1\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown1(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there is at least one preset time option\n if (time_options_count > 0) {\n CLOCK_TOTAL_TIME = time_options[0] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are no preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 2\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown2(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least two preset time options\n if (time_options_count > 1) {\n CLOCK_TOTAL_TIME = time_options[1] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 3\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown3(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least three preset time options\n if (time_options_count > 2) {\n CLOCK_TOTAL_TIME = time_options[2] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n"], ["/Catime/src/notification.c", "/**\n * @file notification.c\n * @brief Application notification system implementation\n * \n * This module implements various notification functions of the application, including:\n * 1. Custom styled popup notification windows with fade-in/fade-out animation effects\n * 2. System tray notification message integration\n * 3. Creation, display and lifecycle management of notification windows\n * \n * The notification system supports UTF-8 encoded Chinese text to ensure correct display in multilingual environments.\n */\n\n#include \n#include \n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\" // Contains definitions of all IDs and constants\n#include // For GET_X_LPARAM and GET_Y_LPARAM macros\n\n// Imported from config.h\n// New: notification type configuration\nextern NotificationType NOTIFICATION_TYPE;\n\n/**\n * Notification window animation state enumeration\n * Tracks the current animation phase of the notification window\n */\ntypedef enum {\n ANIM_FADE_IN, // Fade-in phase - opacity increases from 0 to target value\n ANIM_VISIBLE, // Fully visible phase - maintains maximum opacity\n ANIM_FADE_OUT, // Fade-out phase - opacity decreases from maximum to 0\n} AnimationState;\n\n// Forward declarations\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid RegisterNotificationClass(HINSTANCE hInstance);\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius);\n\n/**\n * @brief Calculate the width required for text rendering\n * @param hdc Device context\n * @param text Text to measure\n * @param font Font to use\n * @return int Width required for text rendering (pixels)\n */\nint CalculateTextWidth(HDC hdc, const wchar_t* text, HFONT font) {\n HFONT oldFont = (HFONT)SelectObject(hdc, font);\n SIZE textSize;\n GetTextExtentPoint32W(hdc, text, wcslen(text), &textSize);\n SelectObject(hdc, oldFont);\n return textSize.cx;\n}\n\n/**\n * @brief Show notification (based on configured notification type)\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays different styles of notifications based on the configured notification type\n */\nvoid ShowNotification(HWND hwnd, const char* message) {\n // Read the latest notification type configuration\n ReadNotificationTypeConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Choose the corresponding notification method based on notification type\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n ShowToastNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n ShowModalNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_OS:\n ShowTrayNotification(hwnd, message);\n break;\n default:\n // Default to using Catime notification window\n ShowToastNotification(hwnd, message);\n break;\n }\n}\n\n/**\n * Modal dialog thread parameter structure\n */\ntypedef struct {\n HWND hwnd; // Parent window handle\n char message[512]; // Message content\n} DialogThreadParams;\n\n/**\n * @brief Thread function to display modal dialog\n * @param lpParam Thread parameter, pointer to DialogThreadParams structure\n * @return DWORD Thread return value\n */\nDWORD WINAPI ShowModalDialogThread(LPVOID lpParam) {\n DialogThreadParams* params = (DialogThreadParams*)lpParam;\n \n // Convert UTF-8 message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, params->message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, display English version directly\n MessageBoxA(params->hwnd, params->message, \"Catime\", MB_OK);\n free(params);\n return 0;\n }\n \n MultiByteToWideChar(CP_UTF8, 0, params->message, -1, wmessage, wlen);\n \n // Display modal dialog with fixed title \"Catime\"\n MessageBoxW(params->hwnd, wmessage, L\"Catime\", MB_OK);\n \n // Free allocated memory\n free(wmessage);\n free(params);\n \n return 0;\n}\n\n/**\n * @brief Display system modal dialog notification\n * @param hwnd Parent window handle\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a modal dialog in a separate thread, which won't block the main program\n */\nvoid ShowModalNotification(HWND hwnd, const char* message) {\n // Create thread parameter structure\n DialogThreadParams* params = (DialogThreadParams*)malloc(sizeof(DialogThreadParams));\n if (!params) return;\n \n // Copy parameters\n params->hwnd = hwnd;\n strncpy(params->message, message, sizeof(params->message) - 1);\n params->message[sizeof(params->message) - 1] = '\\0';\n \n // Create new thread to display dialog\n HANDLE hThread = CreateThread(\n NULL, // Default security attributes\n 0, // Default stack size\n ShowModalDialogThread, // Thread function\n params, // Thread parameter\n 0, // Run thread immediately\n NULL // Don't receive thread ID\n );\n \n // If thread creation fails, free resources\n if (hThread == NULL) {\n free(params);\n // Fall back to non-blocking notification method\n MessageBeep(MB_OK);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Close thread handle, let system clean up automatically\n CloseHandle(hThread);\n}\n\n/**\n * @brief Display custom styled toast notification\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a custom notification window with animation effects in the bottom right corner of the screen:\n * 1. Register notification window class (if needed)\n * 2. Calculate notification display position (bottom right of work area)\n * 3. Create notification window with fade-in/fade-out effects\n * 4. Set auto-close timer\n * \n * Note: If creating custom notification window fails, will fall back to using system tray notification\n */\nvoid ShowToastNotification(HWND hwnd, const char* message) {\n static BOOL isClassRegistered = FALSE;\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n \n // Dynamically read the latest notification settings before displaying notification\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Register notification window class (if not already registered)\n if (!isClassRegistered) {\n RegisterNotificationClass(hInstance);\n isClassRegistered = TRUE;\n }\n \n // Convert message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, fall back to system tray notification\n ShowTrayNotification(hwnd, message);\n return;\n }\n MultiByteToWideChar(CP_UTF8, 0, message, -1, wmessage, wlen);\n \n // Calculate width needed for text\n HDC hdc = GetDC(hwnd);\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Calculate text width and add margins\n int textWidth = CalculateTextWidth(hdc, wmessage, contentFont);\n int notificationWidth = textWidth + 40; // 20 pixel margin on each side\n \n // Ensure width is within allowed range\n if (notificationWidth < NOTIFICATION_MIN_WIDTH) \n notificationWidth = NOTIFICATION_MIN_WIDTH;\n if (notificationWidth > NOTIFICATION_MAX_WIDTH) \n notificationWidth = NOTIFICATION_MAX_WIDTH;\n \n DeleteObject(contentFont);\n ReleaseDC(hwnd, hdc);\n \n // Get work area size, calculate notification window position (bottom right)\n RECT workArea;\n SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);\n \n int x = workArea.right - notificationWidth - 20;\n int y = workArea.bottom - NOTIFICATION_HEIGHT - 20;\n \n // Create notification window, add layered support for transparency effects\n HWND hNotification = CreateWindowExW(\n WS_EX_TOPMOST | WS_EX_LAYERED | WS_EX_TOOLWINDOW, // Keep on top and hide from taskbar\n NOTIFICATION_CLASS_NAME,\n L\"Catime Notification\", // Window title (not visible)\n WS_POPUP, // Borderless popup window style\n x, y, // Bottom right screen position\n notificationWidth, NOTIFICATION_HEIGHT,\n NULL, NULL, hInstance, NULL\n );\n \n // Fall back to system tray notification if creation fails\n if (!hNotification) {\n free(wmessage);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Save message text and window width to window properties\n SetPropW(hNotification, L\"MessageText\", (HANDLE)wmessage);\n SetPropW(hNotification, L\"WindowWidth\", (HANDLE)(LONG_PTR)notificationWidth);\n \n // Set initial animation state to fade-in\n SetPropW(hNotification, L\"AnimState\", (HANDLE)ANIM_FADE_IN);\n SetPropW(hNotification, L\"Opacity\", (HANDLE)0); // Initial opacity is 0\n \n // Set initial window to completely transparent\n SetLayeredWindowAttributes(hNotification, 0, 0, LWA_ALPHA);\n \n // Show window but don't activate (don't steal focus)\n ShowWindow(hNotification, SW_SHOWNOACTIVATE);\n UpdateWindow(hNotification);\n \n // Start fade-in animation\n SetTimer(hNotification, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n \n // Set auto-close timer, using globally configured timeout\n SetTimer(hNotification, NOTIFICATION_TIMER_ID, NOTIFICATION_TIMEOUT_MS, NULL);\n}\n\n/**\n * @brief Register notification window class\n * @param hInstance Application instance handle\n * \n * Registers custom notification window class with Windows, defining basic behavior and appearance:\n * 1. Set window procedure function\n * 2. Define default cursor and background\n * 3. Specify unique window class name\n * \n * This function is only called the first time a notification is displayed, subsequent calls reuse the registered class.\n */\nvoid RegisterNotificationClass(HINSTANCE hInstance) {\n WNDCLASSEXW wc = {0};\n wc.cbSize = sizeof(WNDCLASSEXW);\n wc.lpfnWndProc = NotificationWndProc;\n wc.hInstance = hInstance;\n wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n wc.lpszClassName = NOTIFICATION_CLASS_NAME;\n \n RegisterClassExW(&wc);\n}\n\n/**\n * @brief Notification window message processing procedure\n * @param hwnd Window handle\n * @param msg Message ID\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return LRESULT Message processing result\n * \n * Handles all Windows messages for the notification window, including:\n * - WM_PAINT: Draw notification window content (title, message text)\n * - WM_TIMER: Handle auto-close and animation effects\n * - WM_LBUTTONDOWN: Handle user click to close\n * - WM_DESTROY: Release window resources\n * \n * Specifically handles animation state transition logic to ensure smooth fade-in/fade-out effects.\n */\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_PAINT: {\n PAINTSTRUCT ps;\n HDC hdc = BeginPaint(hwnd, &ps);\n \n // Get window client area size\n RECT clientRect;\n GetClientRect(hwnd, &clientRect);\n \n // Create compatible DC and bitmap for double-buffered drawing to avoid flickering\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, clientRect.right, clientRect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n \n // Fill white background\n HBRUSH whiteBrush = CreateSolidBrush(RGB(255, 255, 255));\n FillRect(memDC, &clientRect, whiteBrush);\n DeleteObject(whiteBrush);\n \n // Draw rectangle with border\n DrawRoundedRectangle(memDC, clientRect, 0);\n \n // Set text drawing mode to transparent background\n SetBkMode(memDC, TRANSPARENT);\n \n // Create title font - bold\n HFONT titleFont = CreateFontW(22, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Create message content font\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Draw title \"Catime\"\n SelectObject(memDC, titleFont);\n SetTextColor(memDC, RGB(0, 0, 0));\n RECT titleRect = {15, 10, clientRect.right - 15, 35};\n DrawTextW(memDC, L\"Catime\", -1, &titleRect, DT_SINGLELINE);\n \n // Draw message content - placed below title, using single line mode\n SelectObject(memDC, contentFont);\n SetTextColor(memDC, RGB(100, 100, 100));\n const wchar_t* message = (const wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n RECT textRect = {15, 35, clientRect.right - 15, clientRect.bottom - 10};\n // Use DT_SINGLELINE|DT_END_ELLIPSIS to ensure text is displayed in one line, with ellipsis for long text\n DrawTextW(memDC, message, -1, &textRect, DT_SINGLELINE|DT_END_ELLIPSIS);\n }\n \n // Copy content from memory DC to window DC\n BitBlt(hdc, 0, 0, clientRect.right, clientRect.bottom, memDC, 0, 0, SRCCOPY);\n \n // Clean up resources\n SelectObject(memDC, oldBitmap);\n DeleteObject(titleFont);\n DeleteObject(contentFont);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n \n EndPaint(hwnd, &ps);\n return 0;\n }\n \n case WM_TIMER:\n if (wParam == NOTIFICATION_TIMER_ID) {\n // Auto-close timer triggered, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // Check current state - only start fade-out when fully visible\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState == ANIM_VISIBLE) {\n // Set to fade-out state\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start animation timer\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n return 0;\n }\n else if (wParam == ANIMATION_TIMER_ID) {\n // Handle animation effect timer\n AnimationState state = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n DWORD opacityVal = (DWORD)(DWORD_PTR)GetPropW(hwnd, L\"Opacity\");\n BYTE opacity = (BYTE)opacityVal;\n \n // Calculate maximum opacity value (percentage converted to 0-255 range)\n BYTE maxOpacity = (BYTE)((NOTIFICATION_MAX_OPACITY * 255) / 100);\n \n switch (state) {\n case ANIM_FADE_IN:\n // Fade-in animation - gradually increase opacity\n if (opacity >= maxOpacity - ANIMATION_STEP) {\n // Reached maximum opacity, completed fade-in\n opacity = maxOpacity;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n \n // Switch to visible state and stop animation\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_VISIBLE);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n } else {\n // Normal fade-in - increase by one step each time\n opacity += ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_FADE_OUT:\n // Fade-out animation - gradually decrease opacity\n if (opacity <= ANIMATION_STEP) {\n // Completely transparent, destroy window\n KillTimer(hwnd, ANIMATION_TIMER_ID); // Make sure to stop timer first\n DestroyWindow(hwnd);\n } else {\n // Normal fade-out - decrease by one step each time\n opacity -= ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_VISIBLE:\n // Fully visible state doesn't need animation, stop timer\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n break;\n }\n return 0;\n }\n break;\n \n case WM_LBUTTONDOWN: {\n // Handle left mouse button click event (close notification early)\n \n // Get current state - only respond to clicks when fully visible or after fade-in completes\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState != ANIM_VISIBLE) {\n return 0; // Ignore click, avoid interference during animation\n }\n \n // Click anywhere, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID); // Stop auto-close timer\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n return 0;\n }\n \n case WM_DESTROY: {\n // Cleanup work when window is destroyed\n \n // Stop all timers\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n \n // Free message text memory\n wchar_t* message = (wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n free(message);\n }\n \n // Remove all window properties\n RemovePropW(hwnd, L\"MessageText\");\n RemovePropW(hwnd, L\"AnimState\");\n RemovePropW(hwnd, L\"Opacity\");\n return 0;\n }\n }\n \n return DefWindowProc(hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Draw rectangle with border\n * @param hdc Device context\n * @param rect Rectangle area\n * @param radius Corner radius (unused)\n * \n * Draws a rectangle with light gray border in the specified device context.\n * This function reserves the corner radius parameter, but current implementation uses standard rectangle.\n * Can be extended to support true rounded rectangles in future versions.\n */\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius) {\n // Create light gray border pen\n HPEN pen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n HPEN oldPen = (HPEN)SelectObject(hdc, pen);\n \n // Use normal rectangle instead of rounded rectangle\n Rectangle(hdc, rect.left, rect.top, rect.right, rect.bottom);\n \n // Clean up resources\n SelectObject(hdc, oldPen);\n DeleteObject(pen);\n}\n\n/**\n * @brief Close all currently displayed Catime notification windows\n * \n * Find and close all notification windows created by Catime, ignoring their current display time settings,\n * directly start fade-out animation. Usually called when switching timer modes to ensure notifications don't continue to display.\n */\nvoid CloseAllNotifications(void) {\n // Find all notification windows created by Catime\n HWND hwnd = NULL;\n HWND hwndPrev = NULL;\n \n // Use FindWindowExW to find each matching window one by one\n // First call with hwndPrev as NULL finds the first window\n // Subsequent calls pass the previously found window handle to find the next window\n while ((hwnd = FindWindowExW(NULL, hwndPrev, NOTIFICATION_CLASS_NAME, NULL)) != NULL) {\n // Check current state\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n \n // Stop current auto-close timer\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // If window hasn't started fading out yet, start fade-out animation\n if (currentState != ANIM_FADE_OUT) {\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start fade-out animation\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n \n // Save current window handle for next search\n hwndPrev = hwnd;\n }\n}\n"], ["/Catime/src/dialog_procedure.c", "/**\n * @file dialog_procedure.c\n * @brief Implementation of dialog message handling procedures\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/audio_player.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/dialog_language.h\"\n\nstatic void DrawColorSelectButton(HDC hdc, HWND hwnd);\n\nextern char inputText[256];\n\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES];\nextern int POMODORO_TIMES_COUNT;\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nWNDPROC wpOrigEditProc;\n\nstatic HWND g_hwndAboutDlg = NULL;\nstatic HWND g_hwndErrorDlg = NULL;\nHWND g_hwndInputDialog = NULL;\nstatic WNDPROC wpOrigLoopEditProc;\n\n#define URL_GITHUB_REPO L\"https://github.com/vladelaina/Catime\"\n\nLRESULT APIENTRY EditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n static BOOL firstKeyProcessed = FALSE;\n\n switch (msg) {\n case WM_SETFOCUS:\n PostMessage(hwnd, EM_SETSEL, 0, -1);\n firstKeyProcessed = FALSE;\n break;\n\n case WM_KEYDOWN:\n if (!firstKeyProcessed) {\n firstKeyProcessed = TRUE;\n }\n\n if (wParam == VK_RETURN) {\n HWND hwndOkButton = GetDlgItem(GetParent(hwnd), CLOCK_IDC_BUTTON_OK);\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwndOkButton);\n return 0;\n }\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n\n case WM_CHAR:\n if (wParam == 1 || (wParam == 'a' || wParam == 'A') && GetKeyState(VK_CONTROL) < 0) {\n return 0;\n }\n if (wParam == VK_RETURN) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(wpOrigEditProc, hwnd, msg, wParam, lParam);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\nvoid ShowErrorDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDD_ERROR_DIALOG),\n hwndParent,\n ErrorDlgProc);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG:\n SetDlgItemTextW(hwndDlg, IDC_ERROR_TEXT,\n GetLocalizedString(L\"输入格式无效,请重新输入。\", L\"Invalid input format, please try again.\"));\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"错误\", L\"Error\"));\n return TRUE;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Input dialog procedure\n */\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n\n g_hwndInputDialog = hwndDlg;\n\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n DWORD dlgId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n\n ApplyDialogLanguage(hwndDlg, (int)dlgId);\n\n if (dlgId == CLOCK_IDD_SHORTCUT_DIALOG) {\n }\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n\n SetFocus(hwndEdit);\n\n PostMessage(hwndDlg, WM_APP+100, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+101, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+102, 0, (LPARAM)hwndEdit);\n\n SendDlgItemMessage(hwndDlg, CLOCK_IDC_EDIT, EM_SETSEL, 0, -1);\n\n SendMessage(hwndDlg, DM_SETDEFID, CLOCK_IDC_BUTTON_OK, 0);\n\n SetTimer(hwndDlg, 9999, 50, NULL);\n\n PostMessage(hwndDlg, WM_APP+103, 0, 0);\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return FALSE;\n }\n\n case WM_CLOSE: {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n\n case WM_CTLCOLOREDIT: {\n HDC hdcEdit = (HDC)wParam;\n SetBkColor(hdcEdit, RGB(0xFF, 0xFF, 0xFF));\n if (!hEditBrush) {\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n }\n return (INT_PTR)hEditBrush;\n }\n\n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, inputText, sizeof(inputText));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (inputText[0] == '\\0' || isAllSpaces) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n int total_seconds;\n if (ParseInput(inputText, &total_seconds)) {\n int dialogId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n if (dialogId == CLOCK_IDD_POMODORO_TIME_DIALOG) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_POMODORO_LOOP_DIALOG) {\n WriteConfigPomodoroLoopCount(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_STARTUP_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_SHORTCUT_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n }\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n return TRUE;\n }\n break;\n\n case WM_TIMER:\n if (wParam == 9999) {\n KillTimer(hwndDlg, 9999);\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit && IsWindow(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n return TRUE;\n }\n break;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n int dlgId = GetDlgCtrlID((HWND)lParam);\n if (dlgId == CLOCK_IDD_COLOR_DIALOG) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n } else {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n }\n return TRUE;\n }\n break;\n\n case WM_APP+100:\n case WM_APP+101:\n case WM_APP+102:\n if (lParam) {\n HWND hwndEdit = (HWND)lParam;\n if (IsWindow(hwndEdit) && IsWindowVisible(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n }\n return TRUE;\n\n case WM_APP+103:\n {\n INPUT inputs[8] = {0};\n int inputCount = 0;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n SendInput(inputCount, inputs, sizeof(INPUT));\n }\n return TRUE;\n\n case WM_DESTROY:\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n g_hwndInputDialog = NULL;\n }\n break;\n }\n return FALSE;\n}\n\nINT_PTR CALLBACK AboutDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HICON hLargeIcon = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n hLargeIcon = (HICON)LoadImage(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDI_CATIME),\n IMAGE_ICON,\n ABOUT_ICON_SIZE,\n ABOUT_ICON_SIZE,\n LR_DEFAULTCOLOR);\n\n if (hLargeIcon) {\n SendDlgItemMessage(hwndDlg, IDC_ABOUT_ICON, STM_SETICON, (WPARAM)hLargeIcon, 0);\n }\n\n ApplyDialogLanguage(hwndDlg, IDD_ABOUT_DIALOG);\n\n const wchar_t* versionFormat = GetDialogLocalizedString(IDD_ABOUT_DIALOG, IDC_VERSION_TEXT);\n if (versionFormat) {\n wchar_t versionText[256];\n StringCbPrintfW(versionText, sizeof(versionText), versionFormat, CATIME_VERSION);\n SetDlgItemTextW(hwndDlg, IDC_VERSION_TEXT, versionText);\n }\n\n SetDlgItemTextW(hwndDlg, IDC_CREDIT_LINK, GetLocalizedString(L\"特别感谢猫屋敷梨梨Official提供的图标\", L\"Special thanks to Neko House Lili Official for the icon\"));\n SetDlgItemTextW(hwndDlg, IDC_CREDITS, GetLocalizedString(L\"鸣谢\", L\"Credits\"));\n SetDlgItemTextW(hwndDlg, IDC_BILIBILI_LINK, GetLocalizedString(L\"BiliBili\", L\"BiliBili\"));\n SetDlgItemTextW(hwndDlg, IDC_GITHUB_LINK, GetLocalizedString(L\"GitHub\", L\"GitHub\"));\n SetDlgItemTextW(hwndDlg, IDC_COPYRIGHT_LINK, GetLocalizedString(L\"版权声明\", L\"Copyright Notice\"));\n SetDlgItemTextW(hwndDlg, IDC_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n const wchar_t* dateFormat = GetLocalizedString(L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\");\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), dateFormat,\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return TRUE;\n }\n\n case WM_DESTROY:\n if (hLargeIcon) {\n DestroyIcon(hLargeIcon);\n hLargeIcon = NULL;\n }\n g_hwndAboutDlg = NULL;\n break;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n g_hwndAboutDlg = NULL;\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDIT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://space.bilibili.com/26087398\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_BILIBILI_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_BILIBILI_SPACE, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_GITHUB_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_GITHUB_REPO, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDITS) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/#thanks\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_SUPPORT) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support.html\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_COPYRIGHT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime#️copyright-notice\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n break;\n\n case WM_CLOSE:\n // Close all child dialogs\n EndDialog(hwndDlg, 0);\n g_hwndAboutDlg = NULL; // Clear dialog handle\n return TRUE;\n\n case WM_CTLCOLORSTATIC:\n {\n HDC hdc = (HDC)wParam;\n HWND hwndCtl = (HWND)lParam;\n \n if (GetDlgCtrlID(hwndCtl) == IDC_CREDIT_LINK || \n GetDlgCtrlID(hwndCtl) == IDC_BILIBILI_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_GITHUB_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_CREDITS ||\n GetDlgCtrlID(hwndCtl) == IDC_COPYRIGHT_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_SUPPORT) {\n SetTextColor(hdc, 0x00D26919); // Keep the same orange color (BGR format)\n SetBkMode(hdc, TRANSPARENT);\n return (INT_PTR)GetStockObject(NULL_BRUSH);\n }\n break;\n }\n }\n return FALSE;\n}\n\n// Add DPI awareness related type definitions (if not provided by the compiler)\n#ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n// DPI_AWARENESS_CONTEXT is a HANDLE\ntypedef HANDLE DPI_AWARENESS_CONTEXT;\n// Related DPI context constants definition\n#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n#endif\n\n// Show the About dialog\nvoid ShowAboutDialog(HWND hwndParent) {\n // If an About dialog already exists, close it first\n if (g_hwndAboutDlg != NULL && IsWindow(g_hwndAboutDlg)) {\n EndDialog(g_hwndAboutDlg, 0);\n g_hwndAboutDlg = NULL;\n }\n \n // Save current DPI awareness context\n HANDLE hOldDpiContext = NULL;\n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n // Function pointer type definitions\n typedef HANDLE (WINAPI* GetThreadDpiAwarenessContextFunc)(void);\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n \n GetThreadDpiAwarenessContextFunc getThreadDpiAwarenessContextFunc = \n (GetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"GetThreadDpiAwarenessContext\");\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (getThreadDpiAwarenessContextFunc && setThreadDpiAwarenessContextFunc) {\n // Save current DPI context\n hOldDpiContext = getThreadDpiAwarenessContextFunc();\n // Set to per-monitor DPI awareness V2 mode\n setThreadDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n }\n }\n \n // Create new About dialog\n g_hwndAboutDlg = CreateDialog(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_ABOUT_DIALOG), \n hwndParent, \n AboutDlgProc);\n \n // Restore original DPI awareness context\n if (hUser32 && hOldDpiContext) {\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (setThreadDpiAwarenessContextFunc) {\n setThreadDpiAwarenessContextFunc(hOldDpiContext);\n }\n }\n \n ShowWindow(g_hwndAboutDlg, SW_SHOW);\n}\n\n// Add global variable to track pomodoro loop count setting dialog handle\nstatic HWND g_hwndPomodoroLoopDialog = NULL;\n\nvoid ShowPomodoroLoopDialog(HWND hwndParent) {\n if (!g_hwndPomodoroLoopDialog) {\n g_hwndPomodoroLoopDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_LOOP_DIALOG),\n hwndParent,\n PomodoroLoopDlgProc\n );\n if (g_hwndPomodoroLoopDialog) {\n ShowWindow(g_hwndPomodoroLoopDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroLoopDialog);\n }\n}\n\n// Add subclassing procedure for loop count edit box\nLRESULT APIENTRY LoopEditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n switch (uMsg) {\n case WM_KEYDOWN: {\n if (wParam == VK_RETURN) {\n // Send BM_CLICK message to the parent window (dialog)\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwnd);\n return 0;\n }\n // Handle Ctrl+A select all\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n }\n case WM_CHAR: {\n // Handle Ctrl+A character message to prevent alert sound\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n // Prevent Enter key from generating character messages for further processing to avoid alert sound\n if (wParam == VK_RETURN) { // VK_RETURN (0x0D) is the char code for Enter\n return 0;\n }\n break;\n }\n }\n return CallWindowProc(wpOrigLoopEditProc, hwnd, uMsg, wParam, lParam);\n}\n\n// Modify helper function to handle numeric input with spaces\nBOOL IsValidNumberInput(const wchar_t* str) {\n // Check if empty\n if (!str || !*str) {\n return FALSE;\n }\n \n BOOL hasDigit = FALSE; // Used to track if at least one digit is found\n wchar_t cleanStr[16] = {0}; // Used to store cleaned string\n int cleanIndex = 0;\n \n // Traverse string, ignore spaces, only keep digits\n for (int i = 0; str[i]; i++) {\n if (iswdigit(str[i])) {\n cleanStr[cleanIndex++] = str[i];\n hasDigit = TRUE;\n } else if (!iswspace(str[i])) { // If not a space and not a digit, then invalid\n return FALSE;\n }\n }\n \n return hasDigit; // Return TRUE as long as there is at least one digit\n}\n\n// Modify PomodoroLoopDlgProc function\nINT_PTR CALLBACK PomodoroLoopDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_LOOP_DIALOG);\n \n // Set static text\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_STATIC, GetLocalizedString(L\"请输入循环次数(1-100):\", L\"Please enter loop count (1-100):\"));\n \n // Set focus to edit box\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetFocus(hwndEdit);\n \n // Subclass edit control\n wpOrigLoopEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, \n (LONG_PTR)LoopEditSubclassProc);\n \n return FALSE;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n wchar_t input_str[16];\n GetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, input_str, sizeof(input_str)/sizeof(wchar_t));\n \n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; input_str[i]; i++) {\n if (!iswspace(input_str[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (input_str[0] == L'\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n \n // Validate input and handle spaces\n if (!IsValidNumberInput(input_str)) {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n \n // Extract digits (ignoring spaces)\n wchar_t cleanStr[16] = {0};\n int cleanIndex = 0;\n for (int i = 0; input_str[i]; i++) {\n if (iswdigit(input_str[i])) {\n cleanStr[cleanIndex++] = input_str[i];\n }\n }\n \n int new_loop_count = _wtoi(cleanStr);\n if (new_loop_count >= 1 && new_loop_count <= 100) {\n // Update configuration file and global variables\n WriteConfigPomodoroLoopCount(new_loop_count);\n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroLoopDialog = NULL;\n } else {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n break;\n\n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigLoopEditProc);\n }\n break;\n\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n return FALSE;\n}\n\n// Add global variable to track website URL dialog handle\nstatic HWND g_hwndWebsiteDialog = NULL;\n\n// Website URL input dialog procedure\nINT_PTR CALLBACK WebsiteDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n // Set dialog as modal\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n \n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // If URL already exists, prefill the edit box\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, CLOCK_TIMEOUT_WEBSITE_URL);\n }\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_WEBSITE_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n char url[MAX_PATH] = {0};\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, url, sizeof(url));\n \n // Check if the input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; url[i]; i++) {\n if (!isspace((unsigned char)url[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (url[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n // Validate URL format - simple check, should at least contain http:// or https://\n if (strncmp(url, \"http://\", 7) != 0 && strncmp(url, \"https://\", 8) != 0) {\n // Add https:// prefix\n char tempUrl[MAX_PATH] = \"https://\";\n StringCbCatA(tempUrl, sizeof(tempUrl), url);\n StringCbCopyA(url, sizeof(url), tempUrl);\n }\n \n // Update configuration\n WriteConfigTimeoutWebsite(url);\n EndDialog(hwndDlg, IDOK);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // User cancelled, don't change timeout action\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n return FALSE;\n}\n\n// Show website URL input dialog\nvoid ShowWebsiteDialog(HWND hwndParent) {\n // Use modal dialog instead of modeless dialog, so we can know whether the user confirmed or cancelled\n INT_PTR result = DialogBox(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_WEBSITE_DIALOG),\n hwndParent,\n WebsiteDialogProc\n );\n \n // Only when the user clicks OK and inputs a valid URL will IDOK be returned, at which point WebsiteDialogProc has already set CLOCK_TIMEOUT_ACTION\n // If the user cancels or closes the dialog, the timeout action won't be changed\n}\n\n// Set global variable to track the Pomodoro combination dialog handle\nstatic HWND g_hwndPomodoroComboDialog = NULL;\n\n// Add Pomodoro combination dialog procedure\nINT_PTR CALLBACK PomodoroComboDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Read current pomodoro time options from configuration and format for display\n char currentOptions[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char timeStr[32];\n int seconds = POMODORO_TIMES[i];\n \n // Format time into human-readable format\n if (seconds >= 3600) {\n int hours = seconds / 3600;\n int mins = (seconds % 3600) / 60;\n int secs = seconds % 60;\n if (mins == 0 && secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh \", hours);\n else if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm \", hours, mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm%ds \", hours, mins, secs);\n } else if (seconds >= 60) {\n int mins = seconds / 60;\n int secs = seconds % 60;\n if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm \", mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm%ds \", mins, secs);\n } else {\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%ds \", seconds);\n }\n \n StringCbCatA(currentOptions, sizeof(currentOptions), timeStr);\n }\n \n // Remove trailing space\n if (strlen(currentOptions) > 0 && currentOptions[strlen(currentOptions) - 1] == ' ') {\n currentOptions[strlen(currentOptions) - 1] = '\\0';\n }\n \n // Set edit box text\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, currentOptions);\n \n // Apply multilingual support - moved here to ensure all default text is covered\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_COMBO_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || LOWORD(wParam) == IDOK) {\n char input[256] = {0};\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, input, sizeof(input));\n \n // Parse input time format and convert to seconds array\n char *token, *saveptr;\n char input_copy[256];\n StringCbCopyA(input_copy, sizeof(input_copy), input);\n \n int times[MAX_POMODORO_TIMES] = {0};\n int times_count = 0;\n \n token = strtok_r(input_copy, \" \", &saveptr);\n while (token && times_count < MAX_POMODORO_TIMES) {\n int seconds = 0;\n if (ParseTimeInput(token, &seconds)) {\n times[times_count++] = seconds;\n }\n token = strtok_r(NULL, \" \", &saveptr);\n }\n \n if (times_count > 0) {\n // Update global variables\n POMODORO_TIMES_COUNT = times_count;\n for (int i = 0; i < times_count; i++) {\n POMODORO_TIMES[i] = times[i];\n }\n \n // Update basic pomodoro times\n if (times_count > 0) POMODORO_WORK_TIME = times[0];\n if (times_count > 1) POMODORO_SHORT_BREAK = times[1];\n if (times_count > 2) POMODORO_LONG_BREAK = times[2];\n \n // Write to configuration file\n WriteConfigPomodoroTimeOptions(times, times_count);\n }\n \n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n }\n \n return FALSE;\n}\n\nvoid ShowPomodoroComboDialog(HWND hwndParent) {\n if (!g_hwndPomodoroComboDialog) {\n g_hwndPomodoroComboDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_COMBO_DIALOG),\n hwndParent,\n PomodoroComboDialogProc\n );\n if (g_hwndPomodoroComboDialog) {\n ShowWindow(g_hwndPomodoroComboDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroComboDialog);\n }\n}\n\nBOOL ParseTimeInput(const char* input, int* seconds) {\n if (!input || !seconds) return FALSE;\n\n *seconds = 0;\n char* buffer = _strdup(input);\n if (!buffer) return FALSE;\n\n int len = strlen(buffer);\n char* pos = buffer;\n int value = 0;\n int tempSeconds = 0;\n\n while (*pos) {\n if (isdigit((unsigned char)*pos)) {\n value = 0;\n while (isdigit((unsigned char)*pos)) {\n value = value * 10 + (*pos - '0');\n pos++;\n }\n\n if (*pos == 'h' || *pos == 'H') {\n tempSeconds += value * 3600;\n pos++;\n } else if (*pos == 'm' || *pos == 'M') {\n tempSeconds += value * 60;\n pos++;\n } else if (*pos == 's' || *pos == 'S') {\n tempSeconds += value;\n pos++;\n } else if (*pos == '\\0') {\n tempSeconds += value * 60;\n } else {\n free(buffer);\n return FALSE;\n }\n } else {\n pos++;\n }\n }\n\n free(buffer);\n *seconds = tempSeconds;\n return TRUE;\n}\n\nstatic HWND g_hwndNotificationMessagesDialog = NULL;\n\nINT_PTR CALLBACK NotificationMessagesDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n\n ReadNotificationMessagesConfig();\n \n // For handling UTF-8 Chinese characters, we need to convert to Unicode\n wchar_t wideText[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT)];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL1, \n GetLocalizedString(L\"Countdown timeout message:\", L\"Countdown timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL2, \n GetLocalizedString(L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL3,\n GetLocalizedString(L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"));\n \n // Localize button text\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"OK\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"Cancel\", L\"Cancel\"));\n \n // Subclass edit boxes to support Ctrl+A for select all\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n // Save original window procedure\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Apply the same subclassing process to other edit boxes\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Select all text in the first edit box\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_EDIT1, EM_SETSEL, 0, -1);\n \n // Set focus to the first edit box\n SetFocus(GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1));\n \n return FALSE; // Return FALSE because we manually set focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n // Get text from edit boxes (Unicode method)\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Save to configuration file and update global variables\n WriteConfigNotificationMessages(timeout_msg, pomodoro_msg, cycle_complete_msg);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification message settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification message settings dialog for modifying various notification prompt texts.\n */\nvoid ShowNotificationMessagesDialog(HWND hwndParent) {\n if (!g_hwndNotificationMessagesDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationMessagesConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_MESSAGES_DIALOG), \n hwndParent, \n NotificationMessagesDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationMessagesDialog);\n }\n}\n\n// Add global variable to track notification display settings dialog handle\nstatic HWND g_hwndNotificationDisplayDialog = NULL;\n\n// Add notification display settings dialog procedure\nINT_PTR CALLBACK NotificationDisplayDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set window to topmost\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n \n // Create brushes\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n \n // Read latest configuration\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n // Set current values to edit boxes\n char buffer[32];\n \n // Display time (seconds, support decimal) - convert milliseconds to seconds\n StringCbPrintfA(buffer, sizeof(buffer), \"%.1f\", (float)NOTIFICATION_TIMEOUT_MS / 1000.0f);\n // Remove trailing .0\n if (strlen(buffer) > 2 && buffer[strlen(buffer)-2] == '.' && buffer[strlen(buffer)-1] == '0') {\n buffer[strlen(buffer)-2] = '\\0';\n }\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, buffer);\n \n // Opacity (percentage)\n StringCbPrintfA(buffer, sizeof(buffer), \"%d\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, buffer);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_LABEL, \n GetLocalizedString(L\"Notification display time (sec):\", L\"Notification display time (sec):\"));\n \n // Modify edit box style, remove ES_NUMBER to allow decimal point\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n LONG style = GetWindowLong(hEditTime, GWL_STYLE);\n SetWindowLong(hEditTime, GWL_STYLE, style & ~ES_NUMBER);\n \n // Subclass edit boxes to support Enter key submission and input restrictions\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Set focus to time edit box\n SetFocus(hEditTime);\n \n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n char timeStr[32] = {0};\n char opacityStr[32] = {0};\n \n // Get user input values\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, timeStr, sizeof(timeStr));\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, opacityStr, sizeof(opacityStr));\n \n // Use more robust method to replace Chinese period\n // First get the text in Unicode format\n wchar_t wTimeStr[32] = {0};\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, wTimeStr, sizeof(wTimeStr)/sizeof(wchar_t));\n \n // Replace Chinese punctuation marks in Unicode text\n for (int i = 0; wTimeStr[i] != L'\\0'; i++) {\n // Recognize various punctuation marks as decimal point\n if (wTimeStr[i] == L'。' || // Chinese period\n wTimeStr[i] == L',' || // Chinese comma\n wTimeStr[i] == L',' || // English comma\n wTimeStr[i] == L'·' || // Chinese middle dot\n wTimeStr[i] == L'`' || // Backtick\n wTimeStr[i] == L':' || // Chinese colon\n wTimeStr[i] == L':' || // English colon\n wTimeStr[i] == L';' || // Chinese semicolon\n wTimeStr[i] == L';' || // English semicolon\n wTimeStr[i] == L'/' || // Forward slash\n wTimeStr[i] == L'\\\\' || // Backslash\n wTimeStr[i] == L'~' || // Tilde\n wTimeStr[i] == L'~' || // Full-width tilde\n wTimeStr[i] == L'、' || // Chinese enumeration comma\n wTimeStr[i] == L'.') { // Full-width period\n wTimeStr[i] = L'.'; // Replace with English decimal point\n }\n }\n \n // Convert processed Unicode text back to ASCII\n WideCharToMultiByte(CP_ACP, 0, wTimeStr, -1, \n timeStr, sizeof(timeStr), NULL, NULL);\n \n // Parse time (seconds) and convert to milliseconds\n float timeInSeconds = atof(timeStr);\n int timeInMs = (int)(timeInSeconds * 1000.0f);\n \n // Allow time to be set to 0 (no notification) or at least 100 milliseconds\n if (timeInMs > 0 && timeInMs < 100) timeInMs = 100;\n \n // Parse opacity\n int opacity = atoi(opacityStr);\n \n // Ensure opacity is in range 1-100\n if (opacity < 1) opacity = 1;\n if (opacity > 100) opacity = 100;\n \n // Write to configuration\n WriteConfigNotificationTimeout(timeInMs);\n WriteConfigNotificationOpacity(opacity);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n }\n break;\n \n // Add handling for WM_CLOSE message\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n HWND hEditOpacity = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEditOpacity, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification display settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification display settings dialog for modifying notification display time and opacity.\n */\nvoid ShowNotificationDisplayDialog(HWND hwndParent) {\n if (!g_hwndNotificationDisplayDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_DISPLAY_DIALOG), \n hwndParent, \n NotificationDisplayDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationDisplayDialog);\n }\n}\n\n// Add global variable to track the integrated notification settings dialog handle\nstatic HWND g_hwndNotificationSettingsDialog = NULL;\n\n/**\n * @brief Audio playback completion callback function\n * @param hwnd Window handle\n * \n * When audio playback completes, changes \"Stop\" button back to \"Test\" button\n */\nstatic void OnAudioPlaybackComplete(HWND hwnd) {\n if (hwnd && IsWindow(hwnd)) {\n const wchar_t* testText = GetLocalizedString(L\"Test\", L\"Test\");\n SetDlgItemTextW(hwnd, IDC_TEST_SOUND_BUTTON, testText);\n \n // Get dialog data\n HWND hwndTestButton = GetDlgItem(hwnd, IDC_TEST_SOUND_BUTTON);\n \n // Send WM_SETTEXT message to update button text\n if (hwndTestButton && IsWindow(hwndTestButton)) {\n SendMessageW(hwndTestButton, WM_SETTEXT, 0, (LPARAM)testText);\n }\n \n // Update global playback state\n if (g_hwndNotificationSettingsDialog == hwnd) {\n // Send message to dialog to notify state change\n SendMessage(hwnd, WM_APP + 100, 0, 0);\n }\n }\n}\n\n/**\n * @brief Populate audio dropdown box\n * @param hwndDlg Dialog handle\n */\nstatic void PopulateSoundComboBox(HWND hwndDlg) {\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n if (!hwndCombo) return;\n\n // Clear dropdown list\n SendMessage(hwndCombo, CB_RESETCONTENT, 0, 0);\n\n // Add \"None\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"None\", L\"None\"));\n \n // Add \"System Beep\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"System Beep\", L\"System Beep\"));\n\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to wide character path\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n\n // Build search path\n wchar_t wSearchPath[MAX_PATH];\n StringCbPrintfW(wSearchPath, sizeof(wSearchPath), L\"%s\\\\*.*\", wAudioPath);\n\n // Find audio files - using Unicode version of API\n WIN32_FIND_DATAW find_data;\n HANDLE hFind = FindFirstFileW(wSearchPath, &find_data);\n if (hFind != INVALID_HANDLE_VALUE) {\n do {\n // Check file extension\n wchar_t* ext = wcsrchr(find_data.cFileName, L'.');\n if (ext && (\n _wcsicmp(ext, L\".flac\") == 0 ||\n _wcsicmp(ext, L\".mp3\") == 0 ||\n _wcsicmp(ext, L\".wav\") == 0\n )) {\n // Add Unicode filename directly to dropdown\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)find_data.cFileName);\n }\n } while (FindNextFileW(hFind, &find_data));\n FindClose(hFind);\n }\n\n // Set currently selected audio file\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n // Check if it's the special system beep marker\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n // Select \"System Beep\" option (index 1)\n SendMessage(hwndCombo, CB_SETCURSEL, 1, 0);\n } else {\n wchar_t wSoundFile[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, NOTIFICATION_SOUND_FILE, -1, wSoundFile, MAX_PATH);\n \n // Get filename part\n wchar_t* fileName = wcsrchr(wSoundFile, L'\\\\');\n if (fileName) fileName++;\n else fileName = wSoundFile;\n \n // Find and select the file in dropdown\n int index = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)fileName);\n if (index != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, index, 0);\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n }\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n}\n\n/**\n * @brief Integrated notification settings dialog procedure\n * @param hwndDlg Dialog handle\n * @param msg Message type\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return INT_PTR Message processing result\n * \n * Integrates notification content and notification display settings in a unified interface\n */\nINT_PTR CALLBACK NotificationSettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static BOOL isPlaying = FALSE; // Add a static variable to track playback status\n static int originalVolume = 0; // Add a static variable to store original volume\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Read latest configuration to global variables\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n // Save original volume value for restoration when canceling\n originalVolume = NOTIFICATION_SOUND_VOLUME;\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG);\n \n // Set notification message text - using Unicode functions\n wchar_t wideText[256];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Set notification display time\n SYSTEMTIME st = {0};\n GetLocalTime(&st);\n \n // Read notification disabled setting\n ReadNotificationDisabledConfig();\n \n // Set checkbox based on disabled state\n CheckDlgButton(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK, NOTIFICATION_DISABLED ? BST_CHECKED : BST_UNCHECKED);\n \n // Enable/disable time control based on state\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !NOTIFICATION_DISABLED);\n \n // Set time control value - display actual configured time regardless of disabled state\n int totalSeconds = NOTIFICATION_TIMEOUT_MS / 1000;\n st.wHour = totalSeconds / 3600;\n st.wMinute = (totalSeconds % 3600) / 60;\n st.wSecond = totalSeconds % 60;\n \n // Set time control's initial value\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_SETSYSTEMTIME, \n GDT_VALID, (LPARAM)&st);\n\n // Set notification opacity slider\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n SendMessage(hwndOpacitySlider, TBM_SETRANGE, TRUE, MAKELONG(1, 100));\n SendMessage(hwndOpacitySlider, TBM_SETPOS, TRUE, NOTIFICATION_MAX_OPACITY);\n \n // Update opacity text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n // Set notification type radio buttons\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_OS:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_OS, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, BST_CHECKED);\n break;\n }\n \n // Populate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Set volume slider\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n SendMessage(hwndSlider, TBM_SETRANGE, TRUE, MAKELONG(0, 100));\n SendMessage(hwndSlider, TBM_SETPOS, TRUE, NOTIFICATION_SOUND_VOLUME);\n \n // Update volume text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", NOTIFICATION_SOUND_VOLUME);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Reset playback state on initialization\n isPlaying = FALSE;\n \n // Set audio playback completion callback\n SetAudioPlaybackCompleteCallback(hwndDlg, OnAudioPlaybackComplete);\n \n // Save dialog handle\n g_hwndNotificationSettingsDialog = hwndDlg;\n \n return TRUE;\n }\n \n case WM_HSCROLL: {\n // Handle slider drag events\n if (GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER) == (HWND)lParam) {\n // Get slider's current position\n int volume = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update volume percentage text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", volume);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Apply volume setting in real-time\n SetAudioVolume(volume);\n \n return TRUE;\n }\n else if (GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT) == (HWND)lParam) {\n // Get slider's current position\n int opacity = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update opacity percentage text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", opacity);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND:\n // Handle notification disable checkbox state change\n if (LOWORD(wParam) == IDC_DISABLE_NOTIFICATION_CHECK && HIWORD(wParam) == BN_CLICKED) {\n BOOL isChecked = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !isChecked);\n return TRUE;\n }\n else if (LOWORD(wParam) == IDOK) {\n // Get notification message text - using Unicode functions\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Get notification display time\n SYSTEMTIME st = {0};\n \n // Check if notification disable checkbox is checked\n BOOL isDisabled = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n \n // Save disabled state\n NOTIFICATION_DISABLED = isDisabled;\n WriteConfigNotificationDisabled(isDisabled);\n \n // Get notification time settings\n // Get notification time settings\n if (SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_GETSYSTEMTIME, 0, (LPARAM)&st) == GDT_VALID) {\n // Calculate total seconds: hours*3600 + minutes*60 + seconds\n int totalSeconds = st.wHour * 3600 + st.wMinute * 60 + st.wSecond;\n \n if (totalSeconds == 0) {\n // If time is 00:00:00, set to 0 (meaning disable notifications)\n NOTIFICATION_TIMEOUT_MS = 0;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n \n } else if (!isDisabled) {\n // Only update non-zero notification time if not disabled\n NOTIFICATION_TIMEOUT_MS = totalSeconds * 1000;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n }\n }\n // If notifications are disabled, don't modify notification time configuration\n \n // Get notification opacity (from slider)\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n int opacity = (int)SendMessage(hwndOpacitySlider, TBM_GETPOS, 0, 0);\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n \n // Get notification type\n if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_OS)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n }\n \n // Get selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n if (index > 0) { // 0 is \"None\" option\n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Check if \"System Beep\" is selected\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker to represent system beep\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n } else {\n NOTIFICATION_SOUND_FILE[0] = '\\0';\n }\n \n // Get volume slider position\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n NOTIFICATION_SOUND_VOLUME = volume;\n \n // Save all settings\n WriteConfigNotificationMessages(\n timeout_msg,\n pomodoro_msg,\n cycle_complete_msg\n );\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n WriteConfigNotificationOpacity(NOTIFICATION_MAX_OPACITY);\n WriteConfigNotificationType(NOTIFICATION_TYPE);\n WriteConfigNotificationSound(NOTIFICATION_SOUND_FILE);\n WriteConfigNotificationVolume(NOTIFICATION_SOUND_VOLUME);\n \n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Restore original volume setting\n NOTIFICATION_SOUND_VOLUME = originalVolume;\n \n // Reapply original volume\n SetAudioVolume(originalVolume);\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDC_TEST_SOUND_BUTTON) {\n if (!isPlaying) {\n // Currently not playing, start playback and change button text to \"Stop\"\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n \n if (index > 0) { // 0 is the \"None\" option\n // Get current slider volume and apply it\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n SetAudioVolume(volume);\n \n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Temporarily save current audio settings\n char tempSoundFile[MAX_PATH];\n StringCbCopyA(tempSoundFile, sizeof(tempSoundFile), NOTIFICATION_SOUND_FILE);\n \n // Temporarily set audio file\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n \n // Play audio\n if (PlayNotificationSound(hwndDlg)) {\n // Playback successful, change button text to \"Stop\"\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Stop\", L\"Stop\"));\n isPlaying = TRUE;\n }\n \n // Restore previous settings\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), tempSoundFile);\n }\n } else {\n // Currently playing, stop playback and restore button text\n StopNotificationSound();\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Test\", L\"Test\"));\n isPlaying = FALSE;\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDC_OPEN_SOUND_DIR_BUTTON) {\n // Get audio directory path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Ensure directory exists\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n \n // Open directory\n ShellExecuteW(hwndDlg, L\"open\", wAudioPath, NULL, NULL, SW_SHOWNORMAL);\n \n // Record currently selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Try to restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n } else {\n // If previous selection not found, default to \"None\"\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0);\n }\n }\n \n return TRUE;\n } else if (LOWORD(wParam) == IDC_NOTIFICATION_SOUND_COMBO && HIWORD(wParam) == CBN_DROPDOWN) {\n // When dropdown is about to open, reload file list\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n \n // Record currently selected file\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n }\n }\n \n return TRUE;\n }\n break;\n \n // Add custom message handling for audio playback completion notification\n case WM_APP + 100:\n // Audio playback is complete, update button state\n isPlaying = FALSE;\n return TRUE;\n \n case WM_CLOSE:\n // Make sure to stop playback when closing dialog\n if (isPlaying) {\n StopNotificationSound();\n }\n \n // Clean up callback\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Clean up callback when dialog is destroyed\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n g_hwndNotificationSettingsDialog = NULL;\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Display integrated notification settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays a unified dialog that includes both notification content and display settings\n */\nvoid ShowNotificationSettingsDialog(HWND hwndParent) {\n if (!g_hwndNotificationSettingsDialog) {\n // Ensure the latest configuration values are read first\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG), \n hwndParent, \n NotificationSettingsDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationSettingsDialog);\n }\n}"], ["/Catime/src/window.c", "/**\n * @file window.c\n * @brief Window management functionality implementation\n * \n * This file implements the functionality related to application window management,\n * including window creation, position adjustment, transparency, click-through, and drag functionality.\n */\n\n#include \"../include/window.h\"\n#include \"../include/timer.h\"\n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n\n// Forward declaration of WindowProcedure (defined in main.c)\nextern LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\n\n// Add declaration for SetProcessDPIAware function\n#ifndef _INC_WINUSER\n// If not included by windows.h, add SetProcessDPIAware function declaration\nWINUSERAPI BOOL WINAPI SetProcessDPIAware(VOID);\n#endif\n\n// Window size and position variables\nint CLOCK_BASE_WINDOW_WIDTH = 200;\nint CLOCK_BASE_WINDOW_HEIGHT = 100;\nfloat CLOCK_WINDOW_SCALE = 1.0f;\nint CLOCK_WINDOW_POS_X = 100;\nint CLOCK_WINDOW_POS_Y = 100;\n\n// Window state variables\nBOOL CLOCK_EDIT_MODE = FALSE;\nBOOL CLOCK_IS_DRAGGING = FALSE;\nPOINT CLOCK_LAST_MOUSE_POS = {0, 0};\nBOOL CLOCK_WINDOW_TOPMOST = TRUE; // Default topmost\n\n// Text area variables\nRECT CLOCK_TEXT_RECT = {0, 0, 0, 0};\nBOOL CLOCK_TEXT_RECT_VALID = FALSE;\n\n// DWM function pointer type definition\ntypedef HRESULT (WINAPI *pfnDwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);\nstatic pfnDwmEnableBlurBehindWindow _DwmEnableBlurBehindWindow = NULL;\n\n// Window composition attribute type definition\ntypedef enum _WINDOWCOMPOSITIONATTRIB {\n WCA_UNDEFINED = 0,\n WCA_NCRENDERING_ENABLED = 1,\n WCA_NCRENDERING_POLICY = 2,\n WCA_TRANSITIONS_FORCEDISABLED = 3,\n WCA_ALLOW_NCPAINT = 4,\n WCA_CAPTION_BUTTON_BOUNDS = 5,\n WCA_NONCLIENT_RTL_LAYOUT = 6,\n WCA_FORCE_ICONIC_REPRESENTATION = 7,\n WCA_EXTENDED_FRAME_BOUNDS = 8,\n WCA_HAS_ICONIC_BITMAP = 9,\n WCA_THEME_ATTRIBUTES = 10,\n WCA_NCRENDERING_EXILED = 11,\n WCA_NCADORNMENTINFO = 12,\n WCA_EXCLUDED_FROM_LIVEPREVIEW = 13,\n WCA_VIDEO_OVERLAY_ACTIVE = 14,\n WCA_FORCE_ACTIVEWINDOW_APPEARANCE = 15,\n WCA_DISALLOW_PEEK = 16,\n WCA_CLOAK = 17,\n WCA_CLOAKED = 18,\n WCA_ACCENT_POLICY = 19,\n WCA_FREEZE_REPRESENTATION = 20,\n WCA_EVER_UNCLOAKED = 21,\n WCA_VISUAL_OWNER = 22,\n WCA_HOLOGRAPHIC = 23,\n WCA_EXCLUDED_FROM_DDA = 24,\n WCA_PASSIVEUPDATEMODE = 25,\n WCA_USEDARKMODECOLORS = 26,\n WCA_LAST = 27\n} WINDOWCOMPOSITIONATTRIB;\n\ntypedef struct _WINDOWCOMPOSITIONATTRIBDATA {\n WINDOWCOMPOSITIONATTRIB Attrib;\n PVOID pvData;\n SIZE_T cbData;\n} WINDOWCOMPOSITIONATTRIBDATA;\n\nWINUSERAPI BOOL WINAPI SetWindowCompositionAttribute(HWND hwnd, WINDOWCOMPOSITIONATTRIBDATA* pData);\n\ntypedef enum _ACCENT_STATE {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5\n} ACCENT_STATE;\n\ntypedef struct _ACCENT_POLICY {\n ACCENT_STATE AccentState;\n DWORD AccentFlags;\n DWORD GradientColor;\n DWORD AnimationId;\n} ACCENT_POLICY;\n\nvoid SetClickThrough(HWND hwnd, BOOL enable) {\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n // Clear previously set related styles\n exStyle &= ~WS_EX_TRANSPARENT;\n \n if (enable) {\n // Set click-through\n exStyle |= WS_EX_TRANSPARENT;\n \n // If the window is a layered window, ensure it properly handles mouse input\n if (exStyle & WS_EX_LAYERED) {\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n }\n } else {\n // Ensure window receives all mouse input\n if (exStyle & WS_EX_LAYERED) {\n // Maintain transparency but allow receiving mouse input\n SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);\n }\n }\n \n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Update window to apply new style\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n}\n\nBOOL InitDWMFunctions() {\n HMODULE hDwmapi = LoadLibraryA(\"dwmapi.dll\");\n if (hDwmapi) {\n _DwmEnableBlurBehindWindow = (pfnDwmEnableBlurBehindWindow)GetProcAddress(hDwmapi, \"DwmEnableBlurBehindWindow\");\n return _DwmEnableBlurBehindWindow != NULL;\n }\n return FALSE;\n}\n\nvoid SetBlurBehind(HWND hwnd, BOOL enable) {\n if (enable) {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_ENABLE_BLURBEHIND;\n policy.AccentFlags = 0;\n policy.GradientColor = (180 << 24) | 0x00202020; // Changed to dark gray background with 180 transparency\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = TRUE;\n bb.hRgnBlur = NULL;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n } else {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_DISABLED;\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = FALSE;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n }\n}\n\nvoid AdjustWindowPosition(HWND hwnd, BOOL forceOnScreen) {\n if (!forceOnScreen) {\n // Do not force window to be on screen, return directly\n return;\n }\n \n // Original code to ensure window is on screen\n RECT rect;\n GetWindowRect(hwnd, &rect);\n \n int screenWidth = GetSystemMetrics(SM_CXSCREEN);\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n \n int width = rect.right - rect.left;\n int height = rect.bottom - rect.top;\n \n int x = rect.left;\n int y = rect.top;\n \n // Ensure window right edge doesn't exceed screen\n if (x + width > screenWidth) {\n x = screenWidth - width;\n }\n \n // Ensure window bottom edge doesn't exceed screen\n if (y + height > screenHeight) {\n y = screenHeight - height;\n }\n \n // Ensure window left edge doesn't exceed screen\n if (x < 0) {\n x = 0;\n }\n \n // Ensure window top edge doesn't exceed screen\n if (y < 0) {\n y = 0;\n }\n \n // If window position needs adjustment, move the window\n if (x != rect.left || y != rect.top) {\n SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n }\n}\n\nextern void GetConfigPath(char* path, size_t size);\nextern void WriteConfigEditMode(const char* mode);\n\nvoid SaveWindowSettings(HWND hwnd) {\n if (!hwnd) return;\n\n RECT rect;\n if (!GetWindowRect(hwnd, &rect)) return;\n \n CLOCK_WINDOW_POS_X = rect.left;\n CLOCK_WINDOW_POS_Y = rect.top;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n size_t buffer_size = 8192; \n char *config = malloc(buffer_size);\n char *new_config = malloc(buffer_size);\n if (!config || !new_config) {\n if (config) free(config);\n if (new_config) free(new_config);\n fclose(fp);\n return;\n }\n \n config[0] = new_config[0] = '\\0';\n char line[256];\n size_t total_len = 0;\n \n while (fgets(line, sizeof(line), fp)) {\n size_t line_len = strlen(line);\n if (total_len + line_len >= buffer_size - 1) {\n size_t new_size = buffer_size * 2;\n char *temp_config = realloc(config, new_size);\n char *temp_new_config = realloc(new_config, new_size);\n \n if (!temp_config || !temp_new_config) {\n free(config);\n free(new_config);\n fclose(fp);\n return;\n }\n \n config = temp_config;\n new_config = temp_new_config;\n buffer_size = new_size;\n }\n strcat(config, line);\n total_len += line_len;\n }\n fclose(fp);\n \n char *start = config;\n char *end = config + strlen(config);\n BOOL has_window_scale = FALSE;\n size_t new_config_len = 0;\n \n while (start < end) {\n char *newline = strchr(start, '\\n');\n if (!newline) newline = end;\n \n char temp[256] = {0};\n size_t line_len = newline - start;\n if (line_len >= sizeof(temp)) line_len = sizeof(temp) - 1;\n strncpy(temp, start, line_len);\n \n if (strncmp(temp, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len, \n buffer_size - new_config_len, \n \"CLOCK_WINDOW_POS_X=%d\\n\", CLOCK_WINDOW_POS_X);\n } else if (strncmp(temp, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"CLOCK_WINDOW_POS_Y=%d\\n\", CLOCK_WINDOW_POS_Y);\n } else if (strncmp(temp, \"WINDOW_SCALE=\", 13) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n has_window_scale = TRUE;\n } else {\n size_t remaining = buffer_size - new_config_len;\n if (remaining > line_len + 1) {\n strncpy(new_config + new_config_len, start, line_len);\n new_config_len += line_len;\n new_config[new_config_len++] = '\\n';\n }\n }\n \n start = newline + 1;\n if (start > end) break;\n }\n \n if (!has_window_scale && buffer_size - new_config_len > 50) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n }\n \n if (new_config_len < buffer_size) {\n new_config[new_config_len] = '\\0';\n } else {\n new_config[buffer_size - 1] = '\\0';\n }\n \n fp = fopen(config_path, \"w\");\n if (fp) {\n fputs(new_config, fp);\n fclose(fp);\n }\n \n free(config);\n free(new_config);\n}\n\nvoid LoadWindowSettings(HWND hwnd) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n line[strcspn(line, \"\\n\")] = 0;\n \n if (strncmp(line, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n CLOCK_WINDOW_POS_X = atoi(line + 19);\n } else if (strncmp(line, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n CLOCK_WINDOW_POS_Y = atoi(line + 19);\n } else if (strncmp(line, \"WINDOW_SCALE=\", 13) == 0) {\n CLOCK_WINDOW_SCALE = atof(line + 13);\n CLOCK_FONT_SCALE_FACTOR = CLOCK_WINDOW_SCALE;\n }\n }\n fclose(fp);\n \n // Apply position from config file directly, without additional adjustments\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, \n CLOCK_WINDOW_POS_Y,\n (int)(CLOCK_BASE_WINDOW_WIDTH * CLOCK_WINDOW_SCALE),\n (int)(CLOCK_BASE_WINDOW_HEIGHT * CLOCK_WINDOW_SCALE),\n SWP_NOZORDER\n );\n \n // Don't call AdjustWindowPosition to avoid overriding user settings\n}\n\nBOOL HandleMouseWheel(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n // Remove original position calculation logic, directly use window center as scaling reference point\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n // Use window center as scaling reference\n float relativeX = 0.5f;\n float relativeY = 0.5f;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings after resizing\n SaveWindowSettings(hwnd);\n }\n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleMouseMove(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update the position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nHWND CreateMainWindow(HINSTANCE hInstance, int nCmdShow) {\n // Window class registration\n WNDCLASS wc = {0};\n wc.lpfnWndProc = WindowProcedure;\n wc.hInstance = hInstance;\n wc.lpszClassName = \"CatimeWindow\";\n \n if (!RegisterClass(&wc)) {\n MessageBox(NULL, \"Window Registration Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n // Set extended style\n DWORD exStyle = WS_EX_LAYERED | WS_EX_TOOLWINDOW;\n \n // If not in topmost mode, add WS_EX_NOACTIVATE extended style\n if (!CLOCK_WINDOW_TOPMOST) {\n exStyle |= WS_EX_NOACTIVATE;\n }\n \n // Create window\n HWND hwnd = CreateWindowEx(\n exStyle,\n \"CatimeWindow\",\n \"Catime\",\n WS_POPUP,\n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n CLOCK_BASE_WINDOW_WIDTH, CLOCK_BASE_WINDOW_HEIGHT,\n NULL,\n NULL,\n hInstance,\n NULL\n );\n\n if (!hwnd) {\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n EnableWindow(hwnd, TRUE);\n SetFocus(hwnd);\n\n // Set window transparency\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n\n // Set blur effect\n SetBlurBehind(hwnd, FALSE);\n\n // Initialize tray icon\n InitTrayIcon(hwnd, hInstance);\n\n // Show window\n ShowWindow(hwnd, nCmdShow);\n UpdateWindow(hwnd);\n\n // Set window position and parent based on topmost status\n if (CLOCK_WINDOW_TOPMOST) {\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n } else {\n // Find desktop window and set as parent\n HWND hProgman = FindWindow(\"Progman\", NULL);\n if (hProgman != NULL) {\n // Try to find the real desktop window\n HWND hDesktop = hProgman;\n \n // Look for WorkerW window (common in Win10+)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n \n // Set as child window of desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, set to bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n\n return hwnd;\n}\n\nfloat CLOCK_FONT_SCALE_FACTOR = 1.0f;\nint CLOCK_BASE_FONT_SIZE = 24;\n\nBOOL InitializeApplication(HINSTANCE hInstance) {\n // Set DPI awareness mode to Per-Monitor DPI Aware to properly handle scaling when moving window between displays with different DPIs\n // Use newer API SetProcessDpiAwarenessContext if available, otherwise fallback to older APIs\n \n // Define DPI awareness related constants and types\n #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);\n #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n #endif\n \n // Define PROCESS_DPI_AWARENESS enum\n typedef enum {\n PROCESS_DPI_UNAWARE = 0,\n PROCESS_SYSTEM_DPI_AWARE = 1,\n PROCESS_PER_MONITOR_DPI_AWARE = 2\n } PROCESS_DPI_AWARENESS;\n \n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n typedef BOOL(WINAPI* SetProcessDpiAwarenessContextFunc)(DPI_AWARENESS_CONTEXT);\n SetProcessDpiAwarenessContextFunc setProcessDpiAwarenessContextFunc =\n (SetProcessDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetProcessDpiAwarenessContext\");\n \n if (setProcessDpiAwarenessContextFunc) {\n // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 is the latest DPI awareness mode\n // It provides better multi-monitor DPI support\n setProcessDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n } else {\n // Try using older API\n HMODULE hShcore = LoadLibraryA(\"shcore.dll\");\n if (hShcore) {\n typedef HRESULT(WINAPI* SetProcessDpiAwarenessFunc)(PROCESS_DPI_AWARENESS);\n SetProcessDpiAwarenessFunc setProcessDpiAwarenessFunc =\n (SetProcessDpiAwarenessFunc)GetProcAddress(hShcore, \"SetProcessDpiAwareness\");\n \n if (setProcessDpiAwarenessFunc) {\n // PROCESS_PER_MONITOR_DPI_AWARE corresponds to per-monitor DPI awareness\n setProcessDpiAwarenessFunc(PROCESS_PER_MONITOR_DPI_AWARE);\n } else {\n // Finally try the oldest API\n SetProcessDPIAware();\n }\n \n FreeLibrary(hShcore);\n } else {\n // If shcore.dll is not available, use the most basic DPI awareness API\n SetProcessDPIAware();\n }\n }\n }\n \n SetConsoleOutputCP(936);\n SetConsoleCP(936);\n\n // Modified initialization order: read config file first, then initialize other features\n ReadConfig();\n UpdateStartupShortcut();\n InitializeDefaultLanguage();\n\n int defaultFontIndex = -1;\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, FONT_FILE_NAME) == 0) {\n defaultFontIndex = i;\n break;\n }\n }\n\n if (defaultFontIndex != -1) {\n LoadFontFromResource(hInstance, fontResources[defaultFontIndex].resourceId);\n }\n\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n \n return TRUE;\n}\n\nBOOL OpenFileDialog(HWND hwnd, char* filePath, DWORD maxPath) {\n OPENFILENAME ofn = { 0 };\n ofn.lStructSize = sizeof(OPENFILENAME);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFilter = \"All Files\\0*.*\\0\";\n ofn.lpstrFile = filePath;\n ofn.nMaxFile = maxPath;\n ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;\n ofn.lpstrDefExt = \"\";\n \n return GetOpenFileName(&ofn);\n}\n\n// Add function to set window topmost state\nvoid SetWindowTopmost(HWND hwnd, BOOL topmost) {\n CLOCK_WINDOW_TOPMOST = topmost;\n \n // Get current window style\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n if (topmost) {\n // Topmost mode: remove no-activate style (if exists), add topmost style\n exStyle &= ~WS_EX_NOACTIVATE;\n \n // If window was previously set as desktop child window, need to restore\n // First set window as top-level window, clear parent window relationship\n SetParent(hwnd, NULL);\n \n // Reset window owner, ensure Z-order is correct\n SetWindowLongPtr(hwnd, GWLP_HWNDPARENT, 0);\n \n // Set window position to top layer, and force window update\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_FRAMECHANGED);\n } else {\n // Non-topmost mode: add no-activate style to prevent window from gaining focus\n exStyle |= WS_EX_NOACTIVATE;\n \n // Set as child window of desktop\n HWND hProgman = FindWindow(\"Progman\", NULL);\n HWND hDesktop = NULL;\n \n // Try to find the real desktop window\n if (hProgman != NULL) {\n // First try using Progman\n hDesktop = hProgman;\n \n // Look for WorkerW window (more common on Win10)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n // Found the real desktop container\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n }\n \n if (hDesktop != NULL) {\n // Set window as child of desktop, this keeps it on the desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, at least place at bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n \n // Apply new window style\n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Force window update\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n \n // Save window topmost setting\n WriteConfigTopmost(topmost ? \"TRUE\" : \"FALSE\");\n}\n"], ["/Catime/src/tray_menu.c", "/**\n * @file tray_menu.c\n * @brief Implementation of system tray menu functionality\n * \n * This file implements the system tray menu functionality for the application, including:\n * - Right-click menu and its submenus\n * - Color selection menu\n * - Font settings menu\n * - Timeout action settings\n * - Pomodoro functionality\n * - Preset time management\n * - Multi-language interface support\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/timer.h\"\n#include \"../resource/resource.h\"\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_USE_24HOUR;\nextern BOOL CLOCK_SHOW_SECONDS;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_EDIT_MODE;\nextern char CLOCK_STARTUP_MODE[20];\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\nextern int time_options[];\nextern int time_options_count;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern char CLOCK_TIMEOUT_FILE_PATH[MAX_PATH];\nextern char CLOCK_TIMEOUT_TEXT[50];\nextern BOOL CLOCK_WINDOW_TOPMOST; ///< Whether the window is always on top\n\n// Add Pomodoro related variable declarations\nextern int POMODORO_WORK_TIME; ///< Work time (seconds)\nextern int POMODORO_SHORT_BREAK; ///< Short break time (seconds)\nextern int POMODORO_LONG_BREAK; ///< Long break time (seconds)\nextern int POMODORO_LOOP_COUNT; ///< Loop count\n\n// Pomodoro time array and count variables\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Add to external variable declaration section\nextern char CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH]; ///< URL for timeout open website\nextern int current_pomodoro_time_index; // Current Pomodoro time index\nextern POMODORO_PHASE current_pomodoro_phase; // Pomodoro phase\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t size);\nextern BOOL IsAutoStartEnabled(void);\nextern void WriteConfigStartupMode(const char* mode);\nextern void ClearColorOptions(void);\nextern void AddColorOption(const char* color);\n/// @}\n\n/**\n * @brief Read timeout action settings from configuration file\n * \n * Read the timeout action settings saved in the configuration file and update the global variable CLOCK_TIMEOUT_ACTION\n */\nvoid ReadTimeoutActionFromConfig() {\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"TIMEOUT_ACTION=\", 15) == 0) {\n int action = 0;\n sscanf(line, \"TIMEOUT_ACTION=%d\", &action);\n CLOCK_TIMEOUT_ACTION = (TimeoutActionType)action;\n break;\n }\n }\n fclose(configFile);\n }\n}\n\n/**\n * @brief Recent file structure\n * \n * Store information about recently used files, including full path and display name\n */\ntypedef struct {\n char path[MAX_PATH]; ///< Full file path\n char name[MAX_PATH]; ///< File display name (may be truncated)\n} RecentFile;\n\nextern RecentFile CLOCK_RECENT_FILES[];\nextern int CLOCK_RECENT_FILES_COUNT;\n\n/**\n * @brief Format Pomodoro time to wide string\n * @param seconds Number of seconds\n * @param buffer Output buffer\n * @param bufferSize Buffer size\n */\nstatic void FormatPomodoroTime(int seconds, wchar_t* buffer, size_t bufferSize) {\n int minutes = seconds / 60;\n int secs = seconds % 60;\n int hours = minutes / 60;\n minutes %= 60;\n \n if (hours > 0) {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d:%02d\", hours, minutes, secs);\n } else {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d\", minutes, secs);\n }\n}\n\n/**\n * @brief Truncate long file names\n * \n * @param fileName Original file name\n * @param truncated Truncated file name buffer\n * @param maxLen Maximum display length (excluding terminator)\n * \n * If the file name exceeds the specified length, it uses the format \"first 12 characters...last 12 characters.extension\" for intelligent truncation.\n * This function preserves the file extension to ensure users can identify the file type.\n */\nvoid TruncateFileName(const wchar_t* fileName, wchar_t* truncated, size_t maxLen) {\n if (!fileName || !truncated || maxLen <= 7) return; // At least need to display \"x...y\"\n \n size_t nameLen = wcslen(fileName);\n if (nameLen <= maxLen) {\n // File name does not exceed the length limit, copy directly\n wcscpy(truncated, fileName);\n return;\n }\n \n // Find the position of the last dot (extension separator)\n const wchar_t* lastDot = wcsrchr(fileName, L'.');\n const wchar_t* fileNameNoExt = fileName;\n const wchar_t* ext = L\"\";\n size_t nameNoExtLen = nameLen;\n size_t extLen = 0;\n \n if (lastDot && lastDot != fileName) {\n // Has valid extension\n ext = lastDot; // Extension including dot\n extLen = wcslen(ext);\n nameNoExtLen = lastDot - fileName; // Length of file name without extension\n }\n \n // If the pure file name length is less than or equal to 27 characters (12+3+12), use the old truncation method\n if (nameNoExtLen <= 27) {\n // Simple truncation of main file name, preserving extension\n wcsncpy(truncated, fileName, maxLen - extLen - 3);\n truncated[maxLen - extLen - 3] = L'\\0';\n wcscat(truncated, L\"...\");\n wcscat(truncated, ext);\n return;\n }\n \n // Use new truncation method: first 12 characters + ... + last 12 characters + extension\n wchar_t buffer[MAX_PATH];\n \n // Copy first 12 characters\n wcsncpy(buffer, fileName, 12);\n buffer[12] = L'\\0';\n \n // Add ellipsis\n wcscat(buffer, L\"...\");\n \n // Copy last 12 characters (excluding extension part)\n wcsncat(buffer, fileName + nameNoExtLen - 12, 12);\n \n // Add extension\n wcscat(buffer, ext);\n \n // Copy result to output buffer\n wcscpy(truncated, buffer);\n}\n\n/**\n * @brief Display color and settings menu\n * \n * @param hwnd Window handle\n * \n * Create and display the application's main settings menu, including:\n * - Edit mode toggle\n * - Timeout action settings\n * - Preset time management\n * - Startup mode settings\n * - Font selection\n * - Color settings\n * - Language selection\n * - Help and about information\n */\nvoid ShowColorMenu(HWND hwnd) {\n // Read timeout action settings from the configuration file before creating the menu\n ReadTimeoutActionFromConfig();\n \n // Set mouse cursor to default arrow to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n HMENU hMenu = CreatePopupMenu();\n \n // Add edit mode option\n AppendMenuW(hMenu, MF_STRING | (CLOCK_EDIT_MODE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_EDIT_MODE, \n GetLocalizedString(L\"编辑模式\", L\"Edit Mode\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Timeout action menu\n HMENU hTimeoutMenu = CreatePopupMenu();\n \n // 1. Show message\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_SHOW_MESSAGE, \n GetLocalizedString(L\"显示消息\", L\"Show Message\"));\n\n // 2. Show current time\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHOW_TIME ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_SHOW_TIME, \n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n\n // 3. Count up\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_COUNT_UP ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_COUNT_UP, \n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n\n // 4. Lock screen\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_LOCK ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LOCK_SCREEN,\n GetLocalizedString(L\"锁定屏幕\", L\"Lock Screen\"));\n\n // First separator\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // 5. Open file (submenu)\n HMENU hFileMenu = CreatePopupMenu();\n\n // First add recent files list\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n wchar_t wFileName[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[i].name, -1, wFileName, MAX_PATH);\n \n // Truncate long file names\n wchar_t truncatedName[MAX_PATH];\n TruncateFileName(wFileName, truncatedName, 25); // Limit to 25 characters\n \n // Check if this is the currently selected file and the current timeout action is \"open file\"\n BOOL isCurrentFile = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE && \n strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n strcmp(CLOCK_RECENT_FILES[i].path, CLOCK_TIMEOUT_FILE_PATH) == 0);\n \n // Use menu item check state to indicate selection\n AppendMenuW(hFileMenu, MF_STRING | (isCurrentFile ? MF_CHECKED : 0), \n CLOCK_IDM_RECENT_FILE_1 + i, truncatedName);\n }\n \n // Add separator if there are recent files\n if (CLOCK_RECENT_FILES_COUNT > 0) {\n AppendMenuW(hFileMenu, MF_SEPARATOR, 0, NULL);\n }\n\n // Finally add \"Browse...\" option\n AppendMenuW(hFileMenu, MF_STRING, CLOCK_IDM_BROWSE_FILE,\n GetLocalizedString(L\"浏览...\", L\"Browse...\"));\n\n // Add \"Open File\" as a submenu to the timeout action menu\n AppendMenuW(hTimeoutMenu, MF_POPUP | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE ? MF_CHECKED : MF_UNCHECKED), \n (UINT_PTR)hFileMenu, \n GetLocalizedString(L\"打开文件/软件\", L\"Open File/Software\"));\n\n // 6. Open website\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_WEBSITE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_OPEN_WEBSITE,\n GetLocalizedString(L\"打开网站\", L\"Open Website\"));\n\n // Second separator\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // Add a non-selectable hint option\n AppendMenuW(hTimeoutMenu, MF_STRING | MF_GRAYED | MF_DISABLED, \n 0, // Use ID 0 to indicate non-selectable menu item\n GetLocalizedString(L\"以下超时动作为一次性\", L\"Following actions are one-time only\"));\n\n // 7. Shutdown\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHUTDOWN,\n GetLocalizedString(L\"关机\", L\"Shutdown\"));\n\n // 8. Restart\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RESTART,\n GetLocalizedString(L\"重启\", L\"Restart\"));\n\n // 9. Sleep\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SLEEP,\n GetLocalizedString(L\"睡眠\", L\"Sleep\"));\n\n // Third separator and Advanced menu\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // Create Advanced submenu\n HMENU hAdvancedMenu = CreatePopupMenu();\n\n // Add \"Run Command\" option\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RUN_COMMAND,\n GetLocalizedString(L\"运行命令\", L\"Run Command\"));\n\n // Add \"HTTP Request\" option\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_HTTP_REQUEST,\n GetLocalizedString(L\"HTTP 请求\", L\"HTTP Request\"));\n\n // Check if any advanced option is selected to determine if the Advanced submenu should be checked\n BOOL isAdvancedOptionSelected = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ||\n CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST);\n\n // Add Advanced submenu to timeout menu - mark as checked if any advanced option is selected\n AppendMenuW(hTimeoutMenu, MF_POPUP | (isAdvancedOptionSelected ? MF_CHECKED : MF_UNCHECKED),\n (UINT_PTR)hAdvancedMenu,\n GetLocalizedString(L\"高级\", L\"Advanced\"));\n\n // Add timeout action menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeoutMenu, \n GetLocalizedString(L\"超时动作\", L\"Timeout Action\"));\n\n // Preset management menu\n HMENU hTimeOptionsMenu = CreatePopupMenu();\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDC_MODIFY_TIME_OPTIONS,\n GetLocalizedString(L\"倒计时预设\", L\"Modify Quick Countdown Options\"));\n \n // Startup settings submenu\n HMENU hStartupSettingsMenu = CreatePopupMenu();\n\n // Read current startup mode\n char currentStartupMode[20] = \"COUNTDOWN\";\n char configPath[MAX_PATH]; \n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\"); \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(configFile);\n }\n \n // Add startup mode options\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNTDOWN\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_SET_COUNTDOWN_TIME,\n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNT_UP\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_COUNT_UP,\n GetLocalizedString(L\"正计时\", L\"Stopwatch\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"SHOW_TIME\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_SHOW_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"NO_DISPLAY\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_NO_DISPLAY,\n GetLocalizedString(L\"不显示\", L\"No Display\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_SEPARATOR, 0, NULL);\n\n // Add auto-start option\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (IsAutoStartEnabled() ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_AUTO_START,\n GetLocalizedString(L\"开机自启动\", L\"Start with Windows\"));\n\n // Add startup settings menu to preset management menu\n AppendMenuW(hTimeOptionsMenu, MF_POPUP, (UINT_PTR)hStartupSettingsMenu,\n GetLocalizedString(L\"启动设置\", L\"Startup Settings\"));\n\n // Add notification settings menu - changed to direct menu item, no longer using submenu\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDM_NOTIFICATION_SETTINGS,\n GetLocalizedString(L\"通知设置\", L\"Notification Settings\"));\n\n // Add preset management menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeOptionsMenu,\n GetLocalizedString(L\"预设管理\", L\"Preset Management\"));\n \n AppendMenuW(hTimeOptionsMenu, MF_STRING | (CLOCK_WINDOW_TOPMOST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TOPMOST,\n GetLocalizedString(L\"置顶\", L\"Always on Top\"));\n\n // Add \"Hotkey Settings\" option after preset management menu\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_HOTKEY_SETTINGS,\n GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Font menu\n HMENU hMoreFontsMenu = CreatePopupMenu();\n HMENU hFontSubMenu = CreatePopupMenu();\n \n // First add commonly used fonts to the main menu\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n // These fonts are kept in the main menu\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n \n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayName[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayName, 100);\n wchar_t* dot = wcsstr(wDisplayName, L\".ttf\");\n if (dot) *dot = L'\\0';\n \n AppendMenuW(hFontSubMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayName);\n }\n }\n\n AppendMenuW(hFontSubMenu, MF_SEPARATOR, 0, NULL);\n\n // Add other fonts to the \"More\" submenu\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n // Exclude fonts already added to the main menu\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n continue;\n }\n\n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayNameMore[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayNameMore, 100);\n wchar_t* dot = wcsstr(wDisplayNameMore, L\".ttf\");\n if (dot) *dot = L'\\0';\n \n AppendMenuW(hMoreFontsMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayNameMore);\n }\n\n // Add \"More\" submenu to main font menu\n AppendMenuW(hFontSubMenu, MF_POPUP, (UINT_PTR)hMoreFontsMenu, GetLocalizedString(L\"更多\", L\"More\"));\n\n // Color menu\n HMENU hColorSubMenu = CreatePopupMenu();\n // Preset color option menu IDs start from 201 to 201+COLOR_OPTIONS_COUNT-1\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n \n MENUITEMINFO mii = { sizeof(MENUITEMINFO) };\n mii.fMask = MIIM_STRING | MIIM_ID | MIIM_STATE | MIIM_FTYPE;\n mii.fType = MFT_STRING | MFT_OWNERDRAW;\n mii.fState = strcmp(CLOCK_TEXT_COLOR, hexColor) == 0 ? MFS_CHECKED : MFS_UNCHECKED;\n mii.wID = 201 + i; // Preset color menu item IDs start from 201\n mii.dwTypeData = (LPSTR)hexColor;\n \n InsertMenuItem(hColorSubMenu, i, TRUE, &mii);\n }\n AppendMenuW(hColorSubMenu, MF_SEPARATOR, 0, NULL);\n\n // Custom color options\n HMENU hCustomizeMenu = CreatePopupMenu();\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_VALUE, \n GetLocalizedString(L\"颜色值\", L\"Color Value\"));\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_PANEL, \n GetLocalizedString(L\"颜色面板\", L\"Color Panel\"));\n\n AppendMenuW(hColorSubMenu, MF_POPUP, (UINT_PTR)hCustomizeMenu, \n GetLocalizedString(L\"自定义\", L\"Customize\"));\n\n // Add font and color menus to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hFontSubMenu, \n GetLocalizedString(L\"字体\", L\"Font\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hColorSubMenu, \n GetLocalizedString(L\"颜色\", L\"Color\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // About menu\n HMENU hAboutMenu = CreatePopupMenu();\n\n // Add \"About\" menu item here\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_ABOUT, GetLocalizedString(L\"关于\", L\"About\"));\n\n // Add separator\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n\n // Add \"Support\" option - open sponsorship page\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n \n // Add \"Feedback\" option - open different feedback links based on language\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_FEEDBACK, GetLocalizedString(L\"反馈\", L\"Feedback\"));\n \n // Add separator\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n \n // Add \"Help\" option - open user guide webpage\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_HELP, GetLocalizedString(L\"使用指南\", L\"User Guide\"));\n\n // Add \"Check for Updates\" option\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_CHECK_UPDATE, \n GetLocalizedString(L\"检查更新\", L\"Check for Updates\"));\n\n // Language selection menu\n HMENU hLangMenu = CreatePopupMenu();\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE, L\"简体中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE_TRAD, L\"繁體中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_ENGLISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_ENGLISH, L\"English\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_SPANISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_SPANISH, L\"Español\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_FRENCH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_FRENCH, L\"Français\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_GERMAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_GERMAN, L\"Deutsch\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_RUSSIAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_RUSSIAN, L\"Русский\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_PORTUGUESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_PORTUGUESE, L\"Português\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_JAPANESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_JAPANESE, L\"日本語\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_KOREAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_KOREAN, L\"한국어\");\n\n AppendMenuW(hAboutMenu, MF_POPUP, (UINT_PTR)hLangMenu, GetLocalizedString(L\"语言\", L\"Language\"));\n\n // Add reset option to the end of the help menu\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, 200,\n GetLocalizedString(L\"重置\", L\"Reset\"));\n\n // Add about menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hAboutMenu,\n GetLocalizedString(L\"帮助\", L\"Help\"));\n\n // Only keep exit option\n AppendMenuW(hMenu, MF_STRING, 109,\n GetLocalizedString(L\"退出\", L\"Exit\"));\n \n // Display menu\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); // This will allow the menu to close automatically when clicking outside\n DestroyMenu(hMenu);\n}\n\n/**\n * @brief Display tray right-click menu\n * \n * @param hwnd Window handle\n * \n * Create and display the system tray right-click menu, dynamically adjusting menu items based on current application state. Includes:\n * - Timer control (pause/resume, restart)\n * - Time display settings (24-hour format, show seconds)\n * - Pomodoro clock settings\n * - Count-up and countdown mode switching\n * - Quick time preset options\n */\nvoid ShowContextMenu(HWND hwnd) {\n // Read timeout action settings from configuration file before creating the menu\n ReadTimeoutActionFromConfig();\n \n // Set mouse cursor to default arrow to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n HMENU hMenu = CreatePopupMenu();\n \n // Timer management menu - added at the top\n HMENU hTimerManageMenu = CreatePopupMenu();\n \n // Set conditions for whether submenu items should be enabled\n // Timer options should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress\n // 3. If in countdown mode, the timer hasn't ended yet (countdown elapsed time is less than total time)\n BOOL timerRunning = (!CLOCK_SHOW_CURRENT_TIME && \n (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0 && countdown_elapsed_time < CLOCK_TOTAL_TIME)));\n \n // Pause/Resume text changes based on current state\n const wchar_t* pauseResumeText = CLOCK_IS_PAUSED ? \n GetLocalizedString(L\"继续\", L\"Resume\") : \n GetLocalizedString(L\"暂停\", L\"Pause\");\n \n // Submenu items are disabled based on conditions, but parent menu item remains selectable\n AppendMenuW(hTimerManageMenu, MF_STRING | (timerRunning ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_PAUSE_RESUME, pauseResumeText);\n \n // Restart option should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress (regardless of whether countdown has ended)\n BOOL canRestart = (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0)));\n \n AppendMenuW(hTimerManageMenu, MF_STRING | (canRestart ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_RESTART, \n GetLocalizedString(L\"重新开始\", L\"Start Over\"));\n \n // Add timer management menu to main menu - parent menu item is always enabled\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimerManageMenu,\n GetLocalizedString(L\"计时管理\", L\"Timer Control\"));\n \n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n \n // Time display menu\n HMENU hTimeMenu = CreatePopupMenu();\n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_CURRENT_TIME ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_CURRENT_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_USE_24HOUR ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_24HOUR_FORMAT,\n GetLocalizedString(L\"24小时制\", L\"24-Hour Format\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_SECONDS ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_SECONDS,\n GetLocalizedString(L\"显示秒数\", L\"Show Seconds\"));\n \n AppendMenuW(hMenu, MF_POPUP,\n (UINT_PTR)hTimeMenu,\n GetLocalizedString(L\"时间显示\", L\"Time Display\"));\n\n // Before Pomodoro menu, first read the latest configuration values\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\");\n POMODORO_TIMES_COUNT = 0; // Initialize to 0\n \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n char* options = line + 22;\n char* token;\n int index = 0;\n \n token = strtok(options, \",\");\n while (token && index < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[index++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Set the actual number of time options\n POMODORO_TIMES_COUNT = index;\n \n // Ensure at least one valid value\n if (index > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (index > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (index > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[2];\n }\n }\n else if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n sscanf(line, \"POMODORO_LOOP_COUNT=%d\", &POMODORO_LOOP_COUNT);\n // Ensure loop count is at least 1\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n }\n }\n fclose(configFile);\n }\n\n // Pomodoro menu\n HMENU hPomodoroMenu = CreatePopupMenu();\n \n // Add timeBuffer declaration\n wchar_t timeBuffer[64]; // For storing formatted time string\n \n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_START,\n GetLocalizedString(L\"开始\", L\"Start\"));\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Create menu items for each Pomodoro time\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n FormatPomodoroTime(POMODORO_TIMES[i], timeBuffer, sizeof(timeBuffer)/sizeof(wchar_t));\n \n // Support both old and new ID systems\n UINT menuId;\n if (i == 0) menuId = CLOCK_IDM_POMODORO_WORK;\n else if (i == 1) menuId = CLOCK_IDM_POMODORO_BREAK;\n else if (i == 2) menuId = CLOCK_IDM_POMODORO_LBREAK;\n else menuId = CLOCK_IDM_POMODORO_TIME_BASE + i;\n \n // Check if this is the active Pomodoro phase\n BOOL isCurrentPhase = (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n current_pomodoro_time_index == i &&\n !CLOCK_SHOW_CURRENT_TIME &&\n !CLOCK_COUNT_UP && // Add check for not being in count-up mode\n CLOCK_TOTAL_TIME == POMODORO_TIMES[i]);\n \n // Add check mark if it's the current phase\n AppendMenuW(hPomodoroMenu, MF_STRING | (isCurrentPhase ? MF_CHECKED : MF_UNCHECKED), \n menuId, timeBuffer);\n }\n\n // Add loop count option\n wchar_t menuText[64];\n _snwprintf(menuText, sizeof(menuText)/sizeof(wchar_t),\n GetLocalizedString(L\"循环次数: %d\", L\"Loop Count: %d\"),\n POMODORO_LOOP_COUNT);\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_LOOP_COUNT, menuText);\n\n\n // Add separator\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Add combination option\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_COMBINATION,\n GetLocalizedString(L\"组合\", L\"Combination\"));\n \n // Add Pomodoro menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hPomodoroMenu,\n GetLocalizedString(L\"番茄时钟\", L\"Pomodoro\"));\n\n // Count-up menu - changed to direct click to start\n AppendMenuW(hMenu, MF_STRING | (CLOCK_COUNT_UP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_COUNT_UP_START,\n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n\n // Add \"Set Countdown\" option below Count-up\n AppendMenuW(hMenu, MF_STRING, 101, \n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Add quick time options\n for (int i = 0; i < time_options_count; i++) {\n wchar_t menu_item[20];\n _snwprintf(menu_item, sizeof(menu_item)/sizeof(wchar_t), L\"%d\", time_options[i]);\n AppendMenuW(hMenu, MF_STRING, 102 + i, menu_item);\n }\n\n // Display menu\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); // This will allow the menu to close automatically when clicking outside\n DestroyMenu(hMenu);\n}"], ["/Catime/src/update_checker.c", "/**\n * @file update_checker.c\n * @brief Minimalist application update check functionality implementation\n * \n * This file implements functions for checking versions, opening browser for downloads, and deleting configuration files.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/language.h\"\n#include \"../include/dialog_language.h\"\n#include \"../resource/resource.h\"\n\n#pragma comment(lib, \"wininet.lib\")\n\n// Update source URL\n#define GITHUB_API_URL \"https://api.github.com/repos/vladelaina/Catime/releases/latest\"\n#define USER_AGENT \"Catime Update Checker\"\n\n// Version information structure definition\ntypedef struct {\n const char* currentVersion;\n const char* latestVersion;\n const char* downloadUrl;\n} UpdateVersionInfo;\n\n// Function declarations\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\n/**\n * @brief Compare version numbers\n * @param version1 First version string\n * @param version2 Second version string\n * @return Returns 1 if version1 > version2, 0 if equal, -1 if version1 < version2\n */\nint CompareVersions(const char* version1, const char* version2) {\n LOG_DEBUG(\"Comparing versions: '%s' vs '%s'\", version1, version2);\n \n int major1, minor1, patch1;\n int major2, minor2, patch2;\n \n // Parse version numbers\n sscanf(version1, \"%d.%d.%d\", &major1, &minor1, &patch1);\n sscanf(version2, \"%d.%d.%d\", &major2, &minor2, &patch2);\n \n LOG_DEBUG(\"Parsed version1: %d.%d.%d, version2: %d.%d.%d\", major1, minor1, patch1, major2, minor2, patch2);\n \n // Compare major version\n if (major1 > major2) return 1;\n if (major1 < major2) return -1;\n \n // Compare minor version\n if (minor1 > minor2) return 1;\n if (minor1 < minor2) return -1;\n \n // Compare patch version\n if (patch1 > patch2) return 1;\n if (patch1 < patch2) return -1;\n \n return 0;\n}\n\n/**\n * @brief Parse JSON response to get latest version and download URL\n */\nBOOL ParseLatestVersionFromJson(const char* jsonResponse, char* latestVersion, size_t maxLen, \n char* downloadUrl, size_t urlMaxLen) {\n LOG_DEBUG(\"Starting to parse JSON response, extracting version information\");\n \n // Find version number\n const char* tagNamePos = strstr(jsonResponse, \"\\\"tag_name\\\":\");\n if (!tagNamePos) {\n LOG_ERROR(\"JSON parsing failed: tag_name field not found\");\n return FALSE;\n }\n \n const char* firstQuote = strchr(tagNamePos + 11, '\\\"');\n if (!firstQuote) return FALSE;\n \n const char* secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy version number\n size_t versionLen = secondQuote - (firstQuote + 1);\n if (versionLen >= maxLen) versionLen = maxLen - 1;\n \n strncpy(latestVersion, firstQuote + 1, versionLen);\n latestVersion[versionLen] = '\\0';\n \n // If version starts with 'v', remove it\n if (latestVersion[0] == 'v' || latestVersion[0] == 'V') {\n memmove(latestVersion, latestVersion + 1, versionLen);\n }\n \n // Find download URL\n const char* downloadUrlPos = strstr(jsonResponse, \"\\\"browser_download_url\\\":\");\n if (!downloadUrlPos) {\n LOG_ERROR(\"JSON parsing failed: browser_download_url field not found\");\n return FALSE;\n }\n \n firstQuote = strchr(downloadUrlPos + 22, '\\\"');\n if (!firstQuote) return FALSE;\n \n secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy download URL\n size_t urlLen = secondQuote - (firstQuote + 1);\n if (urlLen >= urlMaxLen) urlLen = urlMaxLen - 1;\n \n strncpy(downloadUrl, firstQuote + 1, urlLen);\n downloadUrl[urlLen] = '\\0';\n \n return TRUE;\n}\n\n/**\n * @brief Exit message dialog procedure\n */\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Get localized exit text\n const wchar_t* exitText = GetLocalizedString(L\"程序即将退出\", L\"The application will exit now\");\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, exitText);\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, L\"\"); // Clear version text\n \n // Set OK button text\n const wchar_t* okText = GetLocalizedString(L\"确定\", L\"OK\");\n SetDlgItemTextW(hwndDlg, IDOK, okText);\n \n // Hide Yes/No buttons, only show OK button\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_SHOW);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"Catime - 更新提示\", L\"Catime - Update Notice\");\n SetWindowTextW(hwndDlg, titleText);\n \n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display custom exit message dialog\n */\nvoid ShowExitMessageDialog(HWND hwnd) {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n ExitMsgDlgProc);\n}\n\n/**\n * @brief Update dialog procedure\n */\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static UpdateVersionInfo* versionInfo = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Save version information\n versionInfo = (UpdateVersionInfo*)lParam;\n \n // Format display text\n if (versionInfo) {\n // Convert ASCII version numbers to Unicode\n wchar_t currentVersionW[64] = {0};\n wchar_t newVersionW[64] = {0};\n \n // Convert version numbers to wide characters\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->currentVersion, -1, \n currentVersionW, sizeof(currentVersionW)/sizeof(wchar_t));\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->latestVersion, -1, \n newVersionW, sizeof(newVersionW)/sizeof(wchar_t));\n \n // Use pre-formatted strings instead of trying to format ourselves\n wchar_t displayText[256];\n \n // Get localized version text (pre-formatted)\n const wchar_t* currentVersionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n const wchar_t* newVersionText = GetLocalizedString(L\"新版本:\", L\"New version:\");\n\n // Manually build formatted string\n StringCbPrintfW(displayText, sizeof(displayText),\n L\"%s %s\\n%s %s\",\n currentVersionText, currentVersionW,\n newVersionText, newVersionW);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, displayText);\n \n // Set button text\n const wchar_t* yesText = GetLocalizedString(L\"是\", L\"Yes\");\n const wchar_t* noText = GetLocalizedString(L\"否\", L\"No\");\n \n // Explicitly set button text, not relying on dialog resource\n SetDlgItemTextW(hwndDlg, IDYES, yesText);\n SetDlgItemTextW(hwndDlg, IDNO, noText);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"发现新版本\", L\"Update Available\");\n SetWindowTextW(hwndDlg, titleText);\n \n // Hide exit text and OK button, show Yes/No buttons\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, L\"\");\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_HIDE);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDNO);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update notification dialog\n */\nint ShowUpdateNotification(HWND hwnd, const char* currentVersion, const char* latestVersion, const char* downloadUrl) {\n // Create version info structure\n UpdateVersionInfo versionInfo;\n versionInfo.currentVersion = currentVersion;\n versionInfo.latestVersion = latestVersion;\n versionInfo.downloadUrl = downloadUrl;\n \n // Display custom dialog\n return DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n UpdateDlgProc, \n (LPARAM)&versionInfo);\n}\n\n/**\n * @brief Update error dialog procedure\n */\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Get error message text\n const wchar_t* errorMsg = (const wchar_t*)lParam;\n if (errorMsg) {\n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_ERROR_TEXT, errorMsg);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update error dialog\n */\nvoid ShowUpdateErrorDialog(HWND hwnd, const wchar_t* errorMsg) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_ERROR_DIALOG), \n hwnd, \n UpdateErrorDlgProc, \n (LPARAM)errorMsg);\n}\n\n/**\n * @brief No update required dialog procedure\n */\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_NO_UPDATE_DIALOG);\n \n // Get current version information\n const char* currentVersion = (const char*)lParam;\n if (currentVersion) {\n // Get localized basic text\n const wchar_t* baseText = GetDialogLocalizedString(IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT);\n if (!baseText) {\n // If localized text not found, use default text\n baseText = L\"You are already using the latest version!\";\n }\n \n // Get localized \"Current version\" text\n const wchar_t* versionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n \n // Create complete message including version number\n wchar_t fullMessage[256];\n StringCbPrintfW(fullMessage, sizeof(fullMessage),\n L\"%s\\n%s %hs\", baseText, versionText, currentVersion);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_NO_UPDATE_TEXT, fullMessage);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display no update required dialog\n * @param hwnd Parent window handle\n * @param currentVersion Current version number\n */\nvoid ShowNoUpdateDialog(HWND hwnd, const char* currentVersion) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_NO_UPDATE_DIALOG), \n hwnd, \n NoUpdateDlgProc, \n (LPARAM)currentVersion);\n}\n\n/**\n * @brief Open browser to download update and exit program\n */\nBOOL OpenBrowserForUpdateAndExit(const char* url, HWND hwnd) {\n // Open browser\n HINSTANCE hInstance = ShellExecuteA(hwnd, \"open\", url, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)hInstance <= 32) {\n // Failed to open browser\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法打开浏览器下载更新\", L\"Could not open browser to download update\"));\n return FALSE;\n }\n \n LOG_INFO(\"Successfully opened browser, preparing to exit program\");\n \n // Prompt user\n wchar_t message[512];\n StringCbPrintfW(message, sizeof(message),\n L\"即将退出程序\");\n \n LOG_INFO(\"Sending exit message to main window\");\n // Use custom dialog to display exit message\n ShowExitMessageDialog(hwnd);\n \n // Exit program\n PostMessage(hwnd, WM_CLOSE, 0, 0);\n return TRUE;\n}\n\n/**\n * @brief General update check function\n */\nvoid CheckForUpdateInternal(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Starting update check process, silent mode: %s\", silentCheck ? \"yes\" : \"no\");\n \n // Create Internet session\n LOG_INFO(\"Attempting to create Internet session\");\n HINTERNET hInternet = InternetOpenA(USER_AGENT, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);\n if (!hInternet) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to create Internet session, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法创建Internet连接\", L\"Could not create Internet connection\"));\n }\n return;\n }\n LOG_INFO(\"Internet session created successfully\");\n \n // Connect to update API\n LOG_INFO(\"Attempting to connect to GitHub API: %s\", GITHUB_API_URL);\n HINTERNET hConnect = InternetOpenUrlA(hInternet, GITHUB_API_URL, NULL, 0, \n INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, 0);\n if (!hConnect) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to connect to GitHub API, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n InternetCloseHandle(hInternet);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法连接到更新服务器\", L\"Could not connect to update server\"));\n }\n return;\n }\n LOG_INFO(\"Successfully connected to GitHub API\");\n \n // Allocate buffer\n LOG_INFO(\"Allocating memory buffer for API response\");\n char* buffer = (char*)malloc(8192);\n if (!buffer) {\n LOG_ERROR(\"Memory allocation failed, could not allocate buffer for API response\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n \n // Read response\n LOG_INFO(\"Starting to read response data from API\");\n DWORD bytesRead = 0;\n DWORD totalBytes = 0;\n size_t bufferSize = 8192;\n \n while (InternetReadFile(hConnect, buffer + totalBytes, \n bufferSize - totalBytes - 1, &bytesRead) && bytesRead > 0) {\n LOG_DEBUG(\"Read %lu bytes of data, accumulated %lu bytes\", bytesRead, totalBytes + bytesRead);\n totalBytes += bytesRead;\n if (totalBytes >= bufferSize - 256) {\n size_t newSize = bufferSize * 2;\n char* newBuffer = (char*)realloc(buffer, newSize);\n if (!newBuffer) {\n // Fix: If realloc fails, free the original buffer and abort\n LOG_ERROR(\"Failed to reallocate buffer, current size: %zu bytes\", bufferSize);\n free(buffer);\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n LOG_DEBUG(\"Buffer expanded, new size: %zu bytes\", newSize);\n buffer = newBuffer;\n bufferSize = newSize;\n }\n }\n \n buffer[totalBytes] = '\\0';\n LOG_INFO(\"Successfully read API response, total %lu bytes of data\", totalBytes);\n \n // Close connection\n LOG_INFO(\"Closing Internet connection\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n \n // Parse version and download URL\n LOG_INFO(\"Starting to parse API response, extracting version info and download URL\");\n char latestVersion[32] = {0};\n char downloadUrl[256] = {0};\n if (!ParseLatestVersionFromJson(buffer, latestVersion, sizeof(latestVersion), \n downloadUrl, sizeof(downloadUrl))) {\n LOG_ERROR(\"Failed to parse version information, response may not be valid JSON format\");\n free(buffer);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法解析版本信息\", L\"Could not parse version information\"));\n }\n return;\n }\n LOG_INFO(\"Successfully parsed version information, GitHub latest version: %s, download URL: %s\", latestVersion, downloadUrl);\n \n free(buffer);\n \n // Get current version\n const char* currentVersion = CATIME_VERSION;\n LOG_INFO(\"Current application version: %s\", currentVersion);\n \n // Compare versions\n LOG_INFO(\"Comparing version numbers: current version %s vs. latest version %s\", currentVersion, latestVersion);\n int versionCompare = CompareVersions(latestVersion, currentVersion);\n if (versionCompare > 0) {\n // New version available\n LOG_INFO(\"New version found! Current: %s, Available update: %s\", currentVersion, latestVersion);\n int response = ShowUpdateNotification(hwnd, currentVersion, latestVersion, downloadUrl);\n LOG_INFO(\"Update prompt dialog result: %s\", response == IDYES ? \"User agreed to update\" : \"User declined update\");\n \n if (response == IDYES) {\n LOG_INFO(\"User chose to update now, preparing to open browser and exit program\");\n OpenBrowserForUpdateAndExit(downloadUrl, hwnd);\n }\n } else if (!silentCheck) {\n // Already using latest version\n LOG_INFO(\"Current version %s is already the latest, no update needed\", currentVersion);\n \n // Use localized strings instead of building complete message\n ShowNoUpdateDialog(hwnd, currentVersion);\n } else {\n LOG_INFO(\"Silent check mode: Current version %s is already the latest, no prompt shown\", currentVersion);\n }\n \n LOG_INFO(\"Update check process complete\");\n}\n\n/**\n * @brief Check for application updates\n */\nvoid CheckForUpdate(HWND hwnd) {\n CheckForUpdateInternal(hwnd, FALSE);\n}\n\n/**\n * @brief Silently check for application updates\n */\nvoid CheckForUpdateSilent(HWND hwnd, BOOL silentCheck) {\n CheckForUpdateInternal(hwnd, silentCheck);\n} \n"], ["/Catime/src/tray_events.c", "/**\n * @file tray_events.c\n * @brief Implementation of system tray event handling module\n * \n * This module implements the event handling functionality for the application's system tray,\n * including response to various mouse events on the tray icon, menu display and control,\n * as well as tray operations related to the timer such as pause/resume and restart.\n * It provides core functionality for users to quickly control the application through the tray icon.\n */\n\n#include \n#include \n#include \"../include/tray_events.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/window_events.h\"\n#include \"../resource/resource.h\"\n\n// Declaration of function to read timeout action from configuration file\nextern void ReadTimeoutActionFromConfig(void);\n\n/**\n * @brief Handle system tray messages\n * @param hwnd Window handle\n * @param uID Tray icon ID\n * @param uMouseMsg Mouse message type\n * \n * Process mouse events for the system tray, displaying different context menus based on the event type:\n * - Left click: Display main function context menu, including timer control functions\n * - Right click: Display color selection menu for quickly changing display color\n * \n * All menu item command processing is implemented in the corresponding menu display module.\n */\nvoid HandleTrayIconMessage(HWND hwnd, UINT uID, UINT uMouseMsg) {\n // Set default cursor to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n if (uMouseMsg == WM_RBUTTONUP) {\n ShowColorMenu(hwnd);\n }\n else if (uMouseMsg == WM_LBUTTONUP) {\n ShowContextMenu(hwnd);\n }\n}\n\n/**\n * @brief Pause or resume timer\n * @param hwnd Window handle\n * \n * Toggle timer pause/resume state based on current status:\n * 1. Check if there is an active timer (countdown or count-up)\n * 2. If timer is active, toggle pause/resume state\n * 3. When paused, record current time point and stop timer\n * 4. When resumed, restart timer\n * 5. Refresh window to reflect new state\n * \n * Note: Can only operate when displaying timer (not current time) and timer is active\n */\nvoid PauseResumeTimer(HWND hwnd) {\n // Check if there is an active timer\n if (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || CLOCK_TOTAL_TIME > 0)) {\n \n // Toggle pause/resume state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n if (CLOCK_IS_PAUSED) {\n // If paused, record current time point\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n // Stop timer\n KillTimer(hwnd, 1);\n \n // Pause playing notification audio (new addition)\n extern BOOL PauseNotificationSound(void);\n PauseNotificationSound();\n } else {\n // If resumed, restart timer\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Resume notification audio (new addition)\n extern BOOL ResumeNotificationSound(void);\n ResumeNotificationSound();\n }\n \n // Update window to reflect new state\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart timer\n * @param hwnd Window handle\n * \n * Reset timer to initial state and continue running, keeping current timer type unchanged:\n * 1. Read current timeout action settings\n * 2. Reset timer progress based on current mode (countdown/count-up)\n * 3. Reset all related timer state variables\n * 4. Cancel pause state, ensure timer is running\n * 5. Refresh window and ensure window is on top after reset\n * \n * This operation does not change the timer mode or total duration, it only resets progress to initial state.\n */\nvoid RestartTimer(HWND hwnd) {\n // Stop any notification audio that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Determine operation based on current mode\n if (!CLOCK_COUNT_UP) {\n // Countdown mode\n if (CLOCK_TOTAL_TIME > 0) {\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n } else {\n // Count-up mode\n countup_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Update window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure window is on top and visible\n HandleWindowReset(hwnd);\n}\n\n/**\n * @brief Set startup mode\n * @param hwnd Window handle\n * @param mode Startup mode (\"COUNTDOWN\"/\"COUNT_UP\"/\"SHOW_TIME\"/\"NO_DISPLAY\")\n * \n * Set the application's default startup mode and save it to the configuration file:\n * 1. Save the selected mode to the configuration file\n * 2. Update menu item checked state to reflect current setting\n * 3. Refresh window display\n * \n * The startup mode determines the default behavior of the application at startup, such as whether to display current time or start timing.\n * The setting will take effect the next time the program starts.\n */\nvoid SetStartupMode(HWND hwnd, const char* mode) {\n // Save startup mode to configuration file\n WriteConfigStartupMode(mode);\n \n // Update menu item checked state\n HMENU hMenu = GetMenu(hwnd);\n if (hMenu) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Open user guide webpage\n * \n * Use ShellExecute to open Catime's user guide webpage,\n * providing detailed software instructions and help documentation for users.\n * URL: https://vladelaina.github.io/Catime/guide\n */\nvoid OpenUserGuide(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/guide\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open support page\n * \n * Use ShellExecute to open Catime's support page,\n * providing channels for users to support the developer.\n * URL: https://vladelaina.github.io/Catime/support\n */\nvoid OpenSupportPage(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open feedback page\n * \n * Open different feedback channels based on current language setting:\n * - Simplified Chinese: Open bilibili private message page\n * - Other languages: Open GitHub Issues page\n */\nvoid OpenFeedbackPage(void) {\n extern AppLanguage CURRENT_LANGUAGE; // Declare external variable\n \n // Choose different feedback links based on language\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP) {\n // Simplified Chinese users open bilibili private message\n ShellExecuteW(NULL, L\"open\", URL_FEEDBACK, NULL, NULL, SW_SHOWNORMAL);\n } else {\n // Users of other languages open GitHub Issues\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime/issues\", NULL, NULL, SW_SHOWNORMAL);\n }\n}"], ["/Catime/src/timer_events.c", "/**\n * @file timer_events.c\n * @brief Implementation of timer event handling\n * \n * This file implements the functionality related to the application's timer event handling,\n * including countdown and count-up mode event processing.\n */\n\n#include \n#include \n#include \"../include/timer_events.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \"../include/window.h\"\n#include \"audio_player.h\" // Include header reference\n\n// Maximum capacity of Pomodoro time list\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Index of the currently executing Pomodoro time\nint current_pomodoro_time_index = 0;\n\n// Define current_pomodoro_phase variable, which is declared as extern in pomodoro.h\nPOMODORO_PHASE current_pomodoro_phase = POMODORO_PHASE_IDLE;\n\n// Number of completed Pomodoro cycles\nint complete_pomodoro_cycles = 0;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\n\n// Variable declarations imported from main.c, for timeout actions\nextern int elapsed_time;\nextern BOOL message_shown;\n\n// Custom message text imported from config.c\nextern char CLOCK_TIMEOUT_MESSAGE_TEXT[100];\nextern char POMODORO_TIMEOUT_MESSAGE_TEXT[100]; // New Pomodoro-specific prompt\nextern char POMODORO_CYCLE_COMPLETE_TEXT[100];\n\n// Define ClockState type\ntypedef enum {\n CLOCK_STATE_IDLE,\n CLOCK_STATE_COUNTDOWN,\n CLOCK_STATE_COUNTUP,\n CLOCK_STATE_POMODORO\n} ClockState;\n\n// Define PomodoroState type\ntypedef struct {\n BOOL isLastCycle;\n int cycleIndex;\n int totalCycles;\n} PomodoroState;\n\nextern HWND g_hwnd; // Main window handle\nextern ClockState g_clockState;\nextern PomodoroState g_pomodoroState;\n\n// Timer behavior function declarations\nextern void ShowTrayNotification(HWND hwnd, const char* message);\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void OpenFileByPath(const char* filePath);\nextern void OpenWebsite(const char* url);\nextern void SleepComputer(void);\nextern void ShutdownComputer(void);\nextern void RestartComputer(void);\nextern void SetTimeDisplay(void);\nextern void ShowCountUp(HWND hwnd);\n\n// Add external function declaration to the beginning of the file or before the function\nextern void StopNotificationSound(void);\n\n/**\n * @brief Convert UTF-8 encoded char* string to wchar_t* string\n * @param utf8String Input UTF-8 string\n * @return Converted wchar_t* string, memory needs to be freed with free() after use. Returns NULL if conversion fails.\n */\nstatic wchar_t* Utf8ToWideChar(const char* utf8String) {\n if (!utf8String || utf8String[0] == '\\0') {\n return NULL; // Return NULL to handle empty strings or NULL pointers\n }\n int size_needed = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, NULL, 0);\n if (size_needed == 0) {\n // Conversion failed\n return NULL;\n }\n wchar_t* wideString = (wchar_t*)malloc(size_needed * sizeof(wchar_t));\n if (!wideString) {\n // Memory allocation failed\n return NULL;\n }\n int result = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, wideString, size_needed);\n if (result == 0) {\n // Conversion failed\n free(wideString);\n return NULL;\n }\n return wideString;\n}\n\n/**\n * @brief Convert wide character string to UTF-8 encoded regular string and display notification\n * @param hwnd Window handle\n * @param message Wide character string message to display (read from configuration and converted)\n */\nstatic void ShowLocalizedNotification(HWND hwnd, const wchar_t* message) {\n // Don't display if message is empty\n if (!message || message[0] == L'\\0') {\n return;\n }\n\n // Calculate required buffer size\n int size_needed = WideCharToMultiByte(CP_UTF8, 0, message, -1, NULL, 0, NULL, NULL);\n if (size_needed == 0) return; // Conversion failed\n\n // Allocate memory\n char* utf8Msg = (char*)malloc(size_needed);\n if (utf8Msg) {\n // Convert to UTF-8\n int result = WideCharToMultiByte(CP_UTF8, 0, message, -1, utf8Msg, size_needed, NULL, NULL);\n\n if (result > 0) {\n // Display notification using the new ShowNotification function\n ShowNotification(hwnd, utf8Msg);\n \n // If timeout action is MESSAGE, play notification audio\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE) {\n // Read the latest audio settings\n ReadNotificationSoundConfig();\n \n // Play notification audio\n PlayNotificationSound(hwnd);\n }\n }\n\n // Free memory\n free(utf8Msg);\n }\n}\n\n/**\n * @brief Set Pomodoro to work phase\n * \n * Reset all timer counts and set Pomodoro to work phase\n */\nvoid InitializePomodoro(void) {\n // Use existing enum value POMODORO_PHASE_WORK instead of POMODORO_PHASE_RUNNING\n current_pomodoro_phase = POMODORO_PHASE_WORK;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Set initial countdown to the first time value\n if (POMODORO_TIMES_COUNT > 0) {\n CLOCK_TOTAL_TIME = POMODORO_TIMES[0];\n } else {\n // If no time is configured, use default 25 minutes\n CLOCK_TOTAL_TIME = 1500;\n }\n \n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n}\n\n/**\n * @brief Handle timer messages\n * @param hwnd Window handle\n * @param wp Message parameter\n * @return BOOL Whether the message was handled\n */\nBOOL HandleTimerEvent(HWND hwnd, WPARAM wp) {\n if (wp == 1) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // In current time display mode, reset the last displayed second on each timer trigger to ensure the latest time is displayed\n extern int last_displayed_second;\n last_displayed_second = -1; // Force reset of seconds cache to ensure the latest system time is displayed each time\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n return TRUE;\n }\n\n // If timer is paused, don't update time\n if (CLOCK_IS_PAUSED) {\n return TRUE;\n }\n\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time++;\n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n if (countdown_elapsed_time < CLOCK_TOTAL_TIME) {\n countdown_elapsed_time++;\n if (countdown_elapsed_time >= CLOCK_TOTAL_TIME && !countdown_message_shown) {\n countdown_message_shown = TRUE;\n\n // Re-read message text from config file before displaying notification\n ReadNotificationMessagesConfig();\n // Force re-read notification type config to ensure latest settings are used\n ReadNotificationTypeConfig();\n \n // Variable declaration before branches to ensure availability in all branches\n wchar_t* timeoutMsgW = NULL;\n\n // Check if in Pomodoro mode - must meet all three conditions:\n // 1. Current Pomodoro phase is not IDLE \n // 2. Pomodoro time configuration is valid\n // 3. Current countdown total time matches the time at current index in the Pomodoro time list\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE && \n POMODORO_TIMES_COUNT > 0 && \n current_pomodoro_time_index < POMODORO_TIMES_COUNT &&\n CLOCK_TOTAL_TIME == POMODORO_TIMES[current_pomodoro_time_index]) {\n \n // Use Pomodoro-specific prompt message\n timeoutMsgW = Utf8ToWideChar(POMODORO_TIMEOUT_MESSAGE_TEXT);\n \n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"番茄钟时间到!\"); // Fallback\n }\n \n // Move to next time period\n current_pomodoro_time_index++;\n \n // Check if a complete cycle has been finished\n if (current_pomodoro_time_index >= POMODORO_TIMES_COUNT) {\n // Reset index back to the first time\n current_pomodoro_time_index = 0;\n \n // Increase completed cycle count\n complete_pomodoro_cycles++;\n \n // Check if all configured loop counts have been completed\n if (complete_pomodoro_cycles >= POMODORO_LOOP_COUNT) {\n // All loop counts completed, end Pomodoro\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_TOTAL_TIME = 0;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n \n // Try to read and convert completion message from config\n wchar_t* cycleCompleteMsgW = Utf8ToWideChar(POMODORO_CYCLE_COMPLETE_TEXT);\n // Display completion prompt (using config or default value)\n if (cycleCompleteMsgW) {\n ShowLocalizedNotification(hwnd, cycleCompleteMsgW);\n free(cycleCompleteMsgW); // Free completion message memory\n } else {\n ShowLocalizedNotification(hwnd, L\"所有番茄钟循环完成!\"); // Fallback\n }\n \n // Switch to idle state - add the following code\n CLOCK_COUNT_UP = FALSE; // Ensure not in count-up mode\n CLOCK_SHOW_CURRENT_TIME = FALSE; // Ensure not in current time display mode\n message_shown = TRUE; // Mark message as shown\n \n // Force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n KillTimer(hwnd, 1);\n if (timeoutMsgW) free(timeoutMsgW); // Free timeout message memory\n return TRUE;\n }\n }\n \n // Set countdown for next time period\n CLOCK_TOTAL_TIME = POMODORO_TIMES[current_pomodoro_time_index];\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n \n // If it's the first time period in a new round, display cycle prompt\n if (current_pomodoro_time_index == 0 && complete_pomodoro_cycles > 0) {\n wchar_t cycleMsg[100];\n // GetLocalizedString needs to be reconsidered, or hardcode English/Chinese\n // Temporarily keep the original approach, but ideally should be configurable\n const wchar_t* formatStr = GetLocalizedString(L\"开始第 %d 轮番茄钟\", L\"Starting Pomodoro cycle %d\");\n swprintf(cycleMsg, 100, formatStr, complete_pomodoro_cycles + 1);\n ShowLocalizedNotification(hwnd, cycleMsg); // Call the modified function\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // Not in Pomodoro mode, or switched to normal countdown mode\n // Use normal countdown prompt message\n timeoutMsgW = Utf8ToWideChar(CLOCK_TIMEOUT_MESSAGE_TEXT);\n \n // Only display notification message if timeout action is not open file, lock, shutdown, or restart\n if (CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_OPEN_FILE && \n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_LOCK &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SHUTDOWN &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_RESTART &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SLEEP) {\n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"时间到!\"); // Fallback\n }\n }\n \n // If current mode is not Pomodoro (manually switched to normal countdown), ensure not to return to Pomodoro cycle\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n (current_pomodoro_time_index >= POMODORO_TIMES_COUNT ||\n CLOCK_TOTAL_TIME != POMODORO_TIMES[current_pomodoro_time_index])) {\n // If switched to normal countdown, reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n // If sleep option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute sleep command\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n return TRUE;\n }\n \n // If shutdown option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute shutdown command\n system(\"shutdown /s /t 0\");\n return TRUE;\n }\n \n // If restart option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute restart command\n system(\"shutdown /r /t 0\");\n return TRUE;\n }\n \n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n // Notification already displayed, no additional operation needed\n break;\n case TIMEOUT_ACTION_LOCK:\n LockWorkStation();\n break;\n case TIMEOUT_ACTION_OPEN_FILE: {\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0) {\n wchar_t wPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_FILE_PATH, -1, wPath, MAX_PATH);\n \n HINSTANCE result = ShellExecuteW(NULL, L\"open\", wPath, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)result <= 32) {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"无法打开文件\", L\"Failed to open file\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case TIMEOUT_ACTION_SHOW_TIME:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to count-up mode and reset\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countup_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set Pomodoro state to idle\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n wchar_t wideUrl[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_WEBSITE_URL, -1, wideUrl, MAX_PATH);\n ShellExecuteW(NULL, L\"open\", wideUrl, NULL, NULL, SW_NORMAL);\n }\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n }\n\n // Free converted wide string memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return TRUE;\n }\n return FALSE;\n}\n\nvoid OnTimerTimeout(HWND hwnd) {\n // Execute different behaviors based on timeout action\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE: {\n char utf8Msg[256] = {0};\n \n // Select different prompt messages based on current state\n if (g_clockState == CLOCK_STATE_POMODORO) {\n // Check if Pomodoro has completed all cycles\n if (g_pomodoroState.isLastCycle && g_pomodoroState.cycleIndex >= g_pomodoroState.totalCycles - 1) {\n strncpy(utf8Msg, POMODORO_CYCLE_COMPLETE_TEXT, sizeof(utf8Msg) - 1);\n } else {\n strncpy(utf8Msg, POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n } else {\n strncpy(utf8Msg, CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n \n utf8Msg[sizeof(utf8Msg) - 1] = '\\0'; // Ensure string ends with null character\n \n // Display custom prompt message\n ShowNotification(hwnd, utf8Msg);\n \n // Read latest audio settings and play alert sound\n ReadNotificationSoundConfig();\n PlayNotificationSound(hwnd);\n \n break;\n }\n case TIMEOUT_ACTION_RUN_COMMAND: {\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n case TIMEOUT_ACTION_HTTP_REQUEST: {\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n\n }\n}\n\n// Add missing global variable definitions (if not defined elsewhere)\n#ifndef STUB_VARIABLES_DEFINED\n#define STUB_VARIABLES_DEFINED\n// Main window handle\nHWND g_hwnd = NULL;\n// Current clock state\nClockState g_clockState = CLOCK_STATE_IDLE;\n// Pomodoro state\nPomodoroState g_pomodoroState = {FALSE, 0, 1};\n#endif\n\n// Add stub function definitions if needed\n#ifndef STUB_FUNCTIONS_DEFINED\n#define STUB_FUNCTIONS_DEFINED\n__attribute__((weak)) void SleepComputer(void) {\n // This is a weak symbol definition, if there's an actual implementation elsewhere, that implementation will be used\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n}\n\n__attribute__((weak)) void ShutdownComputer(void) {\n system(\"shutdown /s /t 0\");\n}\n\n__attribute__((weak)) void RestartComputer(void) {\n system(\"shutdown /r /t 0\");\n}\n\n__attribute__((weak)) void SetTimeDisplay(void) {\n // Stub implementation for setting time display\n}\n\n__attribute__((weak)) void ShowCountUp(HWND hwnd) {\n // Stub implementation for showing count-up\n}\n#endif\n"], ["/Catime/src/log.c", "/**\n * @file log.c\n * @brief Log recording functionality implementation\n * \n * Implements logging functionality, including file writing, error code retrieval, etc.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/log.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n\n// Add check for ARM64 macro\n#ifndef PROCESSOR_ARCHITECTURE_ARM64\n#define PROCESSOR_ARCHITECTURE_ARM64 12\n#endif\n\n// Log file path\nstatic char LOG_FILE_PATH[MAX_PATH] = {0};\nstatic FILE* logFile = NULL;\nstatic CRITICAL_SECTION logCS;\n\n// Log level string representations\nstatic const char* LOG_LEVEL_STRINGS[] = {\n \"DEBUG\",\n \"INFO\",\n \"WARNING\",\n \"ERROR\",\n \"FATAL\"\n};\n\n/**\n * @brief Get operating system version information\n * \n * Use Windows API to get operating system version, version number, build and other information\n */\nstatic void LogSystemInformation(void) {\n // Get system information\n SYSTEM_INFO si;\n GetNativeSystemInfo(&si);\n \n // Use RtlGetVersion to get system version more accurately, because GetVersionEx was changed in newer Windows versions\n typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);\n HMODULE hNtdll = GetModuleHandleW(L\"ntdll.dll\");\n \n DWORD major = 0, minor = 0, build = 0;\n BOOL isWorkstation = TRUE;\n BOOL isServer = FALSE;\n \n if (hNtdll) {\n RtlGetVersionPtr pRtlGetVersion = (RtlGetVersionPtr)GetProcAddress(hNtdll, \"RtlGetVersion\");\n if (pRtlGetVersion) {\n RTL_OSVERSIONINFOW rovi = { 0 };\n rovi.dwOSVersionInfoSize = sizeof(rovi);\n if (pRtlGetVersion(&rovi) == 0) { // STATUS_SUCCESS = 0\n major = rovi.dwMajorVersion;\n minor = rovi.dwMinorVersion;\n build = rovi.dwBuildNumber;\n }\n }\n }\n \n // If the above method fails, try the method below\n if (major == 0) {\n OSVERSIONINFOEXA osvi;\n ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA));\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA);\n \n typedef LONG (WINAPI* PRTLGETVERSION)(OSVERSIONINFOEXW*);\n PRTLGETVERSION pRtlGetVersion;\n pRtlGetVersion = (PRTLGETVERSION)GetProcAddress(GetModuleHandle(TEXT(\"ntdll.dll\")), \"RtlGetVersion\");\n \n if (pRtlGetVersion) {\n pRtlGetVersion((OSVERSIONINFOEXW*)&osvi);\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n // Finally try using GetVersionExA, although it may not be accurate\n if (GetVersionExA((OSVERSIONINFOA*)&osvi)) {\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n WriteLog(LOG_LEVEL_WARNING, \"Unable to get operating system version information\");\n }\n }\n }\n \n // Detect specific Windows version\n const char* windowsVersion = \"Unknown version\";\n \n // Determine specific version based on version number\n if (major == 10) {\n if (build >= 22000) {\n windowsVersion = \"Windows 11\";\n } else {\n windowsVersion = \"Windows 10\";\n }\n } else if (major == 6) {\n if (minor == 3) {\n windowsVersion = \"Windows 8.1\";\n } else if (minor == 2) {\n windowsVersion = \"Windows 8\";\n } else if (minor == 1) {\n windowsVersion = \"Windows 7\";\n } else if (minor == 0) {\n windowsVersion = \"Windows Vista\";\n }\n } else if (major == 5) {\n if (minor == 2) {\n windowsVersion = \"Windows Server 2003\";\n if (isWorkstation && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {\n windowsVersion = \"Windows XP Professional x64\";\n }\n } else if (minor == 1) {\n windowsVersion = \"Windows XP\";\n } else if (minor == 0) {\n windowsVersion = \"Windows 2000\";\n }\n }\n \n WriteLog(LOG_LEVEL_INFO, \"Operating System: %s (%d.%d) Build %d %s\", \n windowsVersion,\n major, minor, \n build, \n isWorkstation ? \"Workstation\" : \"Server\");\n \n // CPU architecture\n const char* arch;\n switch (si.wProcessorArchitecture) {\n case PROCESSOR_ARCHITECTURE_AMD64:\n arch = \"x64 (AMD64)\";\n break;\n case PROCESSOR_ARCHITECTURE_INTEL:\n arch = \"x86 (Intel)\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM:\n arch = \"ARM\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM64:\n arch = \"ARM64\";\n break;\n default:\n arch = \"Unknown\";\n break;\n }\n WriteLog(LOG_LEVEL_INFO, \"CPU Architecture: %s\", arch);\n \n // System memory information\n MEMORYSTATUSEX memInfo;\n memInfo.dwLength = sizeof(MEMORYSTATUSEX);\n if (GlobalMemoryStatusEx(&memInfo)) {\n WriteLog(LOG_LEVEL_INFO, \"Physical Memory: %.2f GB / %.2f GB (%d%% used)\", \n (memInfo.ullTotalPhys - memInfo.ullAvailPhys) / (1024.0 * 1024 * 1024), \n memInfo.ullTotalPhys / (1024.0 * 1024 * 1024),\n memInfo.dwMemoryLoad);\n }\n \n // Don't get screen resolution information as it's not accurate and not necessary for debugging\n \n // Check if UAC is enabled\n BOOL uacEnabled = FALSE;\n HANDLE hToken;\n if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {\n TOKEN_ELEVATION_TYPE elevationType;\n DWORD dwSize;\n if (GetTokenInformation(hToken, TokenElevationType, &elevationType, sizeof(elevationType), &dwSize)) {\n uacEnabled = (elevationType != TokenElevationTypeDefault);\n }\n CloseHandle(hToken);\n }\n WriteLog(LOG_LEVEL_INFO, \"UAC Status: %s\", uacEnabled ? \"Enabled\" : \"Disabled\");\n \n // Check if running as administrator\n BOOL isAdmin = FALSE;\n SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;\n PSID AdministratorsGroup;\n if (AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup)) {\n if (CheckTokenMembership(NULL, AdministratorsGroup, &isAdmin)) {\n WriteLog(LOG_LEVEL_INFO, \"Administrator Privileges: %s\", isAdmin ? \"Yes\" : \"No\");\n }\n FreeSid(AdministratorsGroup);\n }\n}\n\n/**\n * @brief Get log file path\n * \n * Build log filename based on config file path\n * \n * @param logPath Log path buffer\n * @param size Buffer size\n */\nstatic void GetLogFilePath(char* logPath, size_t size) {\n char configPath[MAX_PATH] = {0};\n \n // Get directory containing config file\n GetConfigPath(configPath, MAX_PATH);\n \n // Determine config file directory\n char* lastSeparator = strrchr(configPath, '\\\\');\n if (lastSeparator) {\n size_t dirLen = lastSeparator - configPath + 1;\n \n // Copy directory part\n strncpy(logPath, configPath, dirLen);\n \n // Use simple log filename\n _snprintf_s(logPath + dirLen, size - dirLen, _TRUNCATE, \"Catime_Logs.log\");\n } else {\n // If config directory can't be determined, use current directory\n _snprintf_s(logPath, size, _TRUNCATE, \"Catime_Logs.log\");\n }\n}\n\nBOOL InitializeLogSystem(void) {\n InitializeCriticalSection(&logCS);\n \n GetLogFilePath(LOG_FILE_PATH, MAX_PATH);\n \n // Open file in write mode each startup, which clears existing content\n logFile = fopen(LOG_FILE_PATH, \"w\");\n if (!logFile) {\n // Failed to create log file\n return FALSE;\n }\n \n // Record log system initialization information\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n // First record software version\n WriteLog(LOG_LEVEL_INFO, \"Catime Version: %s\", CATIME_VERSION);\n // Then record system environment information (before any possible errors)\n WriteLog(LOG_LEVEL_INFO, \"-----------------System Information-----------------\");\n LogSystemInformation();\n WriteLog(LOG_LEVEL_INFO, \"-----------------Application Information-----------------\");\n WriteLog(LOG_LEVEL_INFO, \"Log system initialization complete, Catime started\");\n \n return TRUE;\n}\n\nvoid WriteLog(LogLevel level, const char* format, ...) {\n if (!logFile) {\n return;\n }\n \n EnterCriticalSection(&logCS);\n \n // Get current time\n time_t now;\n struct tm local_time;\n char timeStr[32] = {0};\n \n time(&now);\n localtime_s(&local_time, &now);\n strftime(timeStr, sizeof(timeStr), \"%Y-%m-%d %H:%M:%S\", &local_time);\n \n // Write log header\n fprintf(logFile, \"[%s] [%s] \", timeStr, LOG_LEVEL_STRINGS[level]);\n \n // Format and write log content\n va_list args;\n va_start(args, format);\n vfprintf(logFile, format, args);\n va_end(args);\n \n // New line\n fprintf(logFile, \"\\n\");\n \n // Flush buffer immediately to ensure logs are saved even if program crashes\n fflush(logFile);\n \n LeaveCriticalSection(&logCS);\n}\n\nvoid GetLastErrorDescription(DWORD errorCode, char* buffer, int bufferSize) {\n if (!buffer || bufferSize <= 0) {\n return;\n }\n \n LPSTR messageBuffer = NULL;\n DWORD size = FormatMessageA(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | \n FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL,\n errorCode,\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n (LPSTR)&messageBuffer,\n 0, NULL);\n \n if (size > 0) {\n // Remove trailing newlines\n if (size >= 2 && messageBuffer[size-2] == '\\r' && messageBuffer[size-1] == '\\n') {\n messageBuffer[size-2] = '\\0';\n }\n \n strncpy_s(buffer, bufferSize, messageBuffer, _TRUNCATE);\n LocalFree(messageBuffer);\n } else {\n _snprintf_s(buffer, bufferSize, _TRUNCATE, \"Unknown error (code: %lu)\", errorCode);\n }\n}\n\n// Signal handler function - used to handle various C standard signals\nvoid SignalHandler(int signal) {\n char errorMsg[256] = {0};\n \n switch (signal) {\n case SIGFPE:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Floating point exception\");\n break;\n case SIGILL:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Illegal instruction\");\n break;\n case SIGSEGV:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Segmentation fault/memory access error\");\n break;\n case SIGTERM:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Termination signal\");\n break;\n case SIGABRT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Abnormal termination/abort\");\n break;\n case SIGINT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"User interrupt\");\n break;\n default:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Unknown signal\");\n break;\n }\n \n // Record exception information\n if (logFile) {\n fprintf(logFile, \"[FATAL] Fatal signal occurred: %s (signal number: %d)\\n\", \n errorMsg, signal);\n fflush(logFile);\n \n // Close log file\n fclose(logFile);\n logFile = NULL;\n }\n \n // Display error message box\n MessageBox(NULL, \"The program encountered a serious error. Please check the log file for detailed information.\", \"Fatal Error\", MB_ICONERROR | MB_OK);\n \n // Terminate program\n exit(signal);\n}\n\nvoid SetupExceptionHandler(void) {\n // Set up standard C signal handlers\n signal(SIGFPE, SignalHandler); // Floating point exception\n signal(SIGILL, SignalHandler); // Illegal instruction\n signal(SIGSEGV, SignalHandler); // Segmentation fault\n signal(SIGTERM, SignalHandler); // Termination signal\n signal(SIGABRT, SignalHandler); // Abnormal termination\n signal(SIGINT, SignalHandler); // User interrupt\n}\n\n// Call this function when program exits to clean up log resources\nvoid CleanupLogSystem(void) {\n if (logFile) {\n WriteLog(LOG_LEVEL_INFO, \"Catime exited normally\");\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n fclose(logFile);\n logFile = NULL;\n }\n \n DeleteCriticalSection(&logCS);\n}\n"], ["/Catime/src/config.c", "/**\n * @file config.c\n * @brief Configuration file management module implementation\n */\n\n#include \"../include/config.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define MAX_POMODORO_TIMES 10\n\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nint POMODORO_TIMES[MAX_POMODORO_TIMES] = {1500, 300, 1500, 600};\nint POMODORO_TIMES_COUNT = 4;\n\nchar CLOCK_TIMEOUT_MESSAGE_TEXT[100] = \"时间到啦!\";\nchar POMODORO_TIMEOUT_MESSAGE_TEXT[100] = \"番茄钟时间到!\";\nchar POMODORO_CYCLE_COMPLETE_TEXT[100] = \"所有番茄钟循环完成!\";\n\nint NOTIFICATION_TIMEOUT_MS = 3000;\nint NOTIFICATION_MAX_OPACITY = 95;\nNotificationType NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\nBOOL NOTIFICATION_DISABLED = FALSE;\n\nchar NOTIFICATION_SOUND_FILE[MAX_PATH] = \"\";\nint NOTIFICATION_SOUND_VOLUME = 100;\n\n/** @brief Read string value from INI file */\nDWORD ReadIniString(const char* section, const char* key, const char* defaultValue,\n char* returnValue, DWORD returnSize, const char* filePath) {\n return GetPrivateProfileStringA(section, key, defaultValue, returnValue, returnSize, filePath);\n}\n\n/** @brief Write string value to INI file */\nBOOL WriteIniString(const char* section, const char* key, const char* value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value, filePath);\n}\n\n/** @brief Read integer value from INI */\nint ReadIniInt(const char* section, const char* key, int defaultValue, \n const char* filePath) {\n return GetPrivateProfileIntA(section, key, defaultValue, filePath);\n}\n\n/** @brief Write integer value to INI file */\nBOOL WriteIniInt(const char* section, const char* key, int value,\n const char* filePath) {\n char valueStr[32];\n snprintf(valueStr, sizeof(valueStr), \"%d\", value);\n return WritePrivateProfileStringA(section, key, valueStr, filePath);\n}\n\n/** @brief Write boolean value to INI file */\nBOOL WriteIniBool(const char* section, const char* key, BOOL value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value ? \"TRUE\" : \"FALSE\", filePath);\n}\n\n/** @brief Read boolean value from INI */\nBOOL ReadIniBool(const char* section, const char* key, BOOL defaultValue, \n const char* filePath) {\n char value[8];\n GetPrivateProfileStringA(section, key, defaultValue ? \"TRUE\" : \"FALSE\", \n value, sizeof(value), filePath);\n return _stricmp(value, \"TRUE\") == 0;\n}\n\n/** @brief Check if configuration file exists */\nBOOL FileExists(const char* filePath) {\n return GetFileAttributesA(filePath) != INVALID_FILE_ATTRIBUTES;\n}\n\n/** @brief Get configuration file path */\nvoid GetConfigPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\config.ini\", appdata_path) >= size) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Create default configuration file */\nvoid CreateDefaultConfig(const char* config_path) {\n // Get system default language ID\n LANGID systemLangID = GetUserDefaultUILanguage();\n int defaultLanguage = APP_LANG_ENGLISH; // Default to English\n const char* langName = \"English\"; // Default language name\n \n // Set default language based on system language ID\n switch (PRIMARYLANGID(systemLangID)) {\n case LANG_CHINESE:\n if (SUBLANGID(systemLangID) == SUBLANG_CHINESE_SIMPLIFIED) {\n defaultLanguage = APP_LANG_CHINESE_SIMP;\n langName = \"Chinese_Simplified\";\n } else {\n defaultLanguage = APP_LANG_CHINESE_TRAD;\n langName = \"Chinese_Traditional\";\n }\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n langName = \"Spanish\";\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n langName = \"French\";\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n langName = \"German\";\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n langName = \"Russian\";\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n langName = \"Portuguese\";\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n langName = \"Japanese\";\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n langName = \"Korean\";\n break;\n case LANG_ENGLISH:\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n langName = \"English\";\n break;\n }\n \n // Choose default settings based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", \"TRUE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 1; i <= 5; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n config_path);\n}\n\n/** @brief Extract filename from file path */\nvoid ExtractFileName(const char* path, char* name, size_t nameSize) {\n if (!path || !name || nameSize == 0) return;\n \n // First convert to wide characters to properly handle Unicode paths\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, wPath, MAX_PATH);\n \n // Look for the last backslash or forward slash\n wchar_t* lastSlash = wcsrchr(wPath, L'\\\\');\n if (!lastSlash) lastSlash = wcsrchr(wPath, L'/');\n \n wchar_t wName[MAX_PATH] = {0};\n if (lastSlash) {\n wcscpy(wName, lastSlash + 1);\n } else {\n wcscpy(wName, wPath);\n }\n \n // Convert back to UTF-8\n WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, nameSize, NULL, NULL);\n}\n\n/** @brief Check and create resource folders */\nvoid CheckAndCreateResourceFolders() {\n char config_path[MAX_PATH];\n char base_path[MAX_PATH];\n char resource_path[MAX_PATH];\n char *last_slash;\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Copy configuration file path\n strncpy(base_path, config_path, MAX_PATH - 1);\n base_path[MAX_PATH - 1] = '\\0';\n \n // Find the last slash or backslash, which marks the beginning of the filename\n last_slash = strrchr(base_path, '\\\\');\n if (!last_slash) {\n last_slash = strrchr(base_path, '/');\n }\n \n if (last_slash) {\n // Truncate path to directory part\n *(last_slash + 1) = '\\0';\n \n // Create resources main directory\n snprintf(resource_path, MAX_PATH, \"%sresources\", base_path);\n DWORD attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create resources folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n return;\n }\n }\n \n // Create audio subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\audio\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create audio folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create images subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\images\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create images folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create animations subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\animations\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create animations folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create themes subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\themes\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create themes folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create plug-in subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\plug-in\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create plug-in folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n }\n}\n\n/** @brief Read and parse configuration file */\nvoid ReadConfig() {\n // Check and create resource folders\n CheckAndCreateResourceFolders();\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Check if configuration file exists, create default configuration if it doesn't\n if (!FileExists(config_path)) {\n CreateDefaultConfig(config_path);\n }\n \n // Check configuration file version\n char version[32] = {0};\n BOOL versionMatched = FALSE;\n \n // Read current version information\n ReadIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", \"\", version, sizeof(version), config_path);\n \n // Compare if version matches\n if (strcmp(version, CATIME_VERSION) == 0) {\n versionMatched = TRUE;\n }\n \n // If version doesn't match, recreate the configuration file\n if (!versionMatched) {\n CreateDefaultConfig(config_path);\n }\n\n // Reset time options\n time_options_count = 0;\n memset(time_options, 0, sizeof(time_options));\n \n // Reset recent files count\n CLOCK_RECENT_FILES_COUNT = 0;\n \n // Read basic settings\n // ======== [General] Section ========\n char language[32] = {0};\n ReadIniString(INI_SECTION_GENERAL, \"LANGUAGE\", \"English\", language, sizeof(language), config_path);\n \n // Convert language name to enum value\n int languageSetting = APP_LANG_ENGLISH; // Default to English\n \n if (strcmp(language, \"Chinese_Simplified\") == 0) {\n languageSetting = APP_LANG_CHINESE_SIMP;\n } else if (strcmp(language, \"Chinese_Traditional\") == 0) {\n languageSetting = APP_LANG_CHINESE_TRAD;\n } else if (strcmp(language, \"English\") == 0) {\n languageSetting = APP_LANG_ENGLISH;\n } else if (strcmp(language, \"Spanish\") == 0) {\n languageSetting = APP_LANG_SPANISH;\n } else if (strcmp(language, \"French\") == 0) {\n languageSetting = APP_LANG_FRENCH;\n } else if (strcmp(language, \"German\") == 0) {\n languageSetting = APP_LANG_GERMAN;\n } else if (strcmp(language, \"Russian\") == 0) {\n languageSetting = APP_LANG_RUSSIAN;\n } else if (strcmp(language, \"Portuguese\") == 0) {\n languageSetting = APP_LANG_PORTUGUESE;\n } else if (strcmp(language, \"Japanese\") == 0) {\n languageSetting = APP_LANG_JAPANESE;\n } else if (strcmp(language, \"Korean\") == 0) {\n languageSetting = APP_LANG_KOREAN;\n } else {\n // Try to parse as number (for backward compatibility)\n int langValue = atoi(language);\n if (langValue >= 0 && langValue < APP_LANG_COUNT) {\n languageSetting = langValue;\n } else {\n languageSetting = APP_LANG_ENGLISH; // Default to English\n }\n }\n \n // ======== [Display] Section ========\n ReadIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", CLOCK_TEXT_COLOR, sizeof(CLOCK_TEXT_COLOR), config_path);\n CLOCK_BASE_FONT_SIZE = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n ReadIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", FONT_FILE_NAME, sizeof(FONT_FILE_NAME), config_path);\n \n // Extract internal name from font filename\n size_t font_name_len = strlen(FONT_FILE_NAME);\n if (font_name_len > 4 && strcmp(FONT_FILE_NAME + font_name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = font_name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n CLOCK_WINDOW_POS_X = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n CLOCK_WINDOW_POS_Y = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n \n char scaleStr[16] = {0};\n ReadIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", scaleStr, sizeof(scaleStr), config_path);\n CLOCK_WINDOW_SCALE = atof(scaleStr);\n \n CLOCK_WINDOW_TOPMOST = ReadIniBool(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", TRUE, config_path);\n \n // Check and replace pure black color\n if (strcasecmp(CLOCK_TEXT_COLOR, \"#000000\") == 0) {\n strncpy(CLOCK_TEXT_COLOR, \"#000001\", sizeof(CLOCK_TEXT_COLOR) - 1);\n }\n \n // ======== [Timer] Section ========\n CLOCK_DEFAULT_START_TIME = ReadIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n CLOCK_USE_24HOUR = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", FALSE, config_path);\n CLOCK_SHOW_SECONDS = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", FALSE, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", CLOCK_TIMEOUT_TEXT, sizeof(CLOCK_TIMEOUT_TEXT), config_path);\n \n // Read timeout action\n char timeoutAction[32] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", timeoutAction, sizeof(timeoutAction), config_path);\n \n if (strcmp(timeoutAction, \"MESSAGE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"LOCK\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n } else if (strcmp(timeoutAction, \"SHUTDOWN\") == 0) {\n // Even if SHUTDOWN exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"RESTART\") == 0) {\n // Even if RESTART exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"OPEN_FILE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n } else if (strcmp(timeoutAction, \"SHOW_TIME\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n } else if (strcmp(timeoutAction, \"COUNT_UP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n } else if (strcmp(timeoutAction, \"OPEN_WEBSITE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n } else if (strcmp(timeoutAction, \"SLEEP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n } else if (strcmp(timeoutAction, \"RUN_COMMAND\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n } else if (strcmp(timeoutAction, \"HTTP_REQUEST\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n }\n \n // Read timeout file and website settings\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", CLOCK_TIMEOUT_FILE_PATH, MAX_PATH, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", CLOCK_TIMEOUT_WEBSITE_URL, MAX_PATH, config_path);\n \n // If file path is valid, ensure timeout action is set to open file\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n GetFileAttributesA(CLOCK_TIMEOUT_FILE_PATH) != INVALID_FILE_ATTRIBUTES) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n }\n \n // If URL is valid, ensure timeout action is set to open website\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n }\n \n // Read time options\n char timeOptions[256] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", timeOptions, sizeof(timeOptions), config_path);\n \n char *token = strtok(timeOptions, \",\");\n while (token && time_options_count < MAX_TIME_OPTIONS) {\n while (*token == ' ') token++;\n time_options[time_options_count++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Read startup mode\n ReadIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", CLOCK_STARTUP_MODE, sizeof(CLOCK_STARTUP_MODE), config_path);\n \n // ======== [Pomodoro] Section ========\n char pomodoroTimeOptions[256] = {0};\n ReadIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", pomodoroTimeOptions, sizeof(pomodoroTimeOptions), config_path);\n \n // Reset pomodoro time count\n POMODORO_TIMES_COUNT = 0;\n \n // Parse all pomodoro time values\n token = strtok(pomodoroTimeOptions, \",\");\n while (token && POMODORO_TIMES_COUNT < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[POMODORO_TIMES_COUNT++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Even though we now use a new array to store all times,\n // keep these three variables for backward compatibility\n if (POMODORO_TIMES_COUNT > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (POMODORO_TIMES_COUNT > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (POMODORO_TIMES_COUNT > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[3]; // Note this is the 4th value\n }\n \n // Read pomodoro loop count\n POMODORO_LOOP_COUNT = ReadIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n \n // ======== [Notification] Section ========\n ReadIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", \n CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", \n POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", \n POMODORO_CYCLE_COMPLETE_TEXT, sizeof(POMODORO_CYCLE_COMPLETE_TEXT), config_path);\n \n NOTIFICATION_TIMEOUT_MS = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n NOTIFICATION_MAX_OPACITY = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n \n // Ensure opacity is within valid range (1-100)\n if (NOTIFICATION_MAX_OPACITY < 1) NOTIFICATION_MAX_OPACITY = 1;\n if (NOTIFICATION_MAX_OPACITY > 100) NOTIFICATION_MAX_OPACITY = 100;\n \n char notificationType[32] = {0};\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", \"CATIME\", notificationType, sizeof(notificationType), config_path);\n \n // Set notification type\n if (strcmp(notificationType, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(notificationType, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(notificationType, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Read notification audio file path\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", \n NOTIFICATION_SOUND_FILE, MAX_PATH, config_path);\n \n // Read notification audio volume\n NOTIFICATION_SOUND_VOLUME = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n \n // Read whether to disable notification window\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n \n // Ensure volume is within valid range (0-100)\n if (NOTIFICATION_SOUND_VOLUME < 0) NOTIFICATION_SOUND_VOLUME = 0;\n if (NOTIFICATION_SOUND_VOLUME > 100) NOTIFICATION_SOUND_VOLUME = 100;\n \n // ======== [Colors] Section ========\n char colorOptions[1024] = {0};\n ReadIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n colorOptions, sizeof(colorOptions), config_path);\n \n // Parse color options\n token = strtok(colorOptions, \",\");\n COLOR_OPTIONS_COUNT = 0;\n while (token) {\n COLOR_OPTIONS = realloc(COLOR_OPTIONS, sizeof(PredefinedColor) * (COLOR_OPTIONS_COUNT + 1));\n if (COLOR_OPTIONS) {\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = strdup(token);\n COLOR_OPTIONS_COUNT++;\n }\n token = strtok(NULL, \",\");\n }\n \n // ======== [RecentFiles] Section ========\n // Read recent file records\n for (int i = 1; i <= MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n \n char filePath[MAX_PATH] = {0};\n ReadIniString(INI_SECTION_RECENTFILES, key, \"\", filePath, MAX_PATH, config_path);\n \n if (strlen(filePath) > 0) {\n // Convert to wide characters to properly check if the file exists\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, widePath, MAX_PATH);\n \n // Check if file exists\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n ExtractFileName(filePath, CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, MAX_PATH);\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n \n // ======== [Hotkeys] Section ========\n // Read hotkey configurations from INI file\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n // Read hotkey settings\n char hotkeyStr[32] = {0};\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n showTimeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countUpHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countdownHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown1Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown2Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown3Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pomodoroHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n toggleVisibilityHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n editModeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pauseResumeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n restartTimerHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n customCountdownHotkey = StringToHotkey(hotkeyStr);\n \n last_config_time = time(NULL);\n\n // Apply window position\n HWND hwnd = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwnd) {\n SetWindowPos(hwnd, NULL, CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n\n // Apply language settings\n SetLanguage((AppLanguage)languageSetting);\n}\n\n/** @brief Write timeout action configuration */\nvoid WriteConfigTimeoutAction(const char* action) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n // For shutdown or restart actions, don't write them to the config file, write \"MESSAGE\" instead\n const char* actual_action = action;\n if (strcmp(action, \"RESTART\") == 0 || strcmp(action, \"SHUTDOWN\") == 0 || strcmp(action, \"SLEEP\") == 0) {\n actual_action = \"MESSAGE\";\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write time options configuration */\nvoid WriteConfigTimeOptions(const char* options) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIME_OPTIONS=\", 19) == 0) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Load recently used file records */\nvoid LoadRecentFiles(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) return;\n\n char line[MAX_PATH];\n CLOCK_RECENT_FILES_COUNT = 0;\n\n while (fgets(line, sizeof(line), file)) {\n // Support for the CLOCK_RECENT_FILE_N=path format\n if (strncmp(line, \"CLOCK_RECENT_FILE_\", 18) == 0) {\n char *path = strchr(line + 18, '=');\n if (path) {\n path++; // Skip the equals sign\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n // Also update the old format for compatibility\n else if (strncmp(line, \"CLOCK_RECENT_FILE=\", 18) == 0) {\n char *path = line + 18;\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n\n fclose(file);\n}\n\n/** @brief Save recently used file record */\nvoid SaveRecentFile(const char* filePath) {\n // Check if the file path is valid\n if (!filePath || strlen(filePath) == 0) return;\n \n // Convert to wide characters to check if the file exists\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) == INVALID_FILE_ATTRIBUTES) {\n // File doesn't exist, don't add it\n return;\n }\n \n // Check if the file is already in the list\n int existingIndex = -1;\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n if (strcmp(CLOCK_RECENT_FILES[i].path, filePath) == 0) {\n existingIndex = i;\n break;\n }\n }\n \n if (existingIndex == 0) {\n // File is already at the top of the list, no action needed\n return;\n }\n \n if (existingIndex > 0) {\n // File is in the list, but not at the top, need to move it\n RecentFile temp = CLOCK_RECENT_FILES[existingIndex];\n \n // Move elements backward\n for (int i = existingIndex; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Put it at the first position\n CLOCK_RECENT_FILES[0] = temp;\n } else {\n // File is not in the list, need to add it\n // First ensure the list doesn't exceed 5 items\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n CLOCK_RECENT_FILES_COUNT++;\n }\n \n // Move elements backward\n for (int i = CLOCK_RECENT_FILES_COUNT - 1; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Add new file to the first position\n strncpy(CLOCK_RECENT_FILES[0].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[0].path[MAX_PATH - 1] = '\\0';\n \n // Extract filename\n ExtractFileName(filePath, CLOCK_RECENT_FILES[0].name, MAX_PATH);\n }\n \n // Update configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n WriteConfig(configPath);\n}\n\n/** @brief Convert UTF8 to ANSI encoding */\nchar* UTF8ToANSI(const char* utf8Str) {\n int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, NULL, 0);\n if (wlen == 0) {\n return _strdup(utf8Str);\n }\n\n wchar_t* wstr = (wchar_t*)malloc(sizeof(wchar_t) * wlen);\n if (!wstr) {\n return _strdup(utf8Str);\n }\n\n if (MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, wstr, wlen) == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n int len = WideCharToMultiByte(936, 0, wstr, -1, NULL, 0, NULL, NULL);\n if (len == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n char* str = (char*)malloc(len);\n if (!str) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n if (WideCharToMultiByte(936, 0, wstr, -1, str, len, NULL, NULL) == 0) {\n free(wstr);\n free(str);\n return _strdup(utf8Str);\n }\n\n free(wstr);\n return str;\n}\n\n/** @brief Write pomodoro time settings */\nvoid WriteConfigPomodoroTimes(int work, int short_break, int long_break) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n // Update global variables\n // Maintain backward compatibility, while updating the POMODORO_TIMES array\n POMODORO_WORK_TIME = work;\n POMODORO_SHORT_BREAK = short_break;\n POMODORO_LONG_BREAK = long_break;\n \n // Ensure at least these three time values exist\n POMODORO_TIMES[0] = work;\n if (POMODORO_TIMES_COUNT < 1) POMODORO_TIMES_COUNT = 1;\n \n if (POMODORO_TIMES_COUNT > 1) {\n POMODORO_TIMES[1] = short_break;\n } else if (short_break > 0) {\n POMODORO_TIMES[1] = short_break;\n POMODORO_TIMES_COUNT = 2;\n }\n \n if (POMODORO_TIMES_COUNT > 2) {\n POMODORO_TIMES[2] = long_break;\n } else if (long_break > 0) {\n POMODORO_TIMES[2] = long_break;\n POMODORO_TIMES_COUNT = 3;\n }\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n // Look for POMODORO_TIME_OPTIONS line\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write all pomodoro times\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If POMODORO_TIME_OPTIONS was not found, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro loop count configuration */\nvoid WriteConfigPomodoroLoopCount(int loop_count) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If the key was not found in the configuration file, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n POMODORO_LOOP_COUNT = loop_count;\n}\n\n/** @brief Write window topmost status configuration */\nvoid WriteConfigTopmost(const char* topmost) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"WINDOW_TOPMOST=\", 15) == 0) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write timeout open file path */\nvoid WriteConfigTimeoutFile(const char* filePath) {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n strncpy(CLOCK_TIMEOUT_FILE_PATH, filePath, MAX_PATH - 1);\n CLOCK_TIMEOUT_FILE_PATH[MAX_PATH - 1] = '\\0';\n \n // Use WriteConfig to completely rewrite the configuration file, maintaining structural consistency\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n}\n\n/** @brief Write all configuration settings to file */\nvoid WriteConfig(const char* config_path) {\n // Get the name of the current language\n AppLanguage currentLang = GetCurrentLanguage();\n const char* langName;\n \n switch (currentLang) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n case APP_LANG_ENGLISH:\n default:\n langName = \"English\";\n break;\n }\n \n // Choose string representation based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Read hotkey settings\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0};\n \n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Prepare time options string\n char timeOptionsStr[256] = {0};\n for (int i = 0; i < time_options_count; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", time_options[i]);\n \n if (i > 0) {\n strcat(timeOptionsStr, \",\");\n }\n strcat(timeOptionsStr, buffer);\n }\n \n // Prepare pomodoro time options string\n char pomodoroTimesStr[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", POMODORO_TIMES[i]);\n \n if (i > 0) {\n strcat(pomodoroTimesStr, \",\");\n }\n strcat(pomodoroTimesStr, buffer);\n }\n \n // Prepare color options string\n char colorOptionsStr[1024] = {0};\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (i > 0) {\n strcat(colorOptionsStr, \",\");\n }\n strcat(colorOptionsStr, COLOR_OPTIONS[i].hexColor);\n }\n \n // Determine timeout action string\n const char* timeoutActionStr;\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_LOCK:\n timeoutActionStr = \"LOCK\";\n break;\n case TIMEOUT_ACTION_SHUTDOWN:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RESTART:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_OPEN_FILE:\n timeoutActionStr = \"OPEN_FILE\";\n break;\n case TIMEOUT_ACTION_SHOW_TIME:\n timeoutActionStr = \"SHOW_TIME\";\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n timeoutActionStr = \"COUNT_UP\";\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n timeoutActionStr = \"OPEN_WEBSITE\";\n break;\n case TIMEOUT_ACTION_SLEEP:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n timeoutActionStr = \"RUN_COMMAND\";\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n timeoutActionStr = \"HTTP_REQUEST\";\n break;\n default:\n timeoutActionStr = \"MESSAGE\";\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", IsShortcutCheckDone() ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", CLOCK_TEXT_COLOR, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", CLOCK_BASE_FONT_SIZE, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", FONT_FILE_NAME, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", CLOCK_WINDOW_POS_X, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", CLOCK_WINDOW_POS_Y, config_path);\n \n char scaleStr[16];\n snprintf(scaleStr, sizeof(scaleStr), \"%.2f\", CLOCK_WINDOW_SCALE);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", scaleStr, config_path);\n \n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", CLOCK_WINDOW_TOPMOST ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", CLOCK_DEFAULT_START_TIME, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", CLOCK_USE_24HOUR ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", CLOCK_SHOW_SECONDS ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", CLOCK_TIMEOUT_TEXT, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", timeoutActionStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", CLOCK_TIMEOUT_FILE_PATH, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", CLOCK_TIMEOUT_WEBSITE_URL, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", timeOptionsStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", CLOCK_STARTUP_MODE, config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", pomodoroTimesStr, config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", POMODORO_LOOP_COUNT, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", CLOCK_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", POMODORO_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", POMODORO_CYCLE_COMPLETE_TEXT, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", NOTIFICATION_TIMEOUT_MS, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", NOTIFICATION_MAX_OPACITY, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", NOTIFICATION_SOUND_FILE, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", NOTIFICATION_SOUND_VOLUME, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", NOTIFICATION_DISABLED ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", showTimeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", countUpStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", countdownStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", quickCountdown1Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", quickCountdown2Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", quickCountdown3Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", pomodoroStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", toggleVisibilityStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", editModeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", pauseResumeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", restartTimerStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr, config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, CLOCK_RECENT_FILES[i].path, config_path);\n }\n \n // Clear unused file records\n for (int i = CLOCK_RECENT_FILES_COUNT; i < MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", colorOptionsStr, config_path);\n}\n\n/** @brief Write timeout open website URL */\nvoid WriteConfigTimeoutWebsite(const char* url) {\n // Only set timeout action to open website if a valid URL is provided\n if (url && url[0] != '\\0') {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n strncpy(CLOCK_TIMEOUT_WEBSITE_URL, url, MAX_PATH - 1);\n CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH - 1] = '\\0';\n \n // Then update the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL actionFound = FALSE;\n BOOL urlFound = FALSE;\n \n // Read original configuration file, update timeout action and URL\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n actionFound = TRUE;\n } else if (strncmp(line, \"CLOCK_TIMEOUT_WEBSITE=\", 22) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n urlFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If these items are not in the configuration, add them\n if (!actionFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n }\n if (!urlFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n }\n}\n\n/** @brief Write startup mode configuration */\nvoid WriteConfigStartupMode(const char* mode) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n // Update global variable\n strncpy(CLOCK_STARTUP_MODE, mode, sizeof(CLOCK_STARTUP_MODE) - 1);\n CLOCK_STARTUP_MODE[sizeof(CLOCK_STARTUP_MODE) - 1] = '\\0';\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro time options */\nvoid WriteConfigPomodoroTimeOptions(int* times, int count) {\n if (!times || count <= 0) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL optionsFound = FALSE;\n \n // Read original configuration file, update pomodoro time options\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write new time options\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n optionsFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If this item is not in the configuration, add it\n if (!optionsFound) {\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write notification message configuration */\nvoid WriteConfigNotificationMessages(const char* timeout_msg, const char* pomodoro_msg, const char* cycle_complete_msg) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n // Use standard C file operations instead of Windows API\n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL timeoutFound = FALSE;\n BOOL pomodoroFound = FALSE;\n BOOL cycleFound = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n timeoutFound = TRUE;\n } else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n pomodoroFound = TRUE;\n } else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n cycleFound = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If corresponding items are not found in the configuration, add them\n if (!timeoutFound) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n }\n \n if (!pomodoroFound) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n }\n \n if (!cycleFound) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variables\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, timeout_msg, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, pomodoro_msg, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, cycle_complete_msg, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n}\n\n/** @brief Read notification message text from configuration file */\nvoid ReadNotificationMessagesConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current values in memory or default values\n return;\n }\n\n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[1024];\n BOOL timeoutMsgFound = FALSE;\n BOOL pomodoroTimeoutMsgFound = FALSE;\n BOOL cycleCompleteMsgFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n // Process this line\n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, line + 27, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n timeoutMsgFound = TRUE;\n } \n else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, line + 30, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n pomodoroTimeoutMsgFound = TRUE;\n }\n else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, line + 29, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n cycleCompleteMsgFound = TRUE;\n }\n \n // If all messages have been found, can exit loop early\n if (timeoutMsgFound && pomodoroTimeoutMsgFound && cycleCompleteMsgFound) {\n break;\n }\n }\n \n CloseHandle(hFile);\n \n // If corresponding configuration items are not found in the file, ensure variables have default values\n if (!timeoutMsgFound) {\n strcpy(CLOCK_TIMEOUT_MESSAGE_TEXT, \"时间到啦!\"); // Default value\n }\n if (!pomodoroTimeoutMsgFound) {\n strcpy(POMODORO_TIMEOUT_MESSAGE_TEXT, \"番茄钟时间到!\"); // Default value\n }\n if (!cycleCompleteMsgFound) {\n strcpy(POMODORO_CYCLE_COMPLETE_TEXT, \"所有番茄钟循环完成!\"); // Default value\n }\n}\n\n/** @brief Read notification display time from configuration file */\nvoid ReadNotificationTimeoutConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL timeoutFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n int timeout = atoi(line + 24);\n if (timeout > 0) {\n NOTIFICATION_TIMEOUT_MS = timeout;\n }\n timeoutFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!timeoutFound) {\n NOTIFICATION_TIMEOUT_MS = 3000; // Ensure there's a default value\n }\n}\n\n/** @brief Write notification display time configuration */\nvoid WriteConfigNotificationTimeout(int timeout_ms) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_TIMEOUT_MS = timeout_ms;\n}\n\n/** @brief Read maximum notification opacity from configuration file */\nvoid ReadNotificationOpacityConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL opacityFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n int opacity = atoi(line + 25);\n // Ensure opacity is within valid range (1-100)\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n opacityFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!opacityFound) {\n NOTIFICATION_MAX_OPACITY = 95; // Ensure there's a default value\n }\n}\n\n/** @brief Write maximum notification opacity configuration */\nvoid WriteConfigNotificationOpacity(int opacity) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_MAX_OPACITY = opacity;\n}\n\n/** @brief Read notification type setting from configuration file */\nvoid ReadNotificationTypeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *file = fopen(config_path, \"r\");\n if (file) {\n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n char typeStr[32] = {0};\n sscanf(line + 18, \"%31s\", typeStr);\n \n // Set notification type based on the string\n if (strcmp(typeStr, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(typeStr, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(typeStr, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n // Use default value for invalid type\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n }\n break;\n }\n }\n fclose(file);\n }\n}\n\n/** @brief Write notification type configuration */\nvoid WriteConfigNotificationType(NotificationType type) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure type value is within valid range\n if (type < NOTIFICATION_TYPE_CATIME || type > NOTIFICATION_TYPE_OS) {\n type = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Update global variable\n NOTIFICATION_TYPE = type;\n \n // Convert enum to string\n const char* typeStr;\n switch (type) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Create temporary file path\n char temp_path[MAX_PATH];\n strncpy(temp_path, config_path, MAX_PATH - 5);\n strcat(temp_path, \".tmp\");\n \n FILE *source = fopen(config_path, \"r\");\n FILE *target = fopen(temp_path, \"w\");\n \n if (source && target) {\n char line[256];\n BOOL found = FALSE;\n \n // Copy file content, replace target configuration line\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n found = TRUE;\n } else {\n fputs(line, target);\n }\n }\n \n // If configuration item not found, add it to the end of file\n if (!found) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n }\n \n fclose(source);\n fclose(target);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n } else {\n // Clean up potentially open files\n if (source) fclose(source);\n if (target) fclose(target);\n }\n}\n\n/** @brief Get audio folder path */\nvoid GetAudioFolderPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) >= size) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Read notification audio settings from configuration file */\nvoid ReadNotificationSoundConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[1024];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n char* value = line + 23; // Correct offset, skip \"NOTIFICATION_SOUND_FILE=\"\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Ensure path doesn't contain equals sign\n if (value[0] == '=') {\n value++; // If first character is equals sign, skip it\n }\n \n // Copy to global variable, ensure cleared\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, value, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio configuration */\nvoid WriteConfigNotificationSound(const char* sound_file) {\n if (!sound_file) return;\n \n // Check if the path contains equals sign, remove if present\n char clean_path[MAX_PATH] = {0};\n const char* src = sound_file;\n char* dst = clean_path;\n \n while (*src && (dst - clean_path) < (MAX_PATH - 1)) {\n if (*src != '=') {\n *dst++ = *src;\n }\n src++;\n }\n *dst = '\\0';\n \n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Create temporary file path\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE* source = fopen(config_path, \"r\");\n if (!source) return;\n \n FILE* dest = fopen(temp_path, \"w\");\n if (!dest) {\n fclose(source);\n return;\n }\n \n char line[1024];\n int found = 0;\n \n // Copy file content, replace or add notification audio settings\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n found = 1;\n } else {\n fputs(line, dest);\n }\n }\n \n // If configuration item not found, add to end of file\n if (!found) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n }\n \n fclose(source);\n fclose(dest);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, clean_path, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n}\n\n/** @brief Read notification audio volume from configuration file */\nvoid ReadNotificationVolumeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n int volume = atoi(line + 26);\n if (volume >= 0 && volume <= 100) {\n NOTIFICATION_SOUND_VOLUME = volume;\n }\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio volume configuration */\nvoid WriteConfigNotificationVolume(int volume) {\n // Validate volume range\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n \n // Update global variable\n NOTIFICATION_SOUND_VOLUME = volume;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Read hotkey settings from configuration file */\nvoid ReadConfigHotkeys(WORD* showTimeHotkey, WORD* countUpHotkey, WORD* countdownHotkey,\n WORD* quickCountdown1Hotkey, WORD* quickCountdown2Hotkey, WORD* quickCountdown3Hotkey,\n WORD* pomodoroHotkey, WORD* toggleVisibilityHotkey, WORD* editModeHotkey,\n WORD* pauseResumeHotkey, WORD* restartTimerHotkey)\n{\n // Parameter validation\n if (!showTimeHotkey || !countUpHotkey || !countdownHotkey || \n !quickCountdown1Hotkey || !quickCountdown2Hotkey || !quickCountdown3Hotkey ||\n !pomodoroHotkey || !toggleVisibilityHotkey || !editModeHotkey || \n !pauseResumeHotkey || !restartTimerHotkey) return;\n \n // Initialize to 0 (indicates no hotkey set)\n *showTimeHotkey = 0;\n *countUpHotkey = 0;\n *countdownHotkey = 0;\n *quickCountdown1Hotkey = 0;\n *quickCountdown2Hotkey = 0;\n *quickCountdown3Hotkey = 0;\n *pomodoroHotkey = 0;\n *toggleVisibilityHotkey = 0;\n *editModeHotkey = 0;\n *pauseResumeHotkey = 0;\n *restartTimerHotkey = 0;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *showTimeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countUpHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countdownHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown1Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown2Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown3Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pomodoroHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n char* value = line + 25;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *toggleVisibilityHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *editModeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n char* value = line + 20;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pauseResumeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n char* value = line + 21;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *restartTimerHotkey = StringToHotkey(value);\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write hotkey configuration */\nvoid WriteConfigHotkeys(WORD showTimeHotkey, WORD countUpHotkey, WORD countdownHotkey,\n WORD quickCountdown1Hotkey, WORD quickCountdown2Hotkey, WORD quickCountdown3Hotkey,\n WORD pomodoroHotkey, WORD toggleVisibilityHotkey, WORD editModeHotkey,\n WORD pauseResumeHotkey, WORD restartTimerHotkey) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) {\n // If file doesn't exist, create new file\n file = fopen(config_path, \"w\");\n if (!file) return;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0}; // Add custom countdown hotkey\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n // Get custom countdown hotkey value\n WORD customCountdownHotkey = 0;\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Write hotkey configuration\n fprintf(file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n fprintf(file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n fprintf(file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n fprintf(file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n fprintf(file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n fprintf(file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n fprintf(file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n fprintf(file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n fprintf(file, \"HOTKEY_CUSTOM_COUNTDOWN=%s\\n\", customCountdownStr); // Add new hotkey\n \n fclose(file);\n return;\n }\n \n // File exists, read all lines and update hotkey settings\n char temp_path[MAX_PATH];\n sprintf(temp_path, \"%s.tmp\", config_path);\n FILE* temp_file = fopen(temp_path, \"w\");\n \n if (!temp_file) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL foundShowTime = FALSE;\n BOOL foundCountUp = FALSE;\n BOOL foundCountdown = FALSE;\n BOOL foundQuickCountdown1 = FALSE;\n BOOL foundQuickCountdown2 = FALSE;\n BOOL foundQuickCountdown3 = FALSE;\n BOOL foundPomodoro = FALSE;\n BOOL foundToggleVisibility = FALSE;\n BOOL foundEditMode = FALSE;\n BOOL foundPauseResume = FALSE;\n BOOL foundRestartTimer = FALSE;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n \n // Process each line\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n foundShowTime = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n foundCountUp = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n foundCountdown = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n foundQuickCountdown1 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n foundQuickCountdown2 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n foundQuickCountdown3 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n foundPomodoro = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n foundToggleVisibility = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n foundEditMode = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n foundPauseResume = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n foundRestartTimer = TRUE;\n }\n else {\n // Keep other lines\n fputs(line, temp_file);\n }\n }\n \n // Add hotkey configuration items not found\n if (!foundShowTime) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n }\n if (!foundCountUp) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n }\n if (!foundCountdown) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n }\n if (!foundQuickCountdown1) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n }\n if (!foundQuickCountdown2) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n }\n if (!foundQuickCountdown3) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n }\n if (!foundPomodoro) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n }\n if (!foundToggleVisibility) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n }\n if (!foundEditMode) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n }\n if (!foundPauseResume) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n }\n if (!foundRestartTimer) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n }\n \n fclose(file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Convert hotkey value to readable string */\nvoid HotkeyToString(WORD hotkey, char* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) return;\n \n // 如果热键为0,表示未设置\n if (hotkey == 0) {\n strncpy(buffer, \"None\", bufferSize - 1);\n buffer[bufferSize - 1] = '\\0';\n return;\n }\n \n BYTE vk = LOBYTE(hotkey); // 虚拟键码\n BYTE mod = HIBYTE(hotkey); // 修饰键\n \n buffer[0] = '\\0';\n size_t len = 0;\n \n // 添加修饰键\n if (mod & HOTKEYF_CONTROL) {\n strncpy(buffer, \"Ctrl\", bufferSize - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_SHIFT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Shift\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_ALT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Alt\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n // 添加虚拟键\n if (len > 0 && len < bufferSize - 1 && vk != 0) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n \n // 获取虚拟键名称\n if (vk >= 'A' && vk <= 'Z') {\n // 字母键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= '0' && vk <= '9') {\n // 数字键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= VK_F1 && vk <= VK_F24) {\n // 功能键\n char keyName[4];\n sprintf(keyName, \"F%d\", vk - VK_F1 + 1);\n strncat(buffer, keyName, bufferSize - len - 1);\n } else {\n // 其他特殊键\n switch (vk) {\n case VK_BACK: strncat(buffer, \"Backspace\", bufferSize - len - 1); break;\n case VK_TAB: strncat(buffer, \"Tab\", bufferSize - len - 1); break;\n case VK_RETURN: strncat(buffer, \"Enter\", bufferSize - len - 1); break;\n case VK_ESCAPE: strncat(buffer, \"Esc\", bufferSize - len - 1); break;\n case VK_SPACE: strncat(buffer, \"Space\", bufferSize - len - 1); break;\n case VK_PRIOR: strncat(buffer, \"PageUp\", bufferSize - len - 1); break;\n case VK_NEXT: strncat(buffer, \"PageDown\", bufferSize - len - 1); break;\n case VK_END: strncat(buffer, \"End\", bufferSize - len - 1); break;\n case VK_HOME: strncat(buffer, \"Home\", bufferSize - len - 1); break;\n case VK_LEFT: strncat(buffer, \"Left\", bufferSize - len - 1); break;\n case VK_UP: strncat(buffer, \"Up\", bufferSize - len - 1); break;\n case VK_RIGHT: strncat(buffer, \"Right\", bufferSize - len - 1); break;\n case VK_DOWN: strncat(buffer, \"Down\", bufferSize - len - 1); break;\n case VK_INSERT: strncat(buffer, \"Insert\", bufferSize - len - 1); break;\n case VK_DELETE: strncat(buffer, \"Delete\", bufferSize - len - 1); break;\n case VK_NUMPAD0: strncat(buffer, \"Num0\", bufferSize - len - 1); break;\n case VK_NUMPAD1: strncat(buffer, \"Num1\", bufferSize - len - 1); break;\n case VK_NUMPAD2: strncat(buffer, \"Num2\", bufferSize - len - 1); break;\n case VK_NUMPAD3: strncat(buffer, \"Num3\", bufferSize - len - 1); break;\n case VK_NUMPAD4: strncat(buffer, \"Num4\", bufferSize - len - 1); break;\n case VK_NUMPAD5: strncat(buffer, \"Num5\", bufferSize - len - 1); break;\n case VK_NUMPAD6: strncat(buffer, \"Num6\", bufferSize - len - 1); break;\n case VK_NUMPAD7: strncat(buffer, \"Num7\", bufferSize - len - 1); break;\n case VK_NUMPAD8: strncat(buffer, \"Num8\", bufferSize - len - 1); break;\n case VK_NUMPAD9: strncat(buffer, \"Num9\", bufferSize - len - 1); break;\n case VK_MULTIPLY: strncat(buffer, \"Num*\", bufferSize - len - 1); break;\n case VK_ADD: strncat(buffer, \"Num+\", bufferSize - len - 1); break;\n case VK_SUBTRACT: strncat(buffer, \"Num-\", bufferSize - len - 1); break;\n case VK_DECIMAL: strncat(buffer, \"Num.\", bufferSize - len - 1); break;\n case VK_DIVIDE: strncat(buffer, \"Num/\", bufferSize - len - 1); break;\n case VK_OEM_1: strncat(buffer, \";\", bufferSize - len - 1); break;\n case VK_OEM_PLUS: strncat(buffer, \"=\", bufferSize - len - 1); break;\n case VK_OEM_COMMA: strncat(buffer, \",\", bufferSize - len - 1); break;\n case VK_OEM_MINUS: strncat(buffer, \"-\", bufferSize - len - 1); break;\n case VK_OEM_PERIOD: strncat(buffer, \".\", bufferSize - len - 1); break;\n case VK_OEM_2: strncat(buffer, \"/\", bufferSize - len - 1); break;\n case VK_OEM_3: strncat(buffer, \"`\", bufferSize - len - 1); break;\n case VK_OEM_4: strncat(buffer, \"[\", bufferSize - len - 1); break;\n case VK_OEM_5: strncat(buffer, \"\\\\\", bufferSize - len - 1); break;\n case VK_OEM_6: strncat(buffer, \"]\", bufferSize - len - 1); break;\n case VK_OEM_7: strncat(buffer, \"'\", bufferSize - len - 1); break;\n default: \n // 对于其他未知键,使用十六进制表示\n {\n char keyName[8];\n sprintf(keyName, \"0x%02X\", vk);\n strncat(buffer, keyName, bufferSize - len - 1);\n }\n break;\n }\n }\n}\n\n/** @brief Convert string to hotkey value */\nWORD StringToHotkey(const char* str) {\n if (!str || str[0] == '\\0' || strcmp(str, \"None\") == 0) {\n return 0; // 未设置热键\n }\n \n // 尝试直接解析为数字(兼容旧格式)\n if (isdigit(str[0])) {\n return (WORD)atoi(str);\n }\n \n BYTE vk = 0; // 虚拟键码\n BYTE mod = 0; // 修饰键\n \n // 复制字符串以便使用strtok\n char buffer[256];\n strncpy(buffer, str, sizeof(buffer) - 1);\n buffer[sizeof(buffer) - 1] = '\\0';\n \n // 分割字符串,查找修饰键和主键\n char* token = strtok(buffer, \"+\");\n char* lastToken = NULL;\n \n while (token) {\n if (stricmp(token, \"Ctrl\") == 0) {\n mod |= HOTKEYF_CONTROL;\n } else if (stricmp(token, \"Shift\") == 0) {\n mod |= HOTKEYF_SHIFT;\n } else if (stricmp(token, \"Alt\") == 0) {\n mod |= HOTKEYF_ALT;\n } else {\n // 可能是主键\n lastToken = token;\n }\n token = strtok(NULL, \"+\");\n }\n \n // 解析主键\n if (lastToken) {\n // 检查是否是单个字符的字母或数字\n if (strlen(lastToken) == 1) {\n char ch = toupper(lastToken[0]);\n if ((ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) {\n vk = ch;\n }\n } \n // 检查是否是功能键\n else if (lastToken[0] == 'F' && isdigit(lastToken[1])) {\n int fNum = atoi(lastToken + 1);\n if (fNum >= 1 && fNum <= 24) {\n vk = VK_F1 + fNum - 1;\n }\n }\n // 检查特殊键名\n else if (stricmp(lastToken, \"Backspace\") == 0) vk = VK_BACK;\n else if (stricmp(lastToken, \"Tab\") == 0) vk = VK_TAB;\n else if (stricmp(lastToken, \"Enter\") == 0) vk = VK_RETURN;\n else if (stricmp(lastToken, \"Esc\") == 0) vk = VK_ESCAPE;\n else if (stricmp(lastToken, \"Space\") == 0) vk = VK_SPACE;\n else if (stricmp(lastToken, \"PageUp\") == 0) vk = VK_PRIOR;\n else if (stricmp(lastToken, \"PageDown\") == 0) vk = VK_NEXT;\n else if (stricmp(lastToken, \"End\") == 0) vk = VK_END;\n else if (stricmp(lastToken, \"Home\") == 0) vk = VK_HOME;\n else if (stricmp(lastToken, \"Left\") == 0) vk = VK_LEFT;\n else if (stricmp(lastToken, \"Up\") == 0) vk = VK_UP;\n else if (stricmp(lastToken, \"Right\") == 0) vk = VK_RIGHT;\n else if (stricmp(lastToken, \"Down\") == 0) vk = VK_DOWN;\n else if (stricmp(lastToken, \"Insert\") == 0) vk = VK_INSERT;\n else if (stricmp(lastToken, \"Delete\") == 0) vk = VK_DELETE;\n else if (stricmp(lastToken, \"Num0\") == 0) vk = VK_NUMPAD0;\n else if (stricmp(lastToken, \"Num1\") == 0) vk = VK_NUMPAD1;\n else if (stricmp(lastToken, \"Num2\") == 0) vk = VK_NUMPAD2;\n else if (stricmp(lastToken, \"Num3\") == 0) vk = VK_NUMPAD3;\n else if (stricmp(lastToken, \"Num4\") == 0) vk = VK_NUMPAD4;\n else if (stricmp(lastToken, \"Num5\") == 0) vk = VK_NUMPAD5;\n else if (stricmp(lastToken, \"Num6\") == 0) vk = VK_NUMPAD6;\n else if (stricmp(lastToken, \"Num7\") == 0) vk = VK_NUMPAD7;\n else if (stricmp(lastToken, \"Num8\") == 0) vk = VK_NUMPAD8;\n else if (stricmp(lastToken, \"Num9\") == 0) vk = VK_NUMPAD9;\n else if (stricmp(lastToken, \"Num*\") == 0) vk = VK_MULTIPLY;\n else if (stricmp(lastToken, \"Num+\") == 0) vk = VK_ADD;\n else if (stricmp(lastToken, \"Num-\") == 0) vk = VK_SUBTRACT;\n else if (stricmp(lastToken, \"Num.\") == 0) vk = VK_DECIMAL;\n else if (stricmp(lastToken, \"Num/\") == 0) vk = VK_DIVIDE;\n // 检查十六进制格式\n else if (strncmp(lastToken, \"0x\", 2) == 0) {\n vk = (BYTE)strtol(lastToken, NULL, 16);\n }\n }\n \n return MAKEWORD(vk, mod);\n}\n\n/**\n * @brief Read custom countdown hotkey setting from configuration file\n * @param hotkey Pointer to store the hotkey\n */\nvoid ReadCustomCountdownHotkey(WORD* hotkey) {\n if (!hotkey) return;\n \n *hotkey = 0; // 默认为0(未设置)\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_CUSTOM_COUNTDOWN=\", 24) == 0) {\n char* value = line + 24;\n // 去除末尾的换行符\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // 解析热键字符串\n *hotkey = StringToHotkey(value);\n break;\n }\n }\n \n fclose(file);\n}\n\n/**\n * @brief Write a single configuration item to the configuration file\n * @param key Configuration item key name\n * @param value Configuration item value\n * \n * Adds or updates a single configuration item in the configuration file, automatically selects section based on key name\n */\nvoid WriteConfigKeyValue(const char* key, const char* value) {\n if (!key || !value) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Determine which section to place in based on the key name\n const char* section;\n \n if (strcmp(key, \"CONFIG_VERSION\") == 0 ||\n strcmp(key, \"LANGUAGE\") == 0 ||\n strcmp(key, \"SHORTCUT_CHECK_DONE\") == 0) {\n section = INI_SECTION_GENERAL;\n }\n else if (strncmp(key, \"CLOCK_TEXT_COLOR\", 16) == 0 ||\n strncmp(key, \"FONT_FILE_NAME\", 14) == 0 ||\n strncmp(key, \"CLOCK_BASE_FONT_SIZE\", 20) == 0 ||\n strncmp(key, \"WINDOW_SCALE\", 12) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_X\", 18) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_Y\", 18) == 0 ||\n strncmp(key, \"WINDOW_TOPMOST\", 14) == 0) {\n section = INI_SECTION_DISPLAY;\n }\n else if (strncmp(key, \"CLOCK_DEFAULT_START_TIME\", 24) == 0 ||\n strncmp(key, \"CLOCK_USE_24HOUR\", 16) == 0 ||\n strncmp(key, \"CLOCK_SHOW_SECONDS\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIME_OPTIONS\", 18) == 0 ||\n strncmp(key, \"STARTUP_MODE\", 12) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_TEXT\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_ACTION\", 20) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_FILE\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_WEBSITE\", 21) == 0) {\n section = INI_SECTION_TIMER;\n }\n else if (strncmp(key, \"POMODORO_\", 9) == 0) {\n section = INI_SECTION_POMODORO;\n }\n else if (strncmp(key, \"NOTIFICATION_\", 13) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", 26) == 0) {\n section = INI_SECTION_NOTIFICATION;\n }\n else if (strncmp(key, \"HOTKEY_\", 7) == 0) {\n section = INI_SECTION_HOTKEYS;\n }\n else if (strncmp(key, \"CLOCK_RECENT_FILE\", 17) == 0) {\n section = INI_SECTION_RECENTFILES;\n }\n else if (strncmp(key, \"COLOR_OPTIONS\", 13) == 0) {\n section = INI_SECTION_COLORS;\n }\n else {\n // 其他设置放在OPTIONS节\n section = INI_SECTION_OPTIONS;\n }\n \n // 写入配置\n WriteIniString(section, key, value, config_path);\n}\n\n/** @brief Write current language setting to configuration file */\nvoid WriteConfigLanguage(int language) {\n const char* langName;\n \n // Convert language enum value to readable language name\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_ENGLISH:\n langName = \"English\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n default:\n langName = \"English\"; // Default to English\n break;\n }\n \n WriteConfigKeyValue(\"LANGUAGE\", langName);\n}\n\n/** @brief Determine if shortcut check has been performed */\nbool IsShortcutCheckDone(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n return ReadIniBool(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", FALSE, config_path);\n}\n\n/** @brief Set shortcut check status */\nvoid SetShortcutCheckDone(bool done) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // 使用INI写入方式设置状态\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", done ? \"TRUE\" : \"FALSE\", config_path);\n}\n\n/** @brief Read whether to disable notification setting from configuration file */\nvoid ReadNotificationDisabledConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n}\n\n/** @brief Write whether to disable notification configuration */\nvoid WriteConfigNotificationDisabled(BOOL disabled) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_DISABLED=\", 22) == 0) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If configuration item not found in the configuration, add it\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_DISABLED = disabled;\n}\n"], ["/Catime/src/main.c", "/**\n * @file main.c\n * @brief Application main entry module implementation file\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\"\n#include \"../include/window.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/media.h\"\n#include \"../include/notification.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/dialog_language.h\"\n#include \"../include/shortcut_checker.h\"\n\n// Required for older Windows SDK\n#ifndef CSIDL_STARTUP\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n// Compiler directives\n#pragma comment(lib, \"dwmapi.lib\")\n#pragma comment(lib, \"user32.lib\")\n#pragma comment(lib, \"gdi32.lib\")\n#pragma comment(lib, \"comdlg32.lib\")\n#pragma comment(lib, \"dbghelp.lib\")\n#pragma comment(lib, \"comctl32.lib\")\n\nextern void CleanupLogSystem(void);\n\nint default_countdown_time = 0;\nint CLOCK_DEFAULT_START_TIME = 300;\nint elapsed_time = 0;\nchar inputText[256] = {0};\nint message_shown = 0;\ntime_t last_config_time = 0;\nRecentFile CLOCK_RECENT_FILES[MAX_RECENT_FILES];\nint CLOCK_RECENT_FILES_COUNT = 0;\nchar CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH] = \"\";\n\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char FONT_INTERNAL_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\n\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid ExitProgram(HWND hwnd);\n\n/**\n * @brief Handle application startup mode\n * @param hwnd Main window handle\n */\nstatic void HandleStartupMode(HWND hwnd) {\n LOG_INFO(\"Setting startup mode: %s\", CLOCK_STARTUP_MODE);\n \n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n LOG_INFO(\"Setting to count-up mode\");\n CLOCK_COUNT_UP = TRUE;\n elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n LOG_INFO(\"Setting to hidden mode, window will be hidden\");\n ShowWindow(hwnd, SW_HIDE);\n KillTimer(hwnd, 1);\n elapsed_time = CLOCK_TOTAL_TIME;\n CLOCK_IS_PAUSED = TRUE;\n message_shown = TRUE;\n countdown_message_shown = TRUE;\n countup_message_shown = TRUE;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n LOG_INFO(\"Setting to show current time mode\");\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_LAST_TIME_UPDATE = 0;\n } else {\n LOG_INFO(\"Using default countdown mode\");\n }\n}\n\n/**\n * @brief Application main entry point\n */\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n // Initialize Common Controls\n InitCommonControls();\n \n // Initialize log system\n if (!InitializeLogSystem()) {\n // If log system initialization fails, continue running but without logging\n MessageBox(NULL, \"Log system initialization failed, the program will continue running but will not log.\", \"Warning\", MB_ICONWARNING);\n }\n\n // Set up exception handler\n SetupExceptionHandler();\n\n LOG_INFO(\"Catime is starting...\");\n // Initialize COM\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM initialization failed, error code: 0x%08X\", hr);\n MessageBox(NULL, \"COM initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"COM initialization successful\");\n\n // Initialize application\n LOG_INFO(\"Starting application initialization...\");\n if (!InitializeApplication(hInstance)) {\n LOG_ERROR(\"Application initialization failed\");\n MessageBox(NULL, \"Application initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"Application initialization successful\");\n\n // Check and create desktop shortcut (if necessary)\n LOG_INFO(\"Checking desktop shortcut...\");\n char exe_path[MAX_PATH];\n GetModuleFileNameA(NULL, exe_path, MAX_PATH);\n LOG_INFO(\"Current program path: %s\", exe_path);\n \n // Set log level to DEBUG to show detailed information\n WriteLog(LOG_LEVEL_DEBUG, \"Starting shortcut detection, checking path: %s\", exe_path);\n \n // Check if path contains WinGet identifier\n if (strstr(exe_path, \"WinGet\") != NULL) {\n WriteLog(LOG_LEVEL_DEBUG, \"Path contains WinGet keyword\");\n }\n \n // Additional test: directly test if file exists\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path))) {\n sprintf(shortcut_path, \"%s\\\\Catime.lnk\", desktop_path);\n WriteLog(LOG_LEVEL_DEBUG, \"Checking if desktop shortcut exists: %s\", shortcut_path);\n if (GetFileAttributesA(shortcut_path) == INVALID_FILE_ATTRIBUTES) {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut does not exist, need to create\");\n } else {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut already exists\");\n }\n }\n \n int shortcut_result = CheckAndCreateShortcut();\n if (shortcut_result == 0) {\n LOG_INFO(\"Desktop shortcut check completed\");\n } else {\n LOG_WARNING(\"Desktop shortcut creation failed, error code: %d\", shortcut_result);\n }\n\n // Initialize dialog multi-language support\n LOG_INFO(\"Starting dialog multi-language support initialization...\");\n if (!InitDialogLanguageSupport()) {\n LOG_WARNING(\"Dialog multi-language support initialization failed, but program will continue running\");\n }\n LOG_INFO(\"Dialog multi-language support initialization successful\");\n\n // Handle single instance\n LOG_INFO(\"Checking if another instance is running...\");\n HANDLE hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n DWORD mutexError = GetLastError();\n \n if (mutexError == ERROR_ALREADY_EXISTS) {\n LOG_INFO(\"Detected another instance is running, trying to close that instance\");\n HWND hwndExisting = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwndExisting) {\n // Close existing window instance\n LOG_INFO(\"Sending close message to existing instance\");\n SendMessage(hwndExisting, WM_CLOSE, 0, 0);\n // Wait for old instance to close\n Sleep(200);\n } else {\n LOG_WARNING(\"Could not find window handle of existing instance, but mutex exists\");\n }\n // Release old mutex\n ReleaseMutex(hMutex);\n CloseHandle(hMutex);\n \n // Create new mutex\n LOG_INFO(\"Creating new mutex\");\n hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n if (GetLastError() == ERROR_ALREADY_EXISTS) {\n LOG_WARNING(\"Still have conflict after creating new mutex, possible race condition\");\n }\n }\n Sleep(50);\n\n // Create main window\n LOG_INFO(\"Starting main window creation...\");\n HWND hwnd = CreateMainWindow(hInstance, nCmdShow);\n if (!hwnd) {\n LOG_ERROR(\"Main window creation failed\");\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Main window creation successful, handle: 0x%p\", hwnd);\n\n // Set timer\n LOG_INFO(\"Setting main timer...\");\n if (SetTimer(hwnd, 1, 1000, NULL) == 0) {\n DWORD timerError = GetLastError();\n LOG_ERROR(\"Timer creation failed, error code: %lu\", timerError);\n MessageBox(NULL, \"Timer Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Timer set successfully\");\n\n // Handle startup mode\n LOG_INFO(\"Handling startup mode: %s\", CLOCK_STARTUP_MODE);\n HandleStartupMode(hwnd);\n \n // Automatic update check code has been removed\n\n // Message loop\n LOG_INFO(\"Entering main message loop\");\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0) > 0) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n // Clean up resources\n LOG_INFO(\"Program preparing to exit, starting resource cleanup\");\n \n // Clean up update check thread resources\n LOG_INFO(\"Preparing to clean up update check thread resources\");\n CleanupUpdateThread();\n \n CloseHandle(hMutex);\n CoUninitialize();\n \n // Close log system\n CleanupLogSystem();\n \n return (int)msg.wParam;\n // If execution reaches here, the program has exited normally\n}\n"], ["/Catime/src/language.c", "/**\n * @file language.c\n * @brief Multilingual support module implementation\n * \n * This file implements the multilingual support functionality for the application, \n * including language detection and localized string handling.\n * Translation content is embedded as resources in the executable file.\n */\n\n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\n/// Global language variable, stores the current application language setting\nAppLanguage CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default to English\n\n/// Global hash table for storing translations of the current language\n#define MAX_TRANSLATIONS 200\n#define MAX_STRING_LENGTH 1024\n\n// Language resource IDs (defined in languages.rc)\n#define LANG_EN_INI 1001 // Corresponds to languages/en.ini\n#define LANG_ZH_CN_INI 1002 // Corresponds to languages/zh_CN.ini\n#define LANG_ZH_TW_INI 1003 // Corresponds to languages/zh-Hant.ini\n#define LANG_ES_INI 1004 // Corresponds to languages/es.ini\n#define LANG_FR_INI 1005 // Corresponds to languages/fr.ini\n#define LANG_DE_INI 1006 // Corresponds to languages/de.ini\n#define LANG_RU_INI 1007 // Corresponds to languages/ru.ini\n#define LANG_PT_INI 1008 // Corresponds to languages/pt.ini\n#define LANG_JA_INI 1009 // Corresponds to languages/ja.ini\n#define LANG_KO_INI 1010 // Corresponds to languages/ko.ini\n\n/**\n * @brief Define language string key-value pair structure\n */\ntypedef struct {\n wchar_t english[MAX_STRING_LENGTH]; // English key\n wchar_t translation[MAX_STRING_LENGTH]; // Translated value\n} LocalizedString;\n\nstatic LocalizedString g_translations[MAX_TRANSLATIONS];\nstatic int g_translation_count = 0;\n\n/**\n * @brief Get the resource ID corresponding to a language\n * \n * @param language Language enumeration value\n * @return UINT Corresponding resource ID\n */\nstatic UINT GetLanguageResourceID(AppLanguage language) {\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n return LANG_ZH_CN_INI;\n case APP_LANG_CHINESE_TRAD:\n return LANG_ZH_TW_INI;\n case APP_LANG_SPANISH:\n return LANG_ES_INI;\n case APP_LANG_FRENCH:\n return LANG_FR_INI;\n case APP_LANG_GERMAN:\n return LANG_DE_INI;\n case APP_LANG_RUSSIAN:\n return LANG_RU_INI;\n case APP_LANG_PORTUGUESE:\n return LANG_PT_INI;\n case APP_LANG_JAPANESE:\n return LANG_JA_INI;\n case APP_LANG_KOREAN:\n return LANG_KO_INI;\n case APP_LANG_ENGLISH:\n default:\n return LANG_EN_INI;\n }\n}\n\n/**\n * @brief Convert UTF-8 string to wide character (UTF-16) string\n * \n * @param utf8 UTF-8 string\n * @param wstr Output wide character string buffer\n * @param wstr_size Buffer size (in characters)\n * @return int Number of characters after conversion, returns -1 if failed\n */\nstatic int UTF8ToWideChar(const char* utf8, wchar_t* wstr, int wstr_size) {\n return MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, wstr_size) - 1;\n}\n\n/**\n * @brief Parse a line in an ini file\n * \n * @param line A line from the ini file\n * @return int Whether parsing was successful (1 for success, 0 for failure)\n */\nstatic int ParseIniLine(const wchar_t* line) {\n // Skip empty lines and comment lines\n if (line[0] == L'\\0' || line[0] == L';' || line[0] == L'[') {\n return 0;\n }\n\n // Find content between the first and last quotes as the key\n const wchar_t* key_start = wcschr(line, L'\"');\n if (!key_start) return 0;\n key_start++; // Skip the first quote\n\n const wchar_t* key_end = wcschr(key_start, L'\"');\n if (!key_end) return 0;\n\n // Find content between the first and last quotes after the equal sign as the value\n const wchar_t* value_start = wcschr(key_end + 1, L'=');\n if (!value_start) return 0;\n \n value_start = wcschr(value_start, L'\"');\n if (!value_start) return 0;\n value_start++; // Skip the first quote\n\n const wchar_t* value_end = wcsrchr(value_start, L'\"');\n if (!value_end) return 0;\n\n // Copy key\n size_t key_len = key_end - key_start;\n if (key_len >= MAX_STRING_LENGTH) key_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].english, key_start, key_len);\n g_translations[g_translation_count].english[key_len] = L'\\0';\n\n // Copy value\n size_t value_len = value_end - value_start;\n if (value_len >= MAX_STRING_LENGTH) value_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].translation, value_start, value_len);\n g_translations[g_translation_count].translation[value_len] = L'\\0';\n\n g_translation_count++;\n return 1;\n}\n\n/**\n * @brief Load translations for a specified language from resources\n * \n * @param language Language enumeration value\n * @return int Whether loading was successful\n */\nstatic int LoadLanguageResource(AppLanguage language) {\n UINT resourceID = GetLanguageResourceID(language);\n \n // Reset translation count\n g_translation_count = 0;\n \n // Find resource\n HRSRC hResInfo = FindResource(NULL, MAKEINTRESOURCE(resourceID), RT_RCDATA);\n if (!hResInfo) {\n // If not found, check if it's Chinese and return\n if (language == APP_LANG_CHINESE_SIMP || language == APP_LANG_CHINESE_TRAD) {\n return 0;\n }\n \n // If not Chinese, load English as fallback\n if (language != APP_LANG_ENGLISH) {\n return LoadLanguageResource(APP_LANG_ENGLISH);\n }\n \n return 0;\n }\n \n // Get resource size\n DWORD dwSize = SizeofResource(NULL, hResInfo);\n if (dwSize == 0) {\n return 0;\n }\n \n // Load resource\n HGLOBAL hResData = LoadResource(NULL, hResInfo);\n if (!hResData) {\n return 0;\n }\n \n // Lock resource to get pointer\n const char* pData = (const char*)LockResource(hResData);\n if (!pData) {\n return 0;\n }\n \n // Create memory buffer copy\n char* buffer = (char*)malloc(dwSize + 1);\n if (!buffer) {\n return 0;\n }\n \n // Copy resource data to buffer\n memcpy(buffer, pData, dwSize);\n buffer[dwSize] = '\\0';\n \n // Split by lines and parse\n char* line = strtok(buffer, \"\\r\\n\");\n wchar_t wide_buffer[MAX_STRING_LENGTH];\n \n while (line && g_translation_count < MAX_TRANSLATIONS) {\n // Skip empty lines and BOM markers\n if (line[0] == '\\0' || (line[0] == (char)0xEF && line[1] == (char)0xBB && line[2] == (char)0xBF)) {\n line = strtok(NULL, \"\\r\\n\");\n continue;\n }\n \n // Convert to wide characters\n if (UTF8ToWideChar(line, wide_buffer, MAX_STRING_LENGTH) > 0) {\n ParseIniLine(wide_buffer);\n }\n \n line = strtok(NULL, \"\\r\\n\");\n }\n \n free(buffer);\n return 1;\n}\n\n/**\n * @brief Find corresponding translation in the global translation table\n * \n * @param english English original text\n * @return const wchar_t* Found translation, returns NULL if not found\n */\nstatic const wchar_t* FindTranslation(const wchar_t* english) {\n for (int i = 0; i < g_translation_count; i++) {\n if (wcscmp(english, g_translations[i].english) == 0) {\n return g_translations[i].translation;\n }\n }\n return NULL;\n}\n\n/**\n * @brief Initialize the application language environment\n * \n * Automatically detect and set the current language of the application based on system language.\n * Supports detection of Simplified Chinese, Traditional Chinese, and other preset languages.\n */\nstatic void DetectSystemLanguage() {\n LANGID langID = GetUserDefaultUILanguage();\n switch (PRIMARYLANGID(langID)) {\n case LANG_CHINESE:\n // Distinguish between Simplified and Traditional Chinese\n if (SUBLANGID(langID) == SUBLANG_CHINESE_SIMPLIFIED) {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_SIMP;\n } else {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_TRAD;\n }\n break;\n case LANG_SPANISH:\n CURRENT_LANGUAGE = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n CURRENT_LANGUAGE = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n CURRENT_LANGUAGE = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n CURRENT_LANGUAGE = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n CURRENT_LANGUAGE = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n CURRENT_LANGUAGE = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n CURRENT_LANGUAGE = APP_LANG_KOREAN;\n break;\n default:\n CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default fallback to English\n }\n}\n\n/**\n * @brief Get localized string\n * @param chinese Simplified Chinese version of the string\n * @param english English version of the string\n * @return const wchar_t* Pointer to the string corresponding to the current language\n * \n * Returns the string in the corresponding language based on the current language setting.\n */\nconst wchar_t* GetLocalizedString(const wchar_t* chinese, const wchar_t* english) {\n // Initialize translation resources on first call, but don't automatically detect system language\n static BOOL initialized = FALSE;\n if (!initialized) {\n // No longer call DetectSystemLanguage() to automatically detect system language\n // Instead, use the currently set CURRENT_LANGUAGE value (possibly from a configuration file)\n LoadLanguageResource(CURRENT_LANGUAGE);\n initialized = TRUE;\n }\n\n const wchar_t* translation = NULL;\n\n // If Simplified Chinese and Chinese string is provided, return directly\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP && chinese) {\n return chinese;\n }\n\n // Find translation\n translation = FindTranslation(english);\n if (translation) {\n return translation;\n }\n\n // For Traditional Chinese but no translation found, return Simplified Chinese as a fallback\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD && chinese) {\n return chinese;\n }\n\n // Default to English\n return english;\n}\n\n/**\n * @brief Set application language\n * \n * @param language The language to set\n * @return BOOL Whether the setting was successful\n */\nBOOL SetLanguage(AppLanguage language) {\n if (language < 0 || language >= APP_LANG_COUNT) {\n return FALSE;\n }\n \n CURRENT_LANGUAGE = language;\n g_translation_count = 0; // Clear existing translations\n return LoadLanguageResource(language);\n}\n\n/**\n * @brief Get current application language\n * \n * @return AppLanguage Current language\n */\nAppLanguage GetCurrentLanguage() {\n return CURRENT_LANGUAGE;\n}\n\n/**\n * @brief Get the name of the current language\n * @param buffer Buffer to store the language name\n * @param bufferSize Buffer size (in characters)\n * @return Whether the language name was successfully retrieved\n */\nBOOL GetCurrentLanguageName(wchar_t* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) {\n return FALSE;\n }\n \n // Get current language\n AppLanguage language = GetCurrentLanguage();\n \n // Return corresponding name based on language enumeration\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n wcscpy_s(buffer, bufferSize, L\"zh_CN\");\n break;\n case APP_LANG_CHINESE_TRAD:\n wcscpy_s(buffer, bufferSize, L\"zh-Hant\");\n break;\n case APP_LANG_SPANISH:\n wcscpy_s(buffer, bufferSize, L\"es\");\n break;\n case APP_LANG_FRENCH:\n wcscpy_s(buffer, bufferSize, L\"fr\");\n break;\n case APP_LANG_GERMAN:\n wcscpy_s(buffer, bufferSize, L\"de\");\n break;\n case APP_LANG_RUSSIAN:\n wcscpy_s(buffer, bufferSize, L\"ru\");\n break;\n case APP_LANG_PORTUGUESE:\n wcscpy_s(buffer, bufferSize, L\"pt\");\n break;\n case APP_LANG_JAPANESE:\n wcscpy_s(buffer, bufferSize, L\"ja\");\n break;\n case APP_LANG_KOREAN:\n wcscpy_s(buffer, bufferSize, L\"ko\");\n break;\n case APP_LANG_ENGLISH:\n default:\n wcscpy_s(buffer, bufferSize, L\"en\");\n break;\n }\n \n return TRUE;\n}\n"], ["/Catime/src/hotkey.c", "/**\n * @file hotkey.c\n * @brief Hotkey management implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#if defined _M_IX86\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_IA64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_X64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#else\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#endif\n#include \"../include/hotkey.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../resource/resource.h\"\n\n#ifndef HOTKEYF_SHIFT\n#define HOTKEYF_SHIFT 0x01\n#define HOTKEYF_CONTROL 0x02\n#define HOTKEYF_ALT 0x04\n#endif\n\nstatic WORD g_dlgShowTimeHotkey = 0;\nstatic WORD g_dlgCountUpHotkey = 0;\nstatic WORD g_dlgCountdownHotkey = 0;\nstatic WORD g_dlgCustomCountdownHotkey = 0;\nstatic WORD g_dlgQuickCountdown1Hotkey = 0;\nstatic WORD g_dlgQuickCountdown2Hotkey = 0;\nstatic WORD g_dlgQuickCountdown3Hotkey = 0;\nstatic WORD g_dlgPomodoroHotkey = 0;\nstatic WORD g_dlgToggleVisibilityHotkey = 0;\nstatic WORD g_dlgEditModeHotkey = 0;\nstatic WORD g_dlgPauseResumeHotkey = 0;\nstatic WORD g_dlgRestartTimerHotkey = 0;\n\nstatic WNDPROC g_OldHotkeyDlgProc = NULL;\n\n/**\n * @brief Dialog subclassing procedure\n */\nLRESULT CALLBACK HotkeyDialogSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n if (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN || msg == WM_KEYUP || msg == WM_SYSKEYUP) {\n BYTE vk = (BYTE)wParam;\n if (!(vk == VK_SHIFT || vk == VK_CONTROL || vk == VK_MENU || vk == VK_LWIN || vk == VK_RWIN)) {\n BYTE currentModifiers = 0;\n if (GetKeyState(VK_SHIFT) & 0x8000) currentModifiers |= HOTKEYF_SHIFT;\n if (GetKeyState(VK_CONTROL) & 0x8000) currentModifiers |= HOTKEYF_CONTROL;\n if (msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP || (GetKeyState(VK_MENU) & 0x8000)) {\n currentModifiers |= HOTKEYF_ALT;\n }\n\n WORD currentEventKeyCombination = MAKEWORD(vk, currentModifiers);\n\n const WORD originalHotkeys[] = {\n g_dlgShowTimeHotkey, g_dlgCountUpHotkey, g_dlgCountdownHotkey,\n g_dlgQuickCountdown1Hotkey, g_dlgQuickCountdown2Hotkey, g_dlgQuickCountdown3Hotkey,\n g_dlgPomodoroHotkey, g_dlgToggleVisibilityHotkey, g_dlgEditModeHotkey,\n g_dlgPauseResumeHotkey, g_dlgRestartTimerHotkey\n };\n BOOL isAnOriginalHotkeyEvent = FALSE;\n for (size_t i = 0; i < sizeof(originalHotkeys) / sizeof(originalHotkeys[0]); ++i) {\n if (originalHotkeys[i] != 0 && originalHotkeys[i] == currentEventKeyCombination) {\n isAnOriginalHotkeyEvent = TRUE;\n break;\n }\n }\n\n if (isAnOriginalHotkeyEvent) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n }\n\n switch (msg) {\n case WM_SYSKEYDOWN:\n case WM_SYSKEYUP:\n {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (isHotkeyEditControl) {\n break;\n }\n }\n return 0;\n }\n\n case WM_KEYDOWN:\n case WM_KEYUP:\n {\n BYTE vk_code = (BYTE)wParam;\n if (vk_code == VK_SHIFT || vk_code == VK_CONTROL || vk_code == VK_LWIN || vk_code == VK_RWIN) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n break;\n\n case WM_SYSCOMMAND:\n if ((wParam & 0xFFF0) == SC_KEYMENU) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(g_OldHotkeyDlgProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Show hotkey settings dialog\n */\nvoid ShowHotkeySettingsDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_HOTKEY_DIALOG),\n hwndParent,\n HotkeySettingsDlgProc);\n}\n\n/**\n * @brief Check if a hotkey is a single key\n */\nBOOL IsSingleKey(WORD hotkey) {\n BYTE modifiers = HIBYTE(hotkey);\n\n return modifiers == 0;\n}\n\n/**\n * @brief Check if a hotkey is a standalone letter, number, or symbol\n */\nBOOL IsRestrictedSingleKey(WORD hotkey) {\n if (hotkey == 0) {\n return FALSE;\n }\n\n BYTE vk = LOBYTE(hotkey);\n BYTE modifiers = HIBYTE(hotkey);\n\n if (modifiers != 0) {\n return FALSE;\n }\n\n if (vk >= 'A' && vk <= 'Z') {\n return TRUE;\n }\n\n if (vk >= '0' && vk <= '9') {\n return TRUE;\n }\n\n if (vk >= VK_NUMPAD0 && vk <= VK_NUMPAD9) {\n return TRUE;\n }\n\n switch (vk) {\n case VK_OEM_1:\n case VK_OEM_PLUS:\n case VK_OEM_COMMA:\n case VK_OEM_MINUS:\n case VK_OEM_PERIOD:\n case VK_OEM_2:\n case VK_OEM_3:\n case VK_OEM_4:\n case VK_OEM_5:\n case VK_OEM_6:\n case VK_OEM_7:\n case VK_SPACE:\n case VK_RETURN:\n case VK_ESCAPE:\n case VK_TAB:\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey settings dialog message processing procedure\n */\nINT_PTR CALLBACK HotkeySettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL1,\n GetLocalizedString(L\"显示当前时间:\", L\"Show Current Time:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL2,\n GetLocalizedString(L\"正计时:\", L\"Count Up:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL12,\n GetLocalizedString(L\"倒计时:\", L\"Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL3,\n GetLocalizedString(L\"默认倒计时:\", L\"Default Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL9,\n GetLocalizedString(L\"快捷倒计时1:\", L\"Quick Countdown 1:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL10,\n GetLocalizedString(L\"快捷倒计时2:\", L\"Quick Countdown 2:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL11,\n GetLocalizedString(L\"快捷倒计时3:\", L\"Quick Countdown 3:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL4,\n GetLocalizedString(L\"开始番茄钟:\", L\"Start Pomodoro:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL5,\n GetLocalizedString(L\"隐藏/显示窗口:\", L\"Hide/Show Window:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL6,\n GetLocalizedString(L\"进入编辑模式:\", L\"Enter Edit Mode:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL7,\n GetLocalizedString(L\"暂停/继续计时:\", L\"Pause/Resume Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL8,\n GetLocalizedString(L\"重新开始计时:\", L\"Restart Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_NOTE,\n GetLocalizedString(L\"* 热键将全局生效\", L\"* Hotkeys will work globally\"));\n\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"确定\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"取消\", L\"Cancel\"));\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n ReadConfigHotkeys(&g_dlgShowTimeHotkey, &g_dlgCountUpHotkey, &g_dlgCountdownHotkey,\n &g_dlgQuickCountdown1Hotkey, &g_dlgQuickCountdown2Hotkey, &g_dlgQuickCountdown3Hotkey,\n &g_dlgPomodoroHotkey, &g_dlgToggleVisibilityHotkey, &g_dlgEditModeHotkey,\n &g_dlgPauseResumeHotkey, &g_dlgRestartTimerHotkey);\n\n ReadCustomCountdownHotkey(&g_dlgCustomCountdownHotkey);\n\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_SETHOTKEY, g_dlgShowTimeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_SETHOTKEY, g_dlgCountUpHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_SETHOTKEY, g_dlgCustomCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_SETHOTKEY, g_dlgCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_SETHOTKEY, g_dlgQuickCountdown1Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_SETHOTKEY, g_dlgQuickCountdown2Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_SETHOTKEY, g_dlgQuickCountdown3Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_SETHOTKEY, g_dlgPomodoroHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_SETHOTKEY, g_dlgToggleVisibilityHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_SETHOTKEY, g_dlgEditModeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_SETHOTKEY, g_dlgPauseResumeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_SETHOTKEY, g_dlgRestartTimerHotkey, 0);\n\n UnregisterGlobalHotkeys(GetParent(hwndDlg));\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n SetWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i, 0);\n }\n }\n\n g_OldHotkeyDlgProc = (WNDPROC)SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)HotkeyDialogSubclassProc);\n\n SetFocus(GetDlgItem(hwndDlg, IDCANCEL));\n\n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n \n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n \n case WM_LBUTTONDOWN: {\n POINT pt = {LOWORD(lParam), HIWORD(lParam)};\n HWND hwndHit = ChildWindowFromPoint(hwndDlg, pt);\n\n if (hwndHit != NULL && hwndHit != hwndDlg) {\n int ctrlId = GetDlgCtrlID(hwndHit);\n\n BOOL isHotkeyEdit = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) {\n isHotkeyEdit = TRUE;\n break;\n }\n }\n\n if (!isHotkeyEdit) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n }\n }\n else if (hwndHit == hwndDlg) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND: {\n WORD ctrlId = LOWORD(wParam);\n WORD notifyCode = HIWORD(wParam);\n\n if (notifyCode == EN_CHANGE &&\n (ctrlId == IDC_HOTKEY_EDIT1 || ctrlId == IDC_HOTKEY_EDIT2 ||\n ctrlId == IDC_HOTKEY_EDIT3 || ctrlId == IDC_HOTKEY_EDIT4 ||\n ctrlId == IDC_HOTKEY_EDIT5 || ctrlId == IDC_HOTKEY_EDIT6 ||\n ctrlId == IDC_HOTKEY_EDIT7 || ctrlId == IDC_HOTKEY_EDIT8 ||\n ctrlId == IDC_HOTKEY_EDIT9 || ctrlId == IDC_HOTKEY_EDIT10 ||\n ctrlId == IDC_HOTKEY_EDIT11 || ctrlId == IDC_HOTKEY_EDIT12)) {\n\n WORD newHotkey = (WORD)SendDlgItemMessage(hwndDlg, ctrlId, HKM_GETHOTKEY, 0, 0);\n\n BYTE vk = LOBYTE(newHotkey);\n BYTE modifiers = HIBYTE(newHotkey);\n\n if (vk == 0xE5 && modifiers == HOTKEYF_SHIFT) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0 && IsRestrictedSingleKey(newHotkey)) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0) {\n static const int hotkeyCtrlIds[] = {\n IDC_HOTKEY_EDIT1, IDC_HOTKEY_EDIT2, IDC_HOTKEY_EDIT3,\n IDC_HOTKEY_EDIT9, IDC_HOTKEY_EDIT10, IDC_HOTKEY_EDIT11,\n IDC_HOTKEY_EDIT4, IDC_HOTKEY_EDIT5, IDC_HOTKEY_EDIT6,\n IDC_HOTKEY_EDIT7, IDC_HOTKEY_EDIT8, IDC_HOTKEY_EDIT12\n };\n\n for (int i = 0; i < sizeof(hotkeyCtrlIds) / sizeof(hotkeyCtrlIds[0]); i++) {\n if (hotkeyCtrlIds[i] == ctrlId) {\n continue;\n }\n\n WORD otherHotkey = (WORD)SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_GETHOTKEY, 0, 0);\n\n if (otherHotkey != 0 && otherHotkey == newHotkey) {\n SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_SETHOTKEY, 0, 0);\n }\n }\n }\n\n return TRUE;\n }\n \n switch (LOWORD(wParam)) {\n case IDOK: {\n WORD showTimeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_GETHOTKEY, 0, 0);\n WORD countUpHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_GETHOTKEY, 0, 0);\n WORD customCountdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_GETHOTKEY, 0, 0);\n WORD countdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown1Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown2Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown3Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_GETHOTKEY, 0, 0);\n WORD pomodoroHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_GETHOTKEY, 0, 0);\n WORD toggleVisibilityHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_GETHOTKEY, 0, 0);\n WORD editModeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_GETHOTKEY, 0, 0);\n WORD pauseResumeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_GETHOTKEY, 0, 0);\n WORD restartTimerHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_GETHOTKEY, 0, 0);\n\n WORD* hotkeys[] = {\n &showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey, &customCountdownHotkey\n };\n\n for (int i = 0; i < sizeof(hotkeys) / sizeof(hotkeys[0]); i++) {\n if (LOBYTE(*hotkeys[i]) == 0xE5 && HIBYTE(*hotkeys[i]) == HOTKEYF_SHIFT) {\n *hotkeys[i] = 0;\n continue;\n }\n\n if (*hotkeys[i] != 0 && IsRestrictedSingleKey(*hotkeys[i])) {\n *hotkeys[i] = 0;\n }\n }\n\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n g_dlgCustomCountdownHotkey = customCountdownHotkey;\n char customCountdownStr[64] = {0};\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr);\n\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n\n case IDCANCEL:\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n \n case WM_DESTROY:\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n if (g_OldHotkeyDlgProc) {\n SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)g_OldHotkeyDlgProc);\n g_OldHotkeyDlgProc = NULL;\n }\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n RemoveWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i);\n }\n }\n break;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey control subclass procedure\n */\nLRESULT CALLBACK HotkeyControlSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam,\n LPARAM lParam, UINT_PTR uIdSubclass,\n DWORD_PTR dwRefData) {\n switch (uMsg) {\n case WM_GETDLGCODE:\n return DLGC_WANTALLKEYS | DLGC_WANTCHARS;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(hwndDlg, IDOK));\n return 0;\n }\n }\n break;\n }\n\n return DefSubclassProc(hwnd, uMsg, wParam, lParam);\n}"], ["/Catime/src/font.c", "/**\n * @file font.c\n * @brief Font management module implementation file\n * \n * This file implements the font management functionality of the application, including font loading, preview,\n * application and configuration file management. Supports loading multiple predefined fonts from resources.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/font.h\"\n#include \"../resource/resource.h\"\n\n/// @name Global font variables\n/// @{\nchar FONT_FILE_NAME[100] = \"Hack Nerd Font.ttf\"; ///< Currently used font file name\nchar FONT_INTERNAL_NAME[100]; ///< Font internal name (without extension)\nchar PREVIEW_FONT_NAME[100] = \"\"; ///< Preview font file name\nchar PREVIEW_INTERNAL_NAME[100] = \"\"; ///< Preview font internal name\nBOOL IS_PREVIEWING = FALSE; ///< Whether font preview is active\n/// @}\n\n/**\n * @brief Font resource array\n * \n * Stores information for all built-in font resources in the application\n */\nFontResource fontResources[] = {\n {CLOCK_IDC_FONT_RECMONO, IDR_FONT_RECMONO, \"RecMonoCasual Nerd Font Mono Essence.ttf\"},\n {CLOCK_IDC_FONT_DEPARTURE, IDR_FONT_DEPARTURE, \"DepartureMono Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_TERMINESS, IDR_FONT_TERMINESS, \"Terminess Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_ARBUTUS, IDR_FONT_ARBUTUS, \"Arbutus Essence.ttf\"},\n {CLOCK_IDC_FONT_BERKSHIRE, IDR_FONT_BERKSHIRE, \"Berkshire Swash Essence.ttf\"},\n {CLOCK_IDC_FONT_CAVEAT, IDR_FONT_CAVEAT, \"Caveat Brush Essence.ttf\"},\n {CLOCK_IDC_FONT_CREEPSTER, IDR_FONT_CREEPSTER, \"Creepster Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTGOTHIC, IDR_FONT_DOTGOTHIC, \"DotGothic16 Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTO, IDR_FONT_DOTO, \"Doto ExtraBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FOLDIT, IDR_FONT_FOLDIT, \"Foldit SemiBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FREDERICKA, IDR_FONT_FREDERICKA, \"Fredericka the Great Essence.ttf\"},\n {CLOCK_IDC_FONT_FRIJOLE, IDR_FONT_FRIJOLE, \"Frijole Essence.ttf\"},\n {CLOCK_IDC_FONT_GWENDOLYN, IDR_FONT_GWENDOLYN, \"Gwendolyn Essence.ttf\"},\n {CLOCK_IDC_FONT_HANDJET, IDR_FONT_HANDJET, \"Handjet Essence.ttf\"},\n {CLOCK_IDC_FONT_INKNUT, IDR_FONT_INKNUT, \"Inknut Antiqua Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARD, IDR_FONT_JACQUARD, \"Jacquard 12 Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARDA, IDR_FONT_JACQUARDA, \"Jacquarda Bastarda 9 Essence.ttf\"},\n {CLOCK_IDC_FONT_KAVOON, IDR_FONT_KAVOON, \"Kavoon Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE, IDR_FONT_KUMAR_ONE_OUTLINE, \"Kumar One Outline Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE, IDR_FONT_KUMAR_ONE, \"Kumar One Essence.ttf\"},\n {CLOCK_IDC_FONT_LAKKI_REDDY, IDR_FONT_LAKKI_REDDY, \"Lakki Reddy Essence.ttf\"},\n {CLOCK_IDC_FONT_LICORICE, IDR_FONT_LICORICE, \"Licorice Essence.ttf\"},\n {CLOCK_IDC_FONT_MA_SHAN_ZHENG, IDR_FONT_MA_SHAN_ZHENG, \"Ma Shan Zheng Essence.ttf\"},\n {CLOCK_IDC_FONT_MOIRAI_ONE, IDR_FONT_MOIRAI_ONE, \"Moirai One Essence.ttf\"},\n {CLOCK_IDC_FONT_MYSTERY_QUEST, IDR_FONT_MYSTERY_QUEST, \"Mystery Quest Essence.ttf\"},\n {CLOCK_IDC_FONT_NOTO_NASTALIQ, IDR_FONT_NOTO_NASTALIQ, \"Noto Nastaliq Urdu Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PIEDRA, IDR_FONT_PIEDRA, \"Piedra Essence.ttf\"},\n {CLOCK_IDC_FONT_PINYON_SCRIPT, IDR_FONT_PINYON_SCRIPT, \"Pinyon Script Essence.ttf\"},\n {CLOCK_IDC_FONT_PIXELIFY, IDR_FONT_PIXELIFY, \"Pixelify Sans Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PRESS_START, IDR_FONT_PRESS_START, \"Press Start 2P Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BUBBLES, IDR_FONT_RUBIK_BUBBLES, \"Rubik Bubbles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BURNED, IDR_FONT_RUBIK_BURNED, \"Rubik Burned Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_GLITCH, IDR_FONT_RUBIK_GLITCH, \"Rubik Glitch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_MARKER_HATCH, IDR_FONT_RUBIK_MARKER_HATCH, \"Rubik Marker Hatch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_PUDDLES, IDR_FONT_RUBIK_PUDDLES, \"Rubik Puddles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_VINYL, IDR_FONT_RUBIK_VINYL, \"Rubik Vinyl Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_WET_PAINT, IDR_FONT_RUBIK_WET_PAINT, \"Rubik Wet Paint Essence.ttf\"},\n {CLOCK_IDC_FONT_RUGE_BOOGIE, IDR_FONT_RUGE_BOOGIE, \"Ruge Boogie Essence.ttf\"},\n {CLOCK_IDC_FONT_SEVILLANA, IDR_FONT_SEVILLANA, \"Sevillana Essence.ttf\"},\n {CLOCK_IDC_FONT_SILKSCREEN, IDR_FONT_SILKSCREEN, \"Silkscreen Essence.ttf\"},\n {CLOCK_IDC_FONT_STICK, IDR_FONT_STICK, \"Stick Essence.ttf\"},\n {CLOCK_IDC_FONT_UNDERDOG, IDR_FONT_UNDERDOG, \"Underdog Essence.ttf\"},\n {CLOCK_IDC_FONT_WALLPOET, IDR_FONT_WALLPOET, \"Wallpoet Essence.ttf\"},\n {CLOCK_IDC_FONT_YESTERYEAR, IDR_FONT_YESTERYEAR, \"Yesteryear Essence.ttf\"},\n {CLOCK_IDC_FONT_ZCOOL_KUAILE, IDR_FONT_ZCOOL_KUAILE, \"ZCOOL KuaiLe Essence.ttf\"},\n {CLOCK_IDC_FONT_PROFONT, IDR_FONT_PROFONT, \"ProFont IIx Nerd Font Essence.ttf\"},\n {CLOCK_IDC_FONT_DADDYTIME, IDR_FONT_DADDYTIME, \"DaddyTimeMono Nerd Font Propo Essence.ttf\"},\n};\n\n/// Number of font resources\nconst int FONT_RESOURCES_COUNT = sizeof(fontResources) / sizeof(FontResource);\n\n/// @name External variable declarations\n/// @{\nextern char CLOCK_TEXT_COLOR[]; ///< Current clock text color\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t maxLen); ///< Get configuration file path\nextern void ReadConfig(void); ///< Read configuration file\nextern int CALLBACK EnumFontFamExProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam); ///< Font enumeration callback function\n/// @}\n\nBOOL LoadFontFromResource(HINSTANCE hInstance, int resourceId) {\n // Find font resource\n HRSRC hResource = FindResource(hInstance, MAKEINTRESOURCE(resourceId), RT_FONT);\n if (hResource == NULL) {\n return FALSE;\n }\n\n // Load resource into memory\n HGLOBAL hMemory = LoadResource(hInstance, hResource);\n if (hMemory == NULL) {\n return FALSE;\n }\n\n // Lock resource\n void* fontData = LockResource(hMemory);\n if (fontData == NULL) {\n return FALSE;\n }\n\n // Get resource size and add font\n DWORD fontLength = SizeofResource(hInstance, hResource);\n DWORD nFonts = 0;\n HANDLE handle = AddFontMemResourceEx(fontData, fontLength, NULL, &nFonts);\n \n if (handle == NULL) {\n return FALSE;\n }\n \n return TRUE;\n}\n\nBOOL LoadFontByName(HINSTANCE hInstance, const char* fontName) {\n // Iterate through the font resource array to find a matching font\n for (int i = 0; i < sizeof(fontResources) / sizeof(FontResource); i++) {\n if (strcmp(fontResources[i].fontName, fontName) == 0) {\n return LoadFontFromResource(hInstance, fontResources[i].resourceId);\n }\n }\n return FALSE;\n}\n\nvoid WriteConfigFont(const char* font_file_name) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Open configuration file for reading\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n // Read the entire configuration file content\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n // Create new configuration file content\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n // Process line by line and replace font settings\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"FONT_FILE_NAME=\", 15) == 0) {\n strcat(new_config, \"FONT_FILE_NAME=\");\n strcat(new_config, font_file_name);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n // Write new configuration content\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n // Re-read configuration\n ReadConfig();\n}\n\nvoid ListAvailableFonts(void) {\n HDC hdc = GetDC(NULL);\n LOGFONT lf;\n memset(&lf, 0, sizeof(LOGFONT));\n lf.lfCharSet = DEFAULT_CHARSET;\n\n // Create temporary font and enumerate fonts\n HFONT hFont = CreateFont(12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n lf.lfCharSet, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, NULL);\n SelectObject(hdc, hFont);\n\n EnumFontFamiliesEx(hdc, &lf, (FONTENUMPROC)EnumFontFamExProc, 0, 0);\n\n // Clean up resources\n DeleteObject(hFont);\n ReleaseDC(NULL, hdc);\n}\n\nint CALLBACK EnumFontFamExProc(\n ENUMLOGFONTEX *lpelfe,\n NEWTEXTMETRICEX *lpntme,\n DWORD FontType,\n LPARAM lParam\n) {\n return 1;\n}\n\nBOOL PreviewFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Save current font name\n strncpy(PREVIEW_FONT_NAME, fontName, sizeof(PREVIEW_FONT_NAME) - 1);\n PREVIEW_FONT_NAME[sizeof(PREVIEW_FONT_NAME) - 1] = '\\0';\n \n // Get internal font name (remove .ttf extension)\n size_t name_len = strlen(PREVIEW_FONT_NAME);\n if (name_len > 4 && strcmp(PREVIEW_FONT_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(PREVIEW_INTERNAL_NAME))\n copy_len = sizeof(PREVIEW_INTERNAL_NAME) - 1;\n \n memcpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, copy_len);\n PREVIEW_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, sizeof(PREVIEW_INTERNAL_NAME) - 1);\n PREVIEW_INTERNAL_NAME[sizeof(PREVIEW_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Load preview font\n if (!LoadFontByName(hInstance, PREVIEW_FONT_NAME)) {\n return FALSE;\n }\n \n IS_PREVIEWING = TRUE;\n return TRUE;\n}\n\nvoid CancelFontPreview(void) {\n IS_PREVIEWING = FALSE;\n PREVIEW_FONT_NAME[0] = '\\0';\n PREVIEW_INTERNAL_NAME[0] = '\\0';\n}\n\nvoid ApplyFontPreview(void) {\n // Check if there is a valid preview font\n if (!IS_PREVIEWING || strlen(PREVIEW_FONT_NAME) == 0) return;\n \n // Update current font\n strncpy(FONT_FILE_NAME, PREVIEW_FONT_NAME, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n strncpy(FONT_INTERNAL_NAME, PREVIEW_INTERNAL_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n \n // Save to configuration file and cancel preview state\n WriteConfigFont(FONT_FILE_NAME);\n CancelFontPreview();\n}\n\nBOOL SwitchFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Load new font\n if (!LoadFontByName(hInstance, fontName)) {\n return FALSE;\n }\n \n // Update font name\n strncpy(FONT_FILE_NAME, fontName, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n // Update internal font name (remove .ttf extension)\n size_t name_len = strlen(FONT_FILE_NAME);\n if (name_len > 4 && strcmp(FONT_FILE_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Write to configuration file\n WriteConfigFont(FONT_FILE_NAME);\n return TRUE;\n}"], ["/Catime/src/dialog_language.c", "/**\n * @file dialog_language.c\n * @brief Dialog multi-language support module implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \"../include/dialog_language.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\ntypedef struct {\n int dialogID;\n wchar_t* titleKey;\n} DialogTitleEntry;\n\ntypedef struct {\n int dialogID;\n int controlID;\n wchar_t* textKey;\n wchar_t* fallbackText;\n} SpecialControlEntry;\n\ntypedef struct {\n HWND hwndDlg;\n int dialogID;\n} EnumChildWindowsData;\n\nstatic DialogTitleEntry g_dialogTitles[] = {\n {IDD_ABOUT_DIALOG, L\"About\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, L\"Notification Settings\"},\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, L\"Set Pomodoro Loop Count\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, L\"Set Pomodoro Time Combination\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, L\"Set Pomodoro Time\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, L\"Countdown Presets\"},\n {CLOCK_IDD_WEBSITE_DIALOG, L\"Open Website\"},\n {CLOCK_IDD_DIALOG1, L\"Set Countdown\"},\n {IDD_NO_UPDATE_DIALOG, L\"Update Check\"},\n {IDD_UPDATE_DIALOG, L\"Update Available\"}\n};\n\nstatic SpecialControlEntry g_specialControls[] = {\n {IDD_ABOUT_DIALOG, IDC_ABOUT_TITLE, L\"关于\", L\"About\"},\n {IDD_ABOUT_DIALOG, IDC_VERSION_TEXT, L\"Version: %hs\", L\"Version: %hs\"},\n {IDD_ABOUT_DIALOG, IDC_BUILD_DATE, L\"构建日期:\", L\"Build Date:\"},\n {IDD_ABOUT_DIALOG, IDC_COPYRIGHT, L\"COPYRIGHT_TEXT\", L\"COPYRIGHT_TEXT\"},\n {IDD_ABOUT_DIALOG, IDC_CREDITS, L\"鸣谢\", L\"Credits\"},\n\n {IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT, L\"NoUpdateRequired\", L\"You are already using the latest version!\"},\n\n {IDD_UPDATE_DIALOG, IDC_UPDATE_TEXT, L\"CurrentVersion: %s\\nNewVersion: %s\", L\"Current Version: %s\\nNew Version: %s\"},\n {IDD_UPDATE_DIALOG, IDC_UPDATE_EXIT_TEXT, L\"The application will exit now\", L\"The application will exit now\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_CONTENT_GROUP, L\"Notification Content\", L\"Notification Content\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL1, L\"Countdown timeout message:\", L\"Countdown timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL2, L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL3, L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_DISPLAY_GROUP, L\"Notification Display\", L\"Notification Display\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TIME_LABEL, L\"Notification display time:\", L\"Notification display time:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_LABEL, L\"Maximum notification opacity (1-100%):\", L\"Maximum notification opacity (1-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_DISABLE_NOTIFICATION_CHECK, L\"Disable notifications\", L\"Disable notifications\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_METHOD_GROUP, L\"Notification Method\", L\"Notification Method\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_CATIME, L\"Catime notification window\", L\"Catime notification window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_OS, L\"System notification\", L\"System notification\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, L\"System modal window\", L\"System modal window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_SOUND_LABEL, L\"Sound (supports .mp3/.wav/.flac):\", L\"Sound (supports .mp3/.wav/.flac):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_LABEL, L\"Volume (0-100%):\", L\"Volume (0-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_TEXT, L\"100%\", L\"100%\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_TEXT, L\"100%\", L\"100%\"},\n\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_STATIC,\n L\"25=25 minutes\\\\n25h=25 hours\\\\n25s=25 seconds\\\\n25 30=25 minutes 30 seconds\\\\n25 30m=25 hours 30 minutes\\\\n1 30 20=1 hour 30 minutes 20 seconds\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\"},\n\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter pomodoro time sequence, separated by spaces:\\\\n\\\\n25m = 25 minutes\\\\n30s = 30 seconds\\\\n1h30m = 1 hour 30 minutes\\\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\",\n L\"Enter pomodoro time sequence, separated by spaces:\\n\\n25m = 25 minutes\\n30s = 30 seconds\\n1h30m = 1 hour 30 minutes\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\"},\n\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter the website URL to open when the countdown ends:\\\\nExample: https://github.com/vladelaina/Catime\",\n L\"Enter the website URL to open when the countdown ends:\\nExample: https://github.com/vladelaina/Catime\"},\n\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_STATIC,\n L\"CountdownPresetDialogStaticText\",\n L\"Enter numbers (minutes), separated by spaces\\n\\n25 10 5\\n\\nThis will create options for 25 minutes, 10 minutes, and 5 minutes\"},\n\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_STATIC,\n L\"CountdownDialogStaticText\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\\n17 20t=Countdown to 17:20\\n9 9 9t=Countdown to 09:09:09\"}\n};\n\nstatic SpecialControlEntry g_specialButtons[] = {\n {IDD_UPDATE_DIALOG, IDYES, L\"Yes\", L\"Yes\"},\n {IDD_UPDATE_DIALOG, IDNO, L\"No\", L\"No\"},\n {IDD_UPDATE_DIALOG, IDOK, L\"OK\", L\"OK\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_TEST_SOUND_BUTTON, L\"Test\", L\"Test\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_OPEN_SOUND_DIR_BUTTON, L\"Audio folder\", L\"Audio folder\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDOK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDCANCEL, L\"Cancel\", L\"Cancel\"},\n\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"}\n};\n\n#define DIALOG_TITLES_COUNT (sizeof(g_dialogTitles) / sizeof(g_dialogTitles[0]))\n#define SPECIAL_CONTROLS_COUNT (sizeof(g_specialControls) / sizeof(g_specialControls[0]))\n#define SPECIAL_BUTTONS_COUNT (sizeof(g_specialButtons) / sizeof(g_specialButtons[0]))\n\n/**\n * @brief Find localized text for special controls\n */\nstatic const wchar_t* FindSpecialControlText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_CONTROLS_COUNT; i++) {\n if (g_specialControls[i].dialogID == dialogID &&\n g_specialControls[i].controlID == controlID) {\n const wchar_t* localizedText = GetLocalizedString(NULL, g_specialControls[i].textKey);\n if (localizedText) {\n return localizedText;\n } else {\n return g_specialControls[i].fallbackText;\n }\n }\n }\n return NULL;\n}\n\n/**\n * @brief Find localized text for special buttons\n */\nstatic const wchar_t* FindSpecialButtonText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_BUTTONS_COUNT; i++) {\n if (g_specialButtons[i].dialogID == dialogID &&\n g_specialButtons[i].controlID == controlID) {\n return GetLocalizedString(NULL, g_specialButtons[i].textKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get localized text for dialog title\n */\nstatic const wchar_t* GetDialogTitleText(int dialogID) {\n for (int i = 0; i < DIALOG_TITLES_COUNT; i++) {\n if (g_dialogTitles[i].dialogID == dialogID) {\n return GetLocalizedString(NULL, g_dialogTitles[i].titleKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get original text of a control for translation lookup\n */\nstatic BOOL GetControlOriginalText(HWND hwndCtl, wchar_t* buffer, int bufferSize) {\n wchar_t className[256];\n GetClassNameW(hwndCtl, className, 256);\n\n if (wcscmp(className, L\"Button\") == 0 ||\n wcscmp(className, L\"Static\") == 0 ||\n wcscmp(className, L\"ComboBox\") == 0 ||\n wcscmp(className, L\"Edit\") == 0) {\n return GetWindowTextW(hwndCtl, buffer, bufferSize) > 0;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Process special control text settings, such as line breaks\n */\nstatic BOOL ProcessSpecialControlText(HWND hwndCtl, const wchar_t* localizedText, int dialogID, int controlID) {\n if ((dialogID == CLOCK_IDD_POMODORO_COMBO_DIALOG ||\n dialogID == CLOCK_IDD_POMODORO_TIME_DIALOG ||\n dialogID == CLOCK_IDD_WEBSITE_DIALOG ||\n dialogID == CLOCK_IDD_SHORTCUT_DIALOG ||\n dialogID == CLOCK_IDD_DIALOG1) &&\n controlID == CLOCK_IDC_STATIC) {\n wchar_t processedText[1024];\n const wchar_t* src = localizedText;\n wchar_t* dst = processedText;\n\n while (*src) {\n if (src[0] == L'\\\\' && src[1] == L'n') {\n *dst++ = L'\\n';\n src += 2;\n }\n else if (src[0] == L'\\n') {\n *dst++ = L'\\n';\n src++;\n }\n else {\n *dst++ = *src++;\n }\n }\n *dst = L'\\0';\n\n SetWindowTextW(hwndCtl, processedText);\n return TRUE;\n }\n\n if (controlID == IDC_VERSION_TEXT && dialogID == IDD_ABOUT_DIALOG) {\n wchar_t versionText[256];\n const wchar_t* localizedVersionFormat = GetLocalizedString(NULL, L\"Version: %hs\");\n if (localizedVersionFormat) {\n StringCbPrintfW(versionText, sizeof(versionText), localizedVersionFormat, CATIME_VERSION);\n } else {\n StringCbPrintfW(versionText, sizeof(versionText), localizedText, CATIME_VERSION);\n }\n SetWindowTextW(hwndCtl, versionText);\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Dialog child window enumeration callback function\n */\nstatic BOOL CALLBACK EnumChildProc(HWND hwndCtl, LPARAM lParam) {\n EnumChildWindowsData* data = (EnumChildWindowsData*)lParam;\n HWND hwndDlg = data->hwndDlg;\n int dialogID = data->dialogID;\n\n int controlID = GetDlgCtrlID(hwndCtl);\n if (controlID == 0) {\n return TRUE;\n }\n\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n if (ProcessSpecialControlText(hwndCtl, specialText, dialogID, controlID)) {\n return TRUE;\n }\n SetWindowTextW(hwndCtl, specialText);\n return TRUE;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n SetWindowTextW(hwndCtl, buttonText);\n return TRUE;\n }\n\n wchar_t originalText[512] = {0};\n if (GetControlOriginalText(hwndCtl, originalText, 512) && originalText[0] != L'\\0') {\n const wchar_t* localizedText = GetLocalizedString(NULL, originalText);\n if (localizedText && wcscmp(localizedText, originalText) != 0) {\n SetWindowTextW(hwndCtl, localizedText);\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Initialize dialog multi-language support\n */\nBOOL InitDialogLanguageSupport(void) {\n return TRUE;\n}\n\n/**\n * @brief Apply multi-language support to dialog\n */\nBOOL ApplyDialogLanguage(HWND hwndDlg, int dialogID) {\n if (!hwndDlg) return FALSE;\n\n const wchar_t* titleText = GetDialogTitleText(dialogID);\n if (titleText) {\n SetWindowTextW(hwndDlg, titleText);\n }\n\n EnumChildWindowsData data = {\n .hwndDlg = hwndDlg,\n .dialogID = dialogID\n };\n\n EnumChildWindows(hwndDlg, EnumChildProc, (LPARAM)&data);\n\n return TRUE;\n}\n\n/**\n * @brief Get localized text for dialog element\n */\nconst wchar_t* GetDialogLocalizedString(int dialogID, int controlID) {\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n return specialText;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n return buttonText;\n }\n\n if (controlID == -1) {\n return GetDialogTitleText(dialogID);\n }\n\n return NULL;\n}"], ["/Catime/src/audio_player.c", "/**\n * @file audio_player.c\n * @brief Audio playback functionality handler\n */\n\n#include \n#include \n#include \n#include \"../libs/miniaudio/miniaudio.h\"\n\n#include \"config.h\"\n\nextern char NOTIFICATION_SOUND_FILE[MAX_PATH];\nextern int NOTIFICATION_SOUND_VOLUME;\n\ntypedef void (*AudioPlaybackCompleteCallback)(HWND hwnd);\n\nstatic ma_engine g_audioEngine;\nstatic ma_sound g_sound;\nstatic ma_bool32 g_engineInitialized = MA_FALSE;\nstatic ma_bool32 g_soundInitialized = MA_FALSE;\n\nstatic AudioPlaybackCompleteCallback g_audioCompleteCallback = NULL;\nstatic HWND g_audioCallbackHwnd = NULL;\nstatic UINT_PTR g_audioTimerId = 0;\n\nstatic ma_bool32 g_isPlaying = MA_FALSE;\nstatic ma_bool32 g_isPaused = MA_FALSE;\n\nstatic void CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime);\n\n/**\n * @brief Initialize audio engine\n */\nstatic BOOL InitializeAudioEngine() {\n if (g_engineInitialized) {\n return TRUE;\n }\n\n ma_result result = ma_engine_init(NULL, &g_audioEngine);\n if (result != MA_SUCCESS) {\n return FALSE;\n }\n\n g_engineInitialized = MA_TRUE;\n return TRUE;\n}\n\n/**\n * @brief Clean up audio engine resources\n */\nstatic void UninitializeAudioEngine() {\n if (g_engineInitialized) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n ma_engine_uninit(&g_audioEngine);\n g_engineInitialized = MA_FALSE;\n }\n}\n\n/**\n * @brief Check if a file exists\n */\nstatic BOOL FileExists(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2);\n\n DWORD dwAttrib = GetFileAttributesW(wFilePath);\n return (dwAttrib != INVALID_FILE_ATTRIBUTES &&\n !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));\n}\n\n/**\n * @brief Show error message dialog\n */\nstatic void ShowErrorMessage(HWND hwnd, const wchar_t* errorMsg) {\n MessageBoxW(hwnd, errorMsg, L\"Audio Playback Error\", MB_ICONERROR | MB_OK);\n}\n\n/**\n * @brief Timer callback to check if audio playback is complete\n */\nstatic void CALLBACK CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n if (g_engineInitialized && g_soundInitialized) {\n if (!ma_sound_is_playing(&g_sound) && !g_isPaused) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n } else {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n}\n\n/**\n * @brief System beep playback completion callback timer function\n */\nstatic void CALLBACK SystemBeepDoneCallback(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n}\n\n/**\n * @brief Set audio playback volume\n * @param volume Volume percentage (0-100)\n */\nvoid SetAudioVolume(int volume) {\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n\n if (g_engineInitialized) {\n float volFloat = (float)volume / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volFloat);\n\n if (g_soundInitialized && g_isPlaying) {\n ma_sound_set_volume(&g_sound, volFloat);\n }\n }\n}\n\n/**\n * @brief Play audio file using miniaudio\n */\nstatic BOOL PlayAudioWithMiniaudio(HWND hwnd, const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (!g_engineInitialized) {\n if (!InitializeAudioEngine()) {\n return FALSE;\n }\n }\n\n float volume = (float)NOTIFICATION_SOUND_VOLUME / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volume);\n\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n if (MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (UTF-8->Unicode): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n wchar_t shortPath[MAX_PATH] = {0};\n DWORD shortPathLen = GetShortPathNameW(wFilePath, shortPath, MAX_PATH);\n if (shortPathLen == 0 || shortPathLen >= MAX_PATH) {\n DWORD error = GetLastError();\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Failed to get short path: %ls\\nError code: %lu\", wFilePath, error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n char asciiPath[MAX_PATH] = {0};\n if (WideCharToMultiByte(CP_ACP, 0, shortPath, -1, asciiPath, MAX_PATH, NULL, NULL) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (Short Path->ASCII): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n return FALSE;\n }\n\n ma_result result = ma_sound_init_from_file(&g_audioEngine, asciiPath, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n char utf8Path[MAX_PATH * 4] = {0};\n WideCharToMultiByte(CP_UTF8, 0, wFilePath, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n\n result = ma_sound_init_from_file(&g_audioEngine, utf8Path, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Unable to load audio file: %ls\\nError code: %d\", wFilePath, result);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n }\n\n g_soundInitialized = MA_TRUE;\n\n if (ma_sound_start(&g_sound) != MA_SUCCESS) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n ShowErrorMessage(hwnd, L\"Cannot start audio playback\");\n return FALSE;\n }\n\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1001, 500, (TIMERPROC)CheckAudioPlaybackComplete);\n\n return TRUE;\n}\n\n/**\n * @brief Validate if file path is legal\n */\nstatic BOOL IsValidFilePath(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (strchr(filePath, '=') != NULL) return FALSE;\n\n if (strlen(filePath) >= MAX_PATH) return FALSE;\n\n return TRUE;\n}\n\n/**\n * @brief Clean up audio resources\n */\nvoid CleanupAudioResources(void) {\n PlaySound(NULL, NULL, SND_PURGE);\n\n if (g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n if (g_audioTimerId != 0 && g_audioCallbackHwnd != NULL) {\n KillTimer(g_audioCallbackHwnd, g_audioTimerId);\n g_audioTimerId = 0;\n }\n\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n}\n\n/**\n * @brief Set audio playback completion callback function\n */\nvoid SetAudioPlaybackCompleteCallback(HWND hwnd, AudioPlaybackCompleteCallback callback) {\n g_audioCallbackHwnd = hwnd;\n g_audioCompleteCallback = callback;\n}\n\n/**\n * @brief Play notification audio\n */\nBOOL PlayNotificationSound(HWND hwnd) {\n CleanupAudioResources();\n\n g_audioCallbackHwnd = hwnd;\n\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (!IsValidFilePath(NOTIFICATION_SOUND_FILE)) {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Invalid audio file path:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (FileExists(NOTIFICATION_SOUND_FILE)) {\n if (PlayAudioWithMiniaudio(hwnd, NOTIFICATION_SOUND_FILE)) {\n return TRUE;\n }\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n } else {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Cannot find the configured audio file:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Pause currently playing notification audio\n */\nBOOL PauseNotificationSound(void) {\n if (g_isPlaying && !g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n g_isPaused = MA_TRUE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Resume previously paused notification audio\n */\nBOOL ResumeNotificationSound(void) {\n if (g_isPlaying && g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_start(&g_sound);\n g_isPaused = MA_FALSE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Stop playing notification audio\n */\nvoid StopNotificationSound(void) {\n CleanupAudioResources();\n}"], ["/Catime/src/shortcut_checker.c", "/**\n * @file shortcut_checker.c\n * @brief Implementation of desktop shortcut detection and creation\n *\n * Detects if the program is installed from the App Store or WinGet,\n * and creates a desktop shortcut when necessary.\n */\n\n#include \"../include/shortcut_checker.h\"\n#include \"../include/config.h\"\n#include \"../include/log.h\" // Include log header\n#include // For printf debug output\n#include \n#include \n#include \n#include \n#include \n#include \n\n// Import required COM interfaces\n#include \n\n// We don't need to manually define IID_IShellLinkA, it's already defined in system headers\n\n/**\n * @brief Check if a string starts with a specified prefix\n * \n * @param str The string to check\n * @param prefix The prefix string\n * @return bool true if the string starts with the specified prefix, false otherwise\n */\nstatic bool StartsWith(const char* str, const char* prefix) {\n size_t prefix_len = strlen(prefix);\n size_t str_len = strlen(str);\n \n if (str_len < prefix_len) {\n return false;\n }\n \n return strncmp(str, prefix, prefix_len) == 0;\n}\n\n/**\n * @brief Check if a string contains a specified substring\n * \n * @param str The string to check\n * @param substring The substring\n * @return bool true if the string contains the specified substring, false otherwise\n */\nstatic bool Contains(const char* str, const char* substring) {\n return strstr(str, substring) != NULL;\n}\n\n/**\n * @brief Check if the program is installed from the App Store or WinGet\n * \n * @param exe_path Buffer to output the program path\n * @param path_size Buffer size\n * @return bool true if installed from the App Store or WinGet, false otherwise\n */\nstatic bool IsStoreOrWingetInstall(char* exe_path, size_t path_size) {\n // Get program path\n if (GetModuleFileNameA(NULL, exe_path, path_size) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n return false;\n }\n \n LOG_DEBUG(\"Checking program path: %s\", exe_path);\n \n // Check if it's an App Store installation path (starts with C:\\Program Files\\WindowsApps)\n if (StartsWith(exe_path, \"C:\\\\Program Files\\\\WindowsApps\")) {\n LOG_DEBUG(\"Detected App Store installation path\");\n return true;\n }\n \n // Check if it's a WinGet installation path\n // 1. Regular path containing \\AppData\\Local\\Microsoft\\WinGet\\Packages\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\WinGet\\\\Packages\")) {\n LOG_DEBUG(\"Detected WinGet installation path (regular)\");\n return true;\n }\n \n // 2. Possible custom WinGet installation path (if in C:\\Users\\username\\AppData\\Local\\Microsoft\\*)\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\\") && Contains(exe_path, \"WinGet\")) {\n LOG_DEBUG(\"Detected possible WinGet installation path (custom)\");\n return true;\n }\n \n // Force test: When the path contains specific strings, consider it a path that needs to create shortcuts\n // This test path matches the installation path seen in user logs\n if (Contains(exe_path, \"\\\\WinGet\\\\catime.exe\")) {\n LOG_DEBUG(\"Detected specific WinGet installation path\");\n return true;\n }\n \n LOG_DEBUG(\"Not a Store or WinGet installation path\");\n return false;\n}\n\n/**\n * @brief Check if the desktop already has a shortcut and if the shortcut points to the current program\n * \n * @param exe_path Program path\n * @param shortcut_path_out If a shortcut is found, output the shortcut path\n * @param shortcut_path_size Shortcut path buffer size\n * @param target_path_out If a shortcut is found, output the shortcut target path\n * @param target_path_size Target path buffer size\n * @return int 0=shortcut not found, 1=shortcut found and points to current program, 2=shortcut found but points to another path\n */\nstatic int CheckShortcutTarget(const char* exe_path, char* shortcut_path_out, size_t shortcut_path_size, \n char* target_path_out, size_t target_path_size) {\n char desktop_path[MAX_PATH];\n char public_desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char link_target[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n WIN32_FIND_DATAA find_data;\n int result = 0;\n \n // Get user desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n LOG_DEBUG(\"User desktop path: %s\", desktop_path);\n \n // Get public desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_COMMON_DESKTOPDIRECTORY, NULL, 0, public_desktop_path);\n if (FAILED(hr)) {\n LOG_WARNING(\"Failed to get public desktop path, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_DEBUG(\"Public desktop path: %s\", public_desktop_path);\n }\n \n // First check user desktop - build complete shortcut path (Catime.lnk)\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n LOG_DEBUG(\"Checking user desktop shortcut: %s\", shortcut_path);\n \n // Check if the user desktop shortcut file exists\n bool file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n \n // If not found on user desktop, check public desktop\n if (!file_exists && SUCCEEDED(hr)) {\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", public_desktop_path);\n LOG_DEBUG(\"Checking public desktop shortcut: %s\", shortcut_path);\n \n file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n }\n \n // If no shortcut file is found, return 0 directly\n if (!file_exists) {\n LOG_DEBUG(\"No shortcut files found\");\n return 0;\n }\n \n // Save the found shortcut path to the output parameter\n if (shortcut_path_out && shortcut_path_size > 0) {\n strncpy(shortcut_path_out, shortcut_path, shortcut_path_size);\n shortcut_path_out[shortcut_path_size - 1] = '\\0';\n }\n \n // Found shortcut file, get its target\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Convert to wide character\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_ACP, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Load shortcut\n hr = ppf->lpVtbl->Load(ppf, wide_path, STGM_READ);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to load shortcut, hr=0x%08X\", (unsigned int)hr);\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Get shortcut target path\n hr = psl->lpVtbl->GetPath(psl, link_target, MAX_PATH, &find_data, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get shortcut target path, hr=0x%08X\", (unsigned int)hr);\n result = 0;\n } else {\n LOG_DEBUG(\"Shortcut target path: %s\", link_target);\n LOG_DEBUG(\"Current program path: %s\", exe_path);\n \n // Save target path to output parameter\n if (target_path_out && target_path_size > 0) {\n strncpy(target_path_out, link_target, target_path_size);\n target_path_out[target_path_size - 1] = '\\0';\n }\n \n // Check if the shortcut points to the current program\n if (_stricmp(link_target, exe_path) == 0) {\n LOG_DEBUG(\"Shortcut points to current program\");\n result = 1;\n } else {\n LOG_DEBUG(\"Shortcut points to another path\");\n result = 2;\n }\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return result;\n}\n\n/**\n * @brief Create or update desktop shortcut\n * \n * @param exe_path Program path\n * @param existing_shortcut_path Existing shortcut path, create new one if NULL\n * @return bool true for successful creation/update, false for failure\n */\nstatic bool CreateOrUpdateDesktopShortcut(const char* exe_path, const char* existing_shortcut_path) {\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char icon_path[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n bool success = false;\n \n // If an existing shortcut path is provided, use it; otherwise create a new shortcut on the user's desktop\n if (existing_shortcut_path && *existing_shortcut_path) {\n LOG_INFO(\"Starting to update desktop shortcut: %s pointing to: %s\", existing_shortcut_path, exe_path);\n strcpy(shortcut_path, existing_shortcut_path);\n } else {\n LOG_INFO(\"Starting to create desktop shortcut, program path: %s\", exe_path);\n \n // Get desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n LOG_DEBUG(\"Desktop path: %s\", desktop_path);\n \n // Build complete shortcut path\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n }\n \n LOG_DEBUG(\"Shortcut path: %s\", shortcut_path);\n \n // Use program path as icon path\n strcpy(icon_path, exe_path);\n \n // Create IShellLink interface\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n \n // Set target path\n hr = psl->lpVtbl->SetPath(psl, exe_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set shortcut target path, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Set working directory (use the directory where the executable is located)\n char work_dir[MAX_PATH];\n strcpy(work_dir, exe_path);\n char* last_slash = strrchr(work_dir, '\\\\');\n if (last_slash) {\n *last_slash = '\\0';\n }\n LOG_DEBUG(\"Working directory: %s\", work_dir);\n \n hr = psl->lpVtbl->SetWorkingDirectory(psl, work_dir);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set working directory, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set icon\n hr = psl->lpVtbl->SetIconLocation(psl, icon_path, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set icon, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set description\n hr = psl->lpVtbl->SetDescription(psl, \"A very useful timer (Pomodoro Clock)\");\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set description, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set window style (normal window)\n psl->lpVtbl->SetShowCmd(psl, SW_SHOWNORMAL);\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Convert to wide characters\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Save shortcut\n hr = ppf->lpVtbl->Save(ppf, wide_path, TRUE);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to save shortcut, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_INFO(\"Desktop shortcut %s successful: %s\", existing_shortcut_path ? \"update\" : \"creation\", shortcut_path);\n success = true;\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return success;\n}\n\n/**\n * @brief Check and create desktop shortcut\n * \n * All installation types will check if the desktop shortcut exists and points to the current program.\n * If the shortcut already exists but points to another program, it will be updated to the current path.\n * But only versions installed from the Windows App Store or WinGet will create a new shortcut.\n * If SHORTCUT_CHECK_DONE=TRUE is marked in the configuration file, no new shortcut will be created even if the shortcut is deleted.\n * \n * @return int 0 means no need to create/update or create/update successful, 1 means failure\n */\nint CheckAndCreateShortcut(void) {\n char exe_path[MAX_PATH];\n char config_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char target_path[MAX_PATH];\n bool shortcut_check_done = false;\n bool isStoreInstall = false;\n \n // Initialize COM library, needed for creating shortcuts later\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM library initialization failed, hr=0x%08X\", (unsigned int)hr);\n return 1;\n }\n \n LOG_DEBUG(\"Starting shortcut check\");\n \n // Read the flag from the configuration file to determine if it has been checked\n GetConfigPath(config_path, MAX_PATH);\n shortcut_check_done = IsShortcutCheckDone();\n \n LOG_DEBUG(\"Configuration path: %s, already checked: %d\", config_path, shortcut_check_done);\n \n // Get current program path\n if (GetModuleFileNameA(NULL, exe_path, MAX_PATH) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n CoUninitialize();\n return 1;\n }\n LOG_DEBUG(\"Program path: %s\", exe_path);\n \n // Check if it's an App Store or WinGet installation (only affects the behavior of creating new shortcuts)\n isStoreInstall = IsStoreOrWingetInstall(exe_path, MAX_PATH);\n LOG_DEBUG(\"Is Store/WinGet installation: %d\", isStoreInstall);\n \n // Check if the shortcut exists and points to the current program\n // Return value: 0=does not exist, 1=exists and points to the current program, 2=exists but points to another path\n int shortcut_status = CheckShortcutTarget(exe_path, shortcut_path, MAX_PATH, target_path, MAX_PATH);\n \n if (shortcut_status == 0) {\n // Shortcut does not exist\n if (shortcut_check_done) {\n // If the configuration has already been marked as checked, don't create it even if there's no shortcut\n LOG_INFO(\"No shortcut found on desktop, but configuration marked as checked, not creating\");\n CoUninitialize();\n return 0;\n } else if (isStoreInstall) {\n // Only first-run Store or WinGet installations create shortcuts\n LOG_INFO(\"No shortcut found on desktop, first run of Store/WinGet installation, starting to create\");\n bool success = CreateOrUpdateDesktopShortcut(exe_path, NULL);\n \n // Mark as checked, regardless of whether creation was successful\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return success ? 0 : 1;\n } else {\n LOG_INFO(\"No shortcut found on desktop, not a Store/WinGet installation, not creating shortcut\");\n \n // Mark as checked\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return 0;\n }\n } else if (shortcut_status == 1) {\n // Shortcut exists and points to the current program, no action needed\n LOG_INFO(\"Desktop shortcut already exists and points to the current program\");\n \n // Mark as checked\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return 0;\n } else if (shortcut_status == 2) {\n // Shortcut exists but points to another program, any installation method will update it\n LOG_INFO(\"Desktop shortcut points to another path: %s, will update to: %s\", target_path, exe_path);\n bool success = CreateOrUpdateDesktopShortcut(exe_path, shortcut_path);\n \n // Mark as checked, regardless of whether the update was successful\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return success ? 0 : 1;\n }\n \n // Should not reach here\n LOG_ERROR(\"Unknown shortcut check status\");\n CoUninitialize();\n return 1;\n} "], ["/Catime/src/window_events.c", "/**\n * @file window_events.c\n * @brief Implementation of basic window event handling\n * \n * This file implements the basic event handling functionality for the application window,\n * including window creation, destruction, resizing, and position adjustment.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/tray.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/window_events.h\"\n\n/**\n * @brief Handle window creation event\n * @param hwnd Window handle\n * @return BOOL Processing result\n */\nBOOL HandleWindowCreate(HWND hwnd) {\n HWND hwndParent = GetParent(hwnd);\n if (hwndParent != NULL) {\n EnableWindow(hwndParent, TRUE);\n }\n \n // Load window settings\n LoadWindowSettings(hwnd);\n \n // Set click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // Ensure window is in topmost state\n SetWindowTopmost(hwnd, CLOCK_WINDOW_TOPMOST);\n \n return TRUE;\n}\n\n/**\n * @brief Handle window destruction event\n * @param hwnd Window handle\n */\nvoid HandleWindowDestroy(HWND hwnd) {\n SaveWindowSettings(hwnd); // Save window settings\n KillTimer(hwnd, 1);\n RemoveTrayIcon();\n \n // Clean up update check thread\n extern void CleanupUpdateThread(void);\n CleanupUpdateThread();\n \n PostQuitMessage(0);\n}\n\n/**\n * @brief Handle window reset event\n * @param hwnd Window handle\n */\nvoid HandleWindowReset(HWND hwnd) {\n // Unconditionally apply topmost setting from configuration\n // Regardless of the current CLOCK_WINDOW_TOPMOST value, force it to TRUE and apply\n CLOCK_WINDOW_TOPMOST = TRUE;\n SetWindowTopmost(hwnd, TRUE);\n WriteConfigTopmost(\"TRUE\");\n \n // Ensure window is always visible - solves the issue of timer not being visible after reset\n ShowWindow(hwnd, SW_SHOW);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowResize(HWND hwnd, int delta) {\n return HandleScaleWindow(hwnd, delta);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowMove(HWND hwnd) {\n return HandleDragWindow(hwnd);\n}\n"], ["/Catime/src/startup.c", "/**\n * @file startup.c\n * @brief Implementation of auto-start functionality\n * \n * This file implements the application's auto-start related functionality,\n * including checking if auto-start is enabled, creating and deleting auto-start shortcuts.\n */\n\n#include \"../include/startup.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/config.h\"\n#include \"../include/timer.h\"\n\n#ifndef CSIDL_STARTUP\n#define CSIDL_STARTUP 0x0007\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern int countup_elapsed_time;\nextern int CLOCK_DEFAULT_START_TIME;\nextern char CLOCK_STARTUP_MODE[20];\n/// @}\n\n/**\n * @brief Check if the application is set to auto-start at system boot\n * @return BOOL Returns TRUE if auto-start is enabled, otherwise FALSE\n */\nBOOL IsAutoStartEnabled(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n return GetFileAttributesW(startupPath) != INVALID_FILE_ATTRIBUTES;\n }\n return FALSE;\n}\n\n/**\n * @brief Create auto-start shortcut\n * @return BOOL Returns TRUE if creation was successful, otherwise FALSE\n */\nBOOL CreateShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n wchar_t exePath[MAX_PATH];\n IShellLinkW* pShellLink = NULL;\n IPersistFile* pPersistFile = NULL;\n BOOL success = FALSE;\n \n GetModuleFileNameW(NULL, exePath, MAX_PATH);\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n HRESULT hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkW, (void**)&pShellLink);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->SetPath(pShellLink, exePath);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->QueryInterface(pShellLink,\n &IID_IPersistFile,\n (void**)&pPersistFile);\n if (SUCCEEDED(hr)) {\n hr = pPersistFile->lpVtbl->Save(pPersistFile, startupPath, TRUE);\n if (SUCCEEDED(hr)) {\n success = TRUE;\n }\n pPersistFile->lpVtbl->Release(pPersistFile);\n }\n }\n pShellLink->lpVtbl->Release(pShellLink);\n }\n }\n \n return success;\n}\n\n/**\n * @brief Delete auto-start shortcut\n * @return BOOL Returns TRUE if deletion was successful, otherwise FALSE\n */\nBOOL RemoveShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n return DeleteFileW(startupPath);\n }\n return FALSE;\n}\n\n/**\n * @brief Update auto-start shortcut\n * \n * Check if auto-start is enabled, if so, delete the old shortcut and create a new one,\n * ensuring that the auto-start functionality works correctly even if the application location changes.\n * \n * @return BOOL Returns TRUE if update was successful, otherwise FALSE\n */\nBOOL UpdateStartupShortcut(void) {\n // If auto-start is already enabled\n if (IsAutoStartEnabled()) {\n // First delete the existing shortcut\n RemoveShortcut();\n // Create a new shortcut\n return CreateShortcut();\n }\n return TRUE; // Auto-start not enabled, considered successful\n}\n\n/**\n * @brief Apply startup mode settings\n * @param hwnd Window handle\n * \n * Initialize the application's display state according to the startup mode settings in the configuration file\n */\nvoid ApplyStartupMode(HWND hwnd) {\n // Read startup mode from configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", CLOCK_STARTUP_MODE);\n break;\n }\n }\n fclose(configFile);\n \n // Apply startup mode\n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n // Set to count-up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n // Set to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n // Set to no display mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n } else { // Default to countdown mode \"COUNTDOWN\"\n // Set to countdown mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n \n // Read default countdown time\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n \n // If countdown is set, start the timer\n if (CLOCK_TOTAL_TIME > 0) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n"], ["/Catime/src/color.c", "/**\n * @file color.c\n * @brief Color processing functionality implementation\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/color.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n\nPredefinedColor* COLOR_OPTIONS = NULL;\nsize_t COLOR_OPTIONS_COUNT = 0;\nchar PREVIEW_COLOR[10] = \"\";\nBOOL IS_COLOR_PREVIEWING = FALSE;\nchar CLOCK_TEXT_COLOR[10] = \"#FFFFFF\";\n\nvoid GetConfigPath(char* path, size_t size);\nvoid CreateDefaultConfig(const char* config_path);\nvoid ReadConfig(void);\nvoid WriteConfig(const char* config_path);\nvoid replaceBlackColor(const char* color, char* output, size_t output_size);\n\nstatic const CSSColor CSS_COLORS[] = {\n {\"white\", \"#FFFFFF\"},\n {\"black\", \"#000000\"},\n {\"red\", \"#FF0000\"},\n {\"lime\", \"#00FF00\"},\n {\"blue\", \"#0000FF\"},\n {\"yellow\", \"#FFFF00\"},\n {\"cyan\", \"#00FFFF\"},\n {\"magenta\", \"#FF00FF\"},\n {\"silver\", \"#C0C0C0\"},\n {\"gray\", \"#808080\"},\n {\"maroon\", \"#800000\"},\n {\"olive\", \"#808000\"},\n {\"green\", \"#008000\"},\n {\"purple\", \"#800080\"},\n {\"teal\", \"#008080\"},\n {\"navy\", \"#000080\"},\n {\"orange\", \"#FFA500\"},\n {\"pink\", \"#FFC0CB\"},\n {\"brown\", \"#A52A2A\"},\n {\"violet\", \"#EE82EE\"},\n {\"indigo\", \"#4B0082\"},\n {\"gold\", \"#FFD700\"},\n {\"coral\", \"#FF7F50\"},\n {\"salmon\", \"#FA8072\"},\n {\"khaki\", \"#F0E68C\"},\n {\"plum\", \"#DDA0DD\"},\n {\"azure\", \"#F0FFFF\"},\n {\"ivory\", \"#FFFFF0\"},\n {\"wheat\", \"#F5DEB3\"},\n {\"snow\", \"#FFFAFA\"}\n};\n\n#define CSS_COLORS_COUNT (sizeof(CSS_COLORS) / sizeof(CSS_COLORS[0]))\n\nstatic const char* DEFAULT_COLOR_OPTIONS[] = {\n \"#FFFFFF\",\n \"#F9DB91\",\n \"#F4CAE0\",\n \"#FFB6C1\",\n \"#A8E7DF\",\n \"#A3CFB3\",\n \"#92CBFC\",\n \"#BDA5E7\",\n \"#9370DB\",\n \"#8C92CF\",\n \"#72A9A5\",\n \"#EB99A7\",\n \"#EB96BD\",\n \"#FFAE8B\",\n \"#FF7F50\",\n \"#CA6174\"\n};\n\n#define DEFAULT_COLOR_OPTIONS_COUNT (sizeof(DEFAULT_COLOR_OPTIONS) / sizeof(DEFAULT_COLOR_OPTIONS[0]))\n\nWNDPROC g_OldEditProc;\n\n#include \n\nCOLORREF ShowColorDialog(HWND hwnd) {\n CHOOSECOLOR cc = {0};\n static COLORREF acrCustClr[16] = {0};\n static DWORD rgbCurrent;\n\n int r, g, b;\n if (CLOCK_TEXT_COLOR[0] == '#') {\n sscanf(CLOCK_TEXT_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n } else {\n sscanf(CLOCK_TEXT_COLOR, \"%d,%d,%d\", &r, &g, &b);\n }\n rgbCurrent = RGB(r, g, b);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT && i < 16; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n if (hexColor[0] == '#') {\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n acrCustClr[i] = RGB(r, g, b);\n }\n }\n\n cc.lStructSize = sizeof(CHOOSECOLOR);\n cc.hwndOwner = hwnd;\n cc.lpCustColors = acrCustClr;\n cc.rgbResult = rgbCurrent;\n cc.Flags = CC_FULLOPEN | CC_RGBINIT | CC_ENABLEHOOK;\n cc.lpfnHook = ColorDialogHookProc;\n\n if (ChooseColor(&cc)) {\n COLORREF finalColor;\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n int r, g, b;\n sscanf(PREVIEW_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n finalColor = RGB(r, g, b);\n } else {\n finalColor = cc.rgbResult;\n }\n\n char tempColor[10];\n snprintf(tempColor, sizeof(tempColor), \"#%02X%02X%02X\",\n GetRValue(finalColor),\n GetGValue(finalColor),\n GetBValue(finalColor));\n\n char finalColorStr[10];\n replaceBlackColor(tempColor, finalColorStr, sizeof(finalColorStr));\n\n strncpy(CLOCK_TEXT_COLOR, finalColorStr, sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n\n IS_COLOR_PREVIEWING = FALSE;\n\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return finalColor;\n }\n\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return (COLORREF)-1;\n}\n\nUINT_PTR CALLBACK ColorDialogHookProc(HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HWND hwndParent;\n static CHOOSECOLOR* pcc;\n static BOOL isColorLocked = FALSE;\n static DWORD rgbCurrent;\n static COLORREF lastCustomColors[16] = {0};\n\n switch (msg) {\n case WM_INITDIALOG:\n pcc = (CHOOSECOLOR*)lParam;\n hwndParent = pcc->hwndOwner;\n rgbCurrent = pcc->rgbResult;\n isColorLocked = FALSE;\n \n for (int i = 0; i < 16; i++) {\n lastCustomColors[i] = pcc->lpCustColors[i];\n }\n return TRUE;\n\n case WM_LBUTTONDOWN:\n case WM_RBUTTONDOWN:\n isColorLocked = !isColorLocked;\n \n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n \n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n \n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n \n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n\n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_MOUSEMOVE:\n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n\n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n\n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n\n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n \n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n \n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_COMMAND:\n if (HIWORD(wParam) == BN_CLICKED) {\n switch (LOWORD(wParam)) {\n case IDOK: {\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n } else {\n snprintf(PREVIEW_COLOR, sizeof(PREVIEW_COLOR), \"#%02X%02X%02X\",\n GetRValue(pcc->rgbResult),\n GetGValue(pcc->rgbResult),\n GetBValue(pcc->rgbResult));\n }\n break;\n }\n \n case IDCANCEL:\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n break;\n }\n }\n break;\n\n case WM_CTLCOLORBTN:\n case WM_CTLCOLOREDIT:\n case WM_CTLCOLORSTATIC:\n if (pcc) {\n BOOL colorsChanged = FALSE;\n for (int i = 0; i < 16; i++) {\n if (lastCustomColors[i] != pcc->lpCustColors[i]) {\n colorsChanged = TRUE;\n lastCustomColors[i] = pcc->lpCustColors[i];\n \n char colorStr[20];\n snprintf(colorStr, sizeof(colorStr), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n \n }\n }\n \n if (colorsChanged) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n ClearColorOptions();\n \n for (int i = 0; i < 16; i++) {\n if (pcc->lpCustColors[i] != 0) {\n char hexColor[10];\n snprintf(hexColor, sizeof(hexColor), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n AddColorOption(hexColor);\n }\n }\n \n WriteConfig(config_path);\n }\n }\n break;\n }\n return 0;\n}\n\nvoid InitializeDefaultLanguage(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n ClearColorOptions();\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n CreateDefaultConfig(config_path);\n file = fopen(config_path, \"r\");\n }\n\n if (file) {\n char line[1024];\n BOOL found_colors = FALSE;\n\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"COLOR_OPTIONS=\", 13) == 0) {\n ClearColorOptions();\n\n char* colors = line + 13;\n while (*colors == '=' || *colors == ' ') {\n colors++;\n }\n\n char* newline = strchr(colors, '\\n');\n if (newline) *newline = '\\0';\n\n char* token = strtok(colors, \",\");\n while (token) {\n while (*token == ' ') token++;\n char* end = token + strlen(token) - 1;\n while (end > token && *end == ' ') {\n *end = '\\0';\n end--;\n }\n\n if (*token) {\n if (token[0] != '#') {\n char colorWithHash[10];\n snprintf(colorWithHash, sizeof(colorWithHash), \"#%s\", token);\n AddColorOption(colorWithHash);\n } else {\n AddColorOption(token);\n }\n }\n token = strtok(NULL, \",\");\n }\n found_colors = TRUE;\n break;\n }\n }\n fclose(file);\n\n if (!found_colors || COLOR_OPTIONS_COUNT == 0) {\n for (size_t i = 0; i < DEFAULT_COLOR_OPTIONS_COUNT; i++) {\n AddColorOption(DEFAULT_COLOR_OPTIONS[i]);\n }\n }\n }\n}\n\n/**\n * @brief Add color option\n */\nvoid AddColorOption(const char* hexColor) {\n if (!hexColor || !*hexColor) {\n return;\n }\n\n char normalizedColor[10];\n const char* hex = (hexColor[0] == '#') ? hexColor + 1 : hexColor;\n\n size_t len = strlen(hex);\n if (len != 6) {\n return;\n }\n\n for (int i = 0; i < 6; i++) {\n if (!isxdigit((unsigned char)hex[i])) {\n return;\n }\n }\n\n unsigned int color;\n if (sscanf(hex, \"%x\", &color) != 1) {\n return;\n }\n\n snprintf(normalizedColor, sizeof(normalizedColor), \"#%06X\", color);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (strcasecmp(normalizedColor, COLOR_OPTIONS[i].hexColor) == 0) {\n return;\n }\n }\n\n PredefinedColor* newArray = realloc(COLOR_OPTIONS,\n (COLOR_OPTIONS_COUNT + 1) * sizeof(PredefinedColor));\n if (newArray) {\n COLOR_OPTIONS = newArray;\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = _strdup(normalizedColor);\n COLOR_OPTIONS_COUNT++;\n }\n}\n\n/**\n * @brief Clear all color options\n */\nvoid ClearColorOptions(void) {\n if (COLOR_OPTIONS) {\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n free((void*)COLOR_OPTIONS[i].hexColor);\n }\n free(COLOR_OPTIONS);\n COLOR_OPTIONS = NULL;\n COLOR_OPTIONS_COUNT = 0;\n }\n}\n\n/**\n * @brief Write color to configuration file\n */\nvoid WriteConfigColor(const char* color_input) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"CLOCK_TEXT_COLOR=\", 17) == 0) {\n strcat(new_config, \"CLOCK_TEXT_COLOR=\");\n strcat(new_config, color_input);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n ReadConfig();\n}\n\n/**\n * @brief Normalize color format\n */\nvoid normalizeColor(const char* input, char* output, size_t output_size) {\n while (isspace(*input)) input++;\n\n char color[32];\n strncpy(color, input, sizeof(color)-1);\n color[sizeof(color)-1] = '\\0';\n for (char* p = color; *p; p++) {\n *p = tolower(*p);\n }\n\n for (size_t i = 0; i < CSS_COLORS_COUNT; i++) {\n if (strcmp(color, CSS_COLORS[i].name) == 0) {\n strncpy(output, CSS_COLORS[i].hex, output_size);\n return;\n }\n }\n\n char cleaned[32] = {0};\n int j = 0;\n for (int i = 0; color[i]; i++) {\n if (!isspace(color[i]) && color[i] != ',' && color[i] != '(' && color[i] != ')') {\n cleaned[j++] = color[i];\n }\n }\n cleaned[j] = '\\0';\n\n if (cleaned[0] == '#') {\n memmove(cleaned, cleaned + 1, strlen(cleaned));\n }\n\n if (strlen(cleaned) == 3) {\n snprintf(output, output_size, \"#%c%c%c%c%c%c\",\n cleaned[0], cleaned[0], cleaned[1], cleaned[1], cleaned[2], cleaned[2]);\n return;\n }\n\n if (strlen(cleaned) == 6 && strspn(cleaned, \"0123456789abcdefABCDEF\") == 6) {\n snprintf(output, output_size, \"#%s\", cleaned);\n return;\n }\n\n int r = -1, g = -1, b = -1;\n char* rgb_str = color;\n\n if (strncmp(rgb_str, \"rgb\", 3) == 0) {\n rgb_str += 3;\n while (*rgb_str && (*rgb_str == '(' || isspace(*rgb_str))) rgb_str++;\n }\n\n if (sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d %d %d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d|%d|%d\", &r, &g, &b) == 3) {\n\n if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) {\n snprintf(output, output_size, \"#%02X%02X%02X\", r, g, b);\n return;\n }\n }\n\n strncpy(output, input, output_size);\n}\n\n/**\n * @brief Check if color is valid\n */\nBOOL isValidColor(const char* input) {\n if (!input || !*input) return FALSE;\n\n char normalized[32];\n normalizeColor(input, normalized, sizeof(normalized));\n\n if (normalized[0] != '#' || strlen(normalized) != 7) {\n return FALSE;\n }\n\n for (int i = 1; i < 7; i++) {\n if (!isxdigit((unsigned char)normalized[i])) {\n return FALSE;\n }\n }\n\n int r, g, b;\n if (sscanf(normalized + 1, \"%02x%02x%02x\", &r, &g, &b) == 3) {\n return (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255);\n }\n\n return FALSE;\n}\n\n/**\n * @brief Color edit box subclass procedure\n */\nLRESULT CALLBACK ColorEditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_KEYDOWN:\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n case WM_COMMAND:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n return 0;\n }\n }\n break;\n\n case WM_CHAR:\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n }\n\n return result;\n\n case WM_PASTE:\n case WM_CUT: {\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n }\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n\n return result;\n }\n }\n\n return CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Color settings dialog procedure\n */\nINT_PTR CALLBACK ColorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit) {\n g_OldEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC,\n (LONG_PTR)ColorEditSubclassProc);\n\n if (CLOCK_TEXT_COLOR[0] != '\\0') {\n SetWindowTextA(hwndEdit, CLOCK_TEXT_COLOR);\n }\n }\n return TRUE;\n }\n\n case WM_COMMAND: {\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n char color[32];\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, color, sizeof(color));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; color[i]; i++) {\n if (!isspace((unsigned char)color[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (color[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n\n if (isValidColor(color)) {\n char normalized_color[10];\n normalizeColor(color, normalized_color, sizeof(normalized_color));\n strncpy(CLOCK_TEXT_COLOR, normalized_color, sizeof(CLOCK_TEXT_COLOR)-1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR)-1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n }\n return FALSE;\n}\n\n/**\n * @brief Replace pure black color with near-black\n */\nvoid replaceBlackColor(const char* color, char* output, size_t output_size) {\n if (color && (strcasecmp(color, \"#000000\") == 0)) {\n strncpy(output, \"#000001\", output_size);\n output[output_size - 1] = '\\0';\n } else {\n strncpy(output, color, output_size);\n output[output_size - 1] = '\\0';\n }\n}"], ["/Catime/src/drawing.c", "/**\n * @file drawing.c\n * @brief Window drawing functionality implementation\n * \n * This file implements the drawing-related functionality of the application window,\n * including text rendering, color settings, and window content drawing.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/drawing.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n\n// Variable imported from window_procedure.c\nextern int elapsed_time;\n\n// Using window drawing related constants defined in resource.h\n\nvoid HandleWindowPaint(HWND hwnd, PAINTSTRUCT *ps) {\n static char time_text[50];\n HDC hdc = ps->hdc;\n RECT rect;\n GetClientRect(hwnd, &rect);\n\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, rect.right, rect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n\n SetGraphicsMode(memDC, GM_ADVANCED);\n SetBkMode(memDC, TRANSPARENT);\n SetStretchBltMode(memDC, HALFTONE);\n SetBrushOrgEx(memDC, 0, 0, NULL);\n\n // Generate display text based on different modes\n if (CLOCK_SHOW_CURRENT_TIME) {\n time_t now = time(NULL);\n struct tm *tm_info = localtime(&now);\n int hour = tm_info->tm_hour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, tm_info->tm_min, tm_info->tm_sec);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, tm_info->tm_min);\n }\n } else if (CLOCK_COUNT_UP) {\n // Count-up mode\n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n } else {\n // Countdown mode\n int remaining_time = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining_time <= 0) {\n // Timeout reached, decide whether to display content based on conditions\n if (CLOCK_TOTAL_TIME == 0 && countdown_elapsed_time == 0) {\n // This is the case after sleep operation, don't display anything\n time_text[0] = '\\0';\n } else if (strcmp(CLOCK_TIMEOUT_TEXT, \"0\") == 0) {\n time_text[0] = '\\0';\n } else if (strlen(CLOCK_TIMEOUT_TEXT) > 0) {\n strncpy(time_text, CLOCK_TIMEOUT_TEXT, sizeof(time_text) - 1);\n time_text[sizeof(time_text) - 1] = '\\0';\n } else {\n time_text[0] = '\\0';\n }\n } else {\n int hours = remaining_time / 3600;\n int minutes = (remaining_time % 3600) / 60;\n int seconds = remaining_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n }\n }\n\n const char* fontToUse = IS_PREVIEWING ? PREVIEW_FONT_NAME : FONT_FILE_NAME;\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE * CLOCK_FONT_SCALE_FACTOR,\n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_TT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, \n VARIABLE_PITCH | FF_SWISS,\n IS_PREVIEWING ? PREVIEW_INTERNAL_NAME : FONT_INTERNAL_NAME\n );\n HFONT oldFont = (HFONT)SelectObject(memDC, hFont);\n\n SetTextAlign(memDC, TA_LEFT | TA_TOP);\n SetTextCharacterExtra(memDC, 0);\n SetMapMode(memDC, MM_TEXT);\n\n DWORD quality = SetICMMode(memDC, ICM_ON);\n SetLayout(memDC, 0);\n\n int r = 255, g = 255, b = 255;\n const char* colorToUse = IS_COLOR_PREVIEWING ? PREVIEW_COLOR : CLOCK_TEXT_COLOR;\n \n if (strlen(colorToUse) > 0) {\n if (colorToUse[0] == '#') {\n if (strlen(colorToUse) == 7) {\n sscanf(colorToUse + 1, \"%02x%02x%02x\", &r, &g, &b);\n }\n } else {\n sscanf(colorToUse, \"%d,%d,%d\", &r, &g, &b);\n }\n }\n SetTextColor(memDC, RGB(r, g, b));\n\n if (CLOCK_EDIT_MODE) {\n HBRUSH hBrush = CreateSolidBrush(RGB(20, 20, 20)); // Dark gray background\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n } else {\n HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0));\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n }\n\n if (strlen(time_text) > 0) {\n SIZE textSize;\n GetTextExtentPoint32(memDC, time_text, strlen(time_text), &textSize);\n\n if (textSize.cx != (rect.right - rect.left) || \n textSize.cy != (rect.bottom - rect.top)) {\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left, windowRect.top,\n textSize.cx + WINDOW_HORIZONTAL_PADDING, \n textSize.cy + WINDOW_VERTICAL_PADDING, \n SWP_NOZORDER | SWP_NOACTIVATE);\n GetClientRect(hwnd, &rect);\n }\n\n \n int x = (rect.right - textSize.cx) / 2;\n int y = (rect.bottom - textSize.cy) / 2;\n\n // If in edit mode, force white text and add outline effect\n if (CLOCK_EDIT_MODE) {\n SetTextColor(memDC, RGB(255, 255, 255));\n \n // Add black outline effect\n SetTextColor(memDC, RGB(0, 0, 0));\n TextOutA(memDC, x-1, y, time_text, strlen(time_text));\n TextOutA(memDC, x+1, y, time_text, strlen(time_text));\n TextOutA(memDC, x, y-1, time_text, strlen(time_text));\n TextOutA(memDC, x, y+1, time_text, strlen(time_text));\n \n // Set back to white for drawing text\n SetTextColor(memDC, RGB(255, 255, 255));\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n } else {\n SetTextColor(memDC, RGB(r, g, b));\n \n for (int i = 0; i < 8; i++) {\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n }\n }\n }\n\n BitBlt(hdc, 0, 0, rect.right, rect.bottom, memDC, 0, 0, SRCCOPY);\n\n SelectObject(memDC, oldFont);\n DeleteObject(hFont);\n SelectObject(memDC, oldBitmap);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n}"], ["/Catime/src/async_update_checker.c", "/**\n * @file async_update_checker.c\n * @brief Asynchronous application update checking functionality\n */\n\n#include \n#include \n#include \"../include/async_update_checker.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n\ntypedef struct {\n HWND hwnd;\n BOOL silentCheck;\n} UpdateThreadParams;\n\nstatic HANDLE g_hUpdateThread = NULL;\nstatic BOOL g_bUpdateThreadRunning = FALSE;\n\n/**\n * @brief Clean up update check thread resources\n */\nvoid CleanupUpdateThread() {\n LOG_INFO(\"Cleaning up update check thread resources\");\n if (g_hUpdateThread != NULL) {\n DWORD waitResult = WaitForSingleObject(g_hUpdateThread, 1000);\n if (waitResult == WAIT_TIMEOUT) {\n LOG_WARNING(\"Wait for thread end timed out, forcibly closing thread handle\");\n } else if (waitResult == WAIT_OBJECT_0) {\n LOG_INFO(\"Thread has ended normally\");\n } else {\n LOG_WARNING(\"Wait for thread returned unexpected result: %lu\", waitResult);\n }\n\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n g_bUpdateThreadRunning = FALSE;\n LOG_INFO(\"Thread resources have been cleaned up\");\n } else {\n LOG_INFO(\"Update check thread not running, no cleanup needed\");\n }\n}\n\n/**\n * @brief Update check thread function\n * @param param Thread parameters\n */\nunsigned __stdcall UpdateCheckThreadProc(void* param) {\n LOG_INFO(\"Update check thread started\");\n\n UpdateThreadParams* threadParams = (UpdateThreadParams*)param;\n if (!threadParams) {\n LOG_ERROR(\"Thread parameters are null, cannot perform update check\");\n g_bUpdateThreadRunning = FALSE;\n _endthreadex(1);\n return 1;\n }\n\n HWND hwnd = threadParams->hwnd;\n BOOL silentCheck = threadParams->silentCheck;\n\n LOG_INFO(\"Thread parameters parsed successfully, window handle: 0x%p, silent check mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n\n free(threadParams);\n LOG_INFO(\"Thread parameter memory freed\");\n\n LOG_INFO(\"Starting update check\");\n CheckForUpdateSilent(hwnd, silentCheck);\n LOG_INFO(\"Update check completed\");\n\n g_bUpdateThreadRunning = FALSE;\n\n _endthreadex(0);\n return 0;\n}\n\n/**\n * @brief Check for application updates asynchronously\n * @param hwnd Window handle\n * @param silentCheck Whether to perform a silent check\n */\nvoid CheckForUpdateAsync(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Asynchronous update check requested, window handle: 0x%p, silent mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n\n if (g_bUpdateThreadRunning) {\n LOG_INFO(\"Update check thread already running, skipping this check request\");\n return;\n }\n\n if (g_hUpdateThread != NULL) {\n LOG_INFO(\"Found old thread handle, cleaning up...\");\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n LOG_INFO(\"Old thread handle closed\");\n }\n\n LOG_INFO(\"Allocating memory for thread parameters\");\n UpdateThreadParams* threadParams = (UpdateThreadParams*)malloc(sizeof(UpdateThreadParams));\n if (!threadParams) {\n LOG_ERROR(\"Thread parameter memory allocation failed, cannot start update check thread\");\n return;\n }\n\n threadParams->hwnd = hwnd;\n threadParams->silentCheck = silentCheck;\n LOG_INFO(\"Thread parameters set up\");\n\n g_bUpdateThreadRunning = TRUE;\n\n LOG_INFO(\"Preparing to create update check thread\");\n HANDLE hThread = (HANDLE)_beginthreadex(\n NULL,\n 0,\n UpdateCheckThreadProc,\n threadParams,\n 0,\n NULL\n );\n\n if (hThread) {\n LOG_INFO(\"Update check thread created successfully, thread handle: 0x%p\", hThread);\n g_hUpdateThread = hThread;\n } else {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Update check thread creation failed, error code: %lu, error message: %s\", errorCode, errorMsg);\n\n free(threadParams);\n g_bUpdateThreadRunning = FALSE;\n }\n}"], ["/Catime/src/timer.c", "/**\n * @file timer.c\n * @brief Implementation of core timer functionality\n * \n * This file contains the implementation of the core timer logic, including time format conversion, \n * input parsing, configuration saving, and other functionalities,\n * while maintaining various timer states and configuration parameters.\n */\n\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n/** @name Timer status flags\n * @{ */\nBOOL CLOCK_IS_PAUSED = FALSE; ///< Timer pause status flag\nBOOL CLOCK_SHOW_CURRENT_TIME = FALSE; ///< Show current time mode flag\nBOOL CLOCK_USE_24HOUR = TRUE; ///< Use 24-hour format flag\nBOOL CLOCK_SHOW_SECONDS = TRUE; ///< Show seconds flag\nBOOL CLOCK_COUNT_UP = FALSE; ///< Countdown/count-up mode flag\nchar CLOCK_STARTUP_MODE[20] = \"COUNTDOWN\"; ///< Startup mode (countdown/count-up)\n/** @} */\n\n/** @name Timer time parameters \n * @{ */\nint CLOCK_TOTAL_TIME = 0; ///< Total timer time (seconds)\nint countdown_elapsed_time = 0; ///< Countdown elapsed time (seconds)\nint countup_elapsed_time = 0; ///< Count-up accumulated time (seconds)\ntime_t CLOCK_LAST_TIME_UPDATE = 0; ///< Last update timestamp\n\n// High-precision timer related variables\nLARGE_INTEGER timer_frequency; ///< High-precision timer frequency\nLARGE_INTEGER timer_last_count; ///< Last timing point\nBOOL high_precision_timer_initialized = FALSE; ///< High-precision timer initialization flag\n/** @} */\n\n/** @name Message status flags\n * @{ */\nBOOL countdown_message_shown = FALSE; ///< Countdown completion message display status\nBOOL countup_message_shown = FALSE; ///< Count-up completion message display status\nint pomodoro_work_cycles = 0; ///< Pomodoro work cycle count\n/** @} */\n\n/** @name Timeout action configuration\n * @{ */\nTimeoutActionType CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE; ///< Timeout action type\nchar CLOCK_TIMEOUT_TEXT[50] = \"\"; ///< Timeout display text\nchar CLOCK_TIMEOUT_FILE_PATH[MAX_PATH] = \"\"; ///< Timeout executable file path\n/** @} */\n\n/** @name Pomodoro time settings\n * @{ */\nint POMODORO_WORK_TIME = 25 * 60; ///< Pomodoro work time (25 minutes)\nint POMODORO_SHORT_BREAK = 5 * 60; ///< Pomodoro short break time (5 minutes)\nint POMODORO_LONG_BREAK = 15 * 60; ///< Pomodoro long break time (15 minutes)\nint POMODORO_LOOP_COUNT = 1; ///< Pomodoro loop count (default 1 time)\n/** @} */\n\n/** @name Preset time options\n * @{ */\nint time_options[MAX_TIME_OPTIONS]; ///< Preset time options array\nint time_options_count = 0; ///< Number of valid preset times\n/** @} */\n\n/** Last displayed time (seconds), used to prevent time display jumping phenomenon */\nint last_displayed_second = -1;\n\n/**\n * @brief Initialize high-precision timer\n * \n * Get system timer frequency and record initial timing point\n * @return BOOL Whether initialization was successful\n */\nBOOL InitializeHighPrecisionTimer(void) {\n if (!QueryPerformanceFrequency(&timer_frequency)) {\n return FALSE; // System does not support high-precision timer\n }\n \n if (!QueryPerformanceCounter(&timer_last_count)) {\n return FALSE; // Failed to get current count\n }\n \n high_precision_timer_initialized = TRUE;\n return TRUE;\n}\n\n/**\n * @brief Calculate milliseconds elapsed since last call\n * \n * Use high-precision timer to calculate exact time interval\n * @return double Elapsed milliseconds\n */\ndouble GetElapsedMilliseconds(void) {\n if (!high_precision_timer_initialized) {\n if (!InitializeHighPrecisionTimer()) {\n return 0.0; // Initialization failed, return 0\n }\n }\n \n LARGE_INTEGER current_count;\n if (!QueryPerformanceCounter(¤t_count)) {\n return 0.0; // Failed to get current count\n }\n \n // Calculate time difference (convert to milliseconds)\n double elapsed = (double)(current_count.QuadPart - timer_last_count.QuadPart) * 1000.0 / (double)timer_frequency.QuadPart;\n \n // Update last timing point\n timer_last_count = current_count;\n \n return elapsed;\n}\n\n/**\n * @brief Update elapsed time for countdown/count-up\n * \n * Use high-precision timer to calculate time elapsed since last call, and update\n * countup_elapsed_time (count-up mode) or countdown_elapsed_time (countdown mode) accordingly.\n * No updates are made in pause state.\n */\nvoid UpdateElapsedTime(void) {\n if (CLOCK_IS_PAUSED) {\n return; // Do not update in pause state\n }\n \n double elapsed_ms = GetElapsedMilliseconds();\n \n if (CLOCK_COUNT_UP) {\n // Count-up mode\n countup_elapsed_time += (int)(elapsed_ms / 1000.0);\n } else {\n // Countdown mode\n countdown_elapsed_time += (int)(elapsed_ms / 1000.0);\n \n // Ensure does not exceed total time\n if (countdown_elapsed_time > CLOCK_TOTAL_TIME) {\n countdown_elapsed_time = CLOCK_TOTAL_TIME;\n }\n }\n}\n\n/**\n * @brief Format display time\n * @param remaining_time Remaining time (seconds)\n * @param[out] time_text Formatted time string output buffer\n * \n * Format time as a string according to current configuration (12/24 hour format, whether to show seconds, countdown/count-up mode).\n * Supports three display modes: current system time, countdown remaining time, count-up accumulated time.\n */\nvoid FormatTime(int remaining_time, char* time_text) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // Get local time\n SYSTEMTIME st;\n GetLocalTime(&st);\n \n // Check time continuity, prevent second jumping display\n if (last_displayed_second != -1) {\n // If not consecutive seconds, and not a cross-minute situation\n if (st.wSecond != (last_displayed_second + 1) % 60 && \n !(last_displayed_second == 59 && st.wSecond == 0)) {\n // Relax conditions, allow larger differences to sync, ensure not lagging behind for long\n if (st.wSecond != last_displayed_second) {\n // Directly use system time seconds\n last_displayed_second = st.wSecond;\n }\n } else {\n // Time is consecutive, normal update\n last_displayed_second = st.wSecond;\n }\n } else {\n // First display, initialize record\n last_displayed_second = st.wSecond;\n }\n \n int hour = st.wHour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, st.wMinute, last_displayed_second);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, st.wMinute);\n }\n return;\n }\n\n if (CLOCK_COUNT_UP) {\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n return;\n }\n\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int remaining = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining <= 0) {\n // Do not return empty string, show 0:00 instead\n sprintf(time_text, \" 0:00\");\n return;\n }\n\n int hours = remaining / 3600;\n int minutes = (remaining % 3600) / 60;\n int seconds = remaining % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n if (minutes >= 10) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n }\n } else {\n if (seconds < 10) {\n sprintf(time_text, \" %d\", seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n }\n}\n\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n */\n\n// Detailed explanation of parsing logic and boundary handling\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n * \n * Parsing process:\n * 1. First check the validity of the input\n * 2. Detect if it's a target time format (ending with 't' or 'T')\n * - If so, calculate seconds from current to target time, if time has passed set to same time tomorrow\n * 3. Otherwise, check if it contains unit identifiers (h/m/s)\n * - If it does, process according to units\n * - If not, decide processing method based on number of space-separated numbers\n * \n * Boundary handling:\n * - Invalid input returns 0\n * - Negative or zero value returns 0\n * - Value exceeding INT_MAX returns 0\n */\nint ParseInput(const char* input, int* total_seconds) {\n if (!isValidInput(input)) return 0;\n\n int total = 0;\n char input_copy[256];\n strncpy(input_copy, input, sizeof(input_copy)-1);\n input_copy[sizeof(input_copy)-1] = '\\0';\n\n // Check if it's a target time format (ending with 't' or 'T')\n int len = strlen(input_copy);\n if (len > 0 && (input_copy[len-1] == 't' || input_copy[len-1] == 'T')) {\n // Remove 't' or 'T' suffix\n input_copy[len-1] = '\\0';\n \n // Get current time\n time_t now = time(NULL);\n struct tm *tm_now = localtime(&now);\n \n // Target time, initialize to current date\n struct tm tm_target = *tm_now;\n \n // Parse target time\n int hour = -1, minute = -1, second = -1;\n int count = 0;\n char *token = strtok(input_copy, \" \");\n \n while (token && count < 3) {\n int value = atoi(token);\n if (count == 0) hour = value;\n else if (count == 1) minute = value;\n else if (count == 2) second = value;\n count++;\n token = strtok(NULL, \" \");\n }\n \n // Set target time, set according to provided values, defaults to 0 if not provided\n if (hour >= 0) {\n tm_target.tm_hour = hour;\n \n // If only hour provided, set minute and second to 0\n if (minute < 0) {\n tm_target.tm_min = 0;\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_min = minute;\n \n // If second not provided, set to 0\n if (second < 0) {\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_sec = second;\n }\n }\n }\n \n // Calculate time difference (seconds)\n time_t target_time = mktime(&tm_target);\n \n // If target time has passed, set to same time tomorrow\n if (target_time <= now) {\n tm_target.tm_mday += 1;\n target_time = mktime(&tm_target);\n }\n \n total = (int)difftime(target_time, now);\n } else {\n // Check if it contains unit identifiers\n BOOL hasUnits = FALSE;\n for (int i = 0; input_copy[i]; i++) {\n char c = tolower((unsigned char)input_copy[i]);\n if (c == 'h' || c == 'm' || c == 's') {\n hasUnits = TRUE;\n break;\n }\n }\n \n if (hasUnits) {\n // For input with units, merge all parts with unit markings\n char* parts[10] = {0}; // Store up to 10 parts\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 10) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n // Process each part\n for (int i = 0; i < part_count; i++) {\n char* part = parts[i];\n int part_len = strlen(part);\n BOOL has_unit = FALSE;\n \n // Check if this part has a unit\n for (int j = 0; j < part_len; j++) {\n char c = tolower((unsigned char)part[j]);\n if (c == 'h' || c == 'm' || c == 's') {\n has_unit = TRUE;\n break;\n }\n }\n \n if (has_unit) {\n // If it has a unit, process according to unit\n char unit = tolower((unsigned char)part[part_len-1]);\n part[part_len-1] = '\\0'; // Remove unit\n int value = atoi(part);\n \n switch (unit) {\n case 'h': total += value * 3600; break;\n case 'm': total += value * 60; break;\n case 's': total += value; break;\n }\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'h') {\n // If next item has h unit, current item is hours\n total += atoi(part) * 3600;\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'm') {\n // If next item has m unit, current item is hours\n total += atoi(part) * 3600;\n } else {\n // Default process as two-segment or three-segment format\n if (part_count == 2) {\n // Two-segment format: first segment is minutes, second segment is seconds\n if (i == 0) total += atoi(part) * 60;\n else total += atoi(part);\n } else if (part_count == 3) {\n // Three-segment format: hour:minute:second\n if (i == 0) total += atoi(part) * 3600;\n else if (i == 1) total += atoi(part) * 60;\n else total += atoi(part);\n } else {\n // Other cases treated as minutes\n total += atoi(part) * 60;\n }\n }\n }\n } else {\n // Processing without units\n char* parts[3] = {0}; // Store up to 3 parts (hour, minute, second)\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 3) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n if (part_count == 1) {\n // Single number, calculate as minutes\n total = atoi(parts[0]) * 60;\n } else if (part_count == 2) {\n // Two numbers: minute:second\n total = atoi(parts[0]) * 60 + atoi(parts[1]);\n } else if (part_count == 3) {\n // Three numbers: hour:minute:second\n total = atoi(parts[0]) * 3600 + atoi(parts[1]) * 60 + atoi(parts[2]);\n }\n }\n }\n\n *total_seconds = total;\n if (*total_seconds <= 0) return 0;\n\n if (*total_seconds > INT_MAX) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Validate if input string is legal\n * @param input Input string to validate\n * @return int Returns 1 if legal, 0 if illegal\n * \n * Valid character check rules:\n * - Only allows digits, spaces, and h/m/s/t unit identifiers at the end (case insensitive)\n * - Must contain at least one digit\n * - Maximum of two space separators\n */\nint isValidInput(const char* input) {\n if (input == NULL || *input == '\\0') {\n return 0;\n }\n\n int len = strlen(input);\n int digitCount = 0;\n\n for (int i = 0; i < len; i++) {\n if (isdigit(input[i])) {\n digitCount++;\n } else if (input[i] == ' ') {\n // Allow any number of spaces\n } else if (i == len - 1 && (input[i] == 'h' || input[i] == 'm' || input[i] == 's' || \n input[i] == 't' || input[i] == 'T' || \n input[i] == 'H' || input[i] == 'M' || input[i] == 'S')) {\n // Allow last character to be h/m/s/t or their uppercase forms\n } else {\n return 0;\n }\n }\n\n if (digitCount == 0) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Reset timer\n * \n * Reset timer state, including pause flag, elapsed time, etc.\n */\nvoid ResetTimer(void) {\n // Reset timing state\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time = 0;\n } else {\n countdown_elapsed_time = 0;\n \n // Ensure countdown total time is not zero, zero would cause timer not to display\n if (CLOCK_TOTAL_TIME <= 0) {\n // If total time is invalid, use default value\n CLOCK_TOTAL_TIME = 60; // Default set to 1 minute\n }\n }\n \n // Cancel pause state\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset message display flags\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Reinitialize high-precision timer\n InitializeHighPrecisionTimer();\n}\n\n/**\n * @brief Toggle timer pause state\n * \n * Toggle timer between pause and continue states\n */\nvoid TogglePauseTimer(void) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n // If resuming from pause state, reinitialize high-precision timer\n if (!CLOCK_IS_PAUSED) {\n InitializeHighPrecisionTimer();\n }\n}\n\n/**\n * @brief Write default startup time to configuration file\n * @param seconds Default startup time (seconds)\n * \n * Use the general path retrieval method in the configuration management module to write to INI format configuration file\n */\nvoid WriteConfigDefaultStartTime(int seconds) {\n char config_path[MAX_PATH];\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Write using INI format\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", seconds, config_path);\n}\n"], ["/Catime/src/drag_scale.c", "/**\n * @file drag_scale.c\n * @brief Window dragging and scaling functionality implementation\n * \n * This file implements the dragging and scaling functionality of the application window,\n * including mouse dragging of the window and mouse wheel scaling of the window.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n\n// Add variable to record the topmost state before edit mode\nBOOL PREVIOUS_TOPMOST_STATE = FALSE;\n\nvoid StartDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_IS_DRAGGING = TRUE;\n SetCapture(hwnd);\n GetCursorPos(&CLOCK_LAST_MOUSE_POS);\n }\n}\n\nvoid StartEditMode(HWND hwnd) {\n // Record current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If currently not in topmost state, set to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Then enable edit mode\n CLOCK_EDIT_MODE = TRUE;\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure mouse cursor is default arrow\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n}\n\nvoid EndEditMode(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_EDIT_MODE = FALSE;\n \n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // If previously not in topmost state, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n }\n}\n\nvoid EndDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n CLOCK_IS_DRAGGING = FALSE;\n ReleaseCapture();\n // In edit mode, don't force window to stay on screen, allow dragging out\n AdjustWindowPosition(hwnd, FALSE);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\nBOOL HandleDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleScaleWindow(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings\n SaveWindowSettings(hwnd);\n return TRUE;\n }\n }\n return FALSE;\n}"], ["/Catime/src/media.c", "/**\n * @file media.c\n * @brief Media control functionality implementation\n * \n * This file implements the application's media control related functions,\n * including pause, play and other media control operations.\n */\n\n#include \n#include \"../include/media.h\"\n\n/**\n * @brief Pause media playback\n * \n * Pauses currently playing media by simulating media control key press events.\n * Includes a combination of stop and pause/play operations to ensure the media is properly paused.\n */\nvoid PauseMediaPlayback(void) {\n keybd_event(VK_MEDIA_STOP, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_STOP, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(100);\n}"], ["/Catime/libs/miniaudio/miniaudio.c", "#define MINIAUDIO_IMPLEMENTATION\n#include \"miniaudio.h\"\n"]], "task_instance_info": {"created_time": "2025-08-20 17:54:33", "created_task_model": "DeepSeek-R1", "function_skeleton": "void InitTrayIcon(HWND hwnd, HINSTANCE hInstance) {}", "code_description": "This code segment functions to: Initialize a system tray icon by configuring its visual properties and metadata, including loading graphical resources, setting notification callbacks, and populating version information in the tooltip text before registering it with the operating system's notification area."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nvoid InitTrayIcon(HWND hwnd, HINSTANCE hInstance) {\n memset(&nid, 0, sizeof(nid));\n nid.cbSize = sizeof(NOTIFYICONDATAW);\n nid.hWnd = hwnd;\n nid.uID = CLOCK_ID_TRAY_APP_ICON;\n nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP;\n nid.uCallbackMessage = WM_TRAYICON;\n nid.hIcon = LoadImageW(hInstance, MAKEINTRESOURCEW(IDI_TRAY_ICON), IMAGE_ICON, \n GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), \n LR_DEFAULTCOLOR);\n \n MultiByteToWideChar(CP_UTF8, 0, GetString(STR_TRAY_TOOLTIP), -1, \n nid.szTip, sizeof(nid.szTip)/sizeof(WCHAR));\n \n Shell_NotifyIconW(NIM_ADD, &nid);\n Shell_NotifyIconW(NIM_SETVERSION, &nid, NOTIFYICON_VERSION_4);\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 17-55-10"}, "editdistance_info": {"edit_distance": 35.1464, "calculate_time": "2025-08-20 17:55:10", "true_code_clean": "void InitTrayIcon(HWND hwnd, HINSTANCE hInstance) {\n memset(&nid, 0, sizeof(nid));\n nid.cbSize = sizeof(nid);\n nid.uID = CLOCK_ID_TRAY_APP_ICON;\n nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;\n nid.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CATIME));\n nid.hWnd = hwnd;\n nid.uCallbackMessage = CLOCK_WM_TRAYICON;\n wchar_t versionText[128] = {0};\n wchar_t versionWide[64] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CATIME_VERSION, -1, versionWide, _countof(versionWide));\n swprintf_s(versionText, _countof(versionText), L\"Catime %s\", versionWide);\n wcscpy_s(nid.szTip, _countof(nid.szTip), versionText);\n Shell_NotifyIconW(NIM_ADD, &nid);\n if (WM_TASKBARCREATED == 0) {\n RegisterTaskbarCreatedMessage();\n }\n}", "predict_code_clean": "void InitTrayIcon(HWND hwnd, HINSTANCE hInstance) {\n memset(&nid, 0, sizeof(nid));\n nid.cbSize = sizeof(NOTIFYICONDATAW);\n nid.hWnd = hwnd;\n nid.uID = CLOCK_ID_TRAY_APP_ICON;\n nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP;\n nid.uCallbackMessage = WM_TRAYICON;\n nid.hIcon = LoadImageW(hInstance, MAKEINTRESOURCEW(IDI_TRAY_ICON), IMAGE_ICON, \n GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), \n LR_DEFAULTCOLOR);\n MultiByteToWideChar(CP_UTF8, 0, GetString(STR_TRAY_TOOLTIP), -1, \n nid.szTip, sizeof(nid.szTip)/sizeof(WCHAR));\n Shell_NotifyIconW(NIM_ADD, &nid);\n Shell_NotifyIconW(NIM_SETVERSION, &nid, NOTIFYICON_VERSION_4);\n}"}} {"repo_name": "Catime", "file_name": "/Catime/src/main.c", "inference_info": {"prefix_code": "/**\n * @file main.c\n * @brief Application main entry module implementation file\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\"\n#include \"../include/window.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/media.h\"\n#include \"../include/notification.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/dialog_language.h\"\n#include \"../include/shortcut_checker.h\"\n\n// Required for older Windows SDK\n#ifndef CSIDL_STARTUP\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n// Compiler directives\n#pragma comment(lib, \"dwmapi.lib\")\n#pragma comment(lib, \"user32.lib\")\n#pragma comment(lib, \"gdi32.lib\")\n#pragma comment(lib, \"comdlg32.lib\")\n#pragma comment(lib, \"dbghelp.lib\")\n#pragma comment(lib, \"comctl32.lib\")\n\nextern void CleanupLogSystem(void);\n\nint default_countdown_time = 0;\nint CLOCK_DEFAULT_START_TIME = 300;\nint elapsed_time = 0;\nchar inputText[256] = {0};\nint message_shown = 0;\ntime_t last_config_time = 0;\nRecentFile CLOCK_RECENT_FILES[MAX_RECENT_FILES];\nint CLOCK_RECENT_FILES_COUNT = 0;\nchar CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH] = \"\";\n\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char FONT_INTERNAL_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\n\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid ExitProgram(HWND hwnd);\n\n/**\n * @brief Handle application startup mode\n * @param hwnd Main window handle\n */\n", "suffix_code": "\n\n/**\n * @brief Application main entry point\n */\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n // Initialize Common Controls\n InitCommonControls();\n \n // Initialize log system\n if (!InitializeLogSystem()) {\n // If log system initialization fails, continue running but without logging\n MessageBox(NULL, \"Log system initialization failed, the program will continue running but will not log.\", \"Warning\", MB_ICONWARNING);\n }\n\n // Set up exception handler\n SetupExceptionHandler();\n\n LOG_INFO(\"Catime is starting...\");\n // Initialize COM\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM initialization failed, error code: 0x%08X\", hr);\n MessageBox(NULL, \"COM initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"COM initialization successful\");\n\n // Initialize application\n LOG_INFO(\"Starting application initialization...\");\n if (!InitializeApplication(hInstance)) {\n LOG_ERROR(\"Application initialization failed\");\n MessageBox(NULL, \"Application initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"Application initialization successful\");\n\n // Check and create desktop shortcut (if necessary)\n LOG_INFO(\"Checking desktop shortcut...\");\n char exe_path[MAX_PATH];\n GetModuleFileNameA(NULL, exe_path, MAX_PATH);\n LOG_INFO(\"Current program path: %s\", exe_path);\n \n // Set log level to DEBUG to show detailed information\n WriteLog(LOG_LEVEL_DEBUG, \"Starting shortcut detection, checking path: %s\", exe_path);\n \n // Check if path contains WinGet identifier\n if (strstr(exe_path, \"WinGet\") != NULL) {\n WriteLog(LOG_LEVEL_DEBUG, \"Path contains WinGet keyword\");\n }\n \n // Additional test: directly test if file exists\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path))) {\n sprintf(shortcut_path, \"%s\\\\Catime.lnk\", desktop_path);\n WriteLog(LOG_LEVEL_DEBUG, \"Checking if desktop shortcut exists: %s\", shortcut_path);\n if (GetFileAttributesA(shortcut_path) == INVALID_FILE_ATTRIBUTES) {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut does not exist, need to create\");\n } else {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut already exists\");\n }\n }\n \n int shortcut_result = CheckAndCreateShortcut();\n if (shortcut_result == 0) {\n LOG_INFO(\"Desktop shortcut check completed\");\n } else {\n LOG_WARNING(\"Desktop shortcut creation failed, error code: %d\", shortcut_result);\n }\n\n // Initialize dialog multi-language support\n LOG_INFO(\"Starting dialog multi-language support initialization...\");\n if (!InitDialogLanguageSupport()) {\n LOG_WARNING(\"Dialog multi-language support initialization failed, but program will continue running\");\n }\n LOG_INFO(\"Dialog multi-language support initialization successful\");\n\n // Handle single instance\n LOG_INFO(\"Checking if another instance is running...\");\n HANDLE hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n DWORD mutexError = GetLastError();\n \n if (mutexError == ERROR_ALREADY_EXISTS) {\n LOG_INFO(\"Detected another instance is running, trying to close that instance\");\n HWND hwndExisting = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwndExisting) {\n // Close existing window instance\n LOG_INFO(\"Sending close message to existing instance\");\n SendMessage(hwndExisting, WM_CLOSE, 0, 0);\n // Wait for old instance to close\n Sleep(200);\n } else {\n LOG_WARNING(\"Could not find window handle of existing instance, but mutex exists\");\n }\n // Release old mutex\n ReleaseMutex(hMutex);\n CloseHandle(hMutex);\n \n // Create new mutex\n LOG_INFO(\"Creating new mutex\");\n hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n if (GetLastError() == ERROR_ALREADY_EXISTS) {\n LOG_WARNING(\"Still have conflict after creating new mutex, possible race condition\");\n }\n }\n Sleep(50);\n\n // Create main window\n LOG_INFO(\"Starting main window creation...\");\n HWND hwnd = CreateMainWindow(hInstance, nCmdShow);\n if (!hwnd) {\n LOG_ERROR(\"Main window creation failed\");\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Main window creation successful, handle: 0x%p\", hwnd);\n\n // Set timer\n LOG_INFO(\"Setting main timer...\");\n if (SetTimer(hwnd, 1, 1000, NULL) == 0) {\n DWORD timerError = GetLastError();\n LOG_ERROR(\"Timer creation failed, error code: %lu\", timerError);\n MessageBox(NULL, \"Timer Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Timer set successfully\");\n\n // Handle startup mode\n LOG_INFO(\"Handling startup mode: %s\", CLOCK_STARTUP_MODE);\n HandleStartupMode(hwnd);\n \n // Automatic update check code has been removed\n\n // Message loop\n LOG_INFO(\"Entering main message loop\");\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0) > 0) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n // Clean up resources\n LOG_INFO(\"Program preparing to exit, starting resource cleanup\");\n \n // Clean up update check thread resources\n LOG_INFO(\"Preparing to clean up update check thread resources\");\n CleanupUpdateThread();\n \n CloseHandle(hMutex);\n CoUninitialize();\n \n // Close log system\n CleanupLogSystem();\n \n return (int)msg.wParam;\n // If execution reaches here, the program has exited normally\n}\n", "middle_code": "static void HandleStartupMode(HWND hwnd) {\n LOG_INFO(\"Setting startup mode: %s\", CLOCK_STARTUP_MODE);\n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n LOG_INFO(\"Setting to count-up mode\");\n CLOCK_COUNT_UP = TRUE;\n elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n LOG_INFO(\"Setting to hidden mode, window will be hidden\");\n ShowWindow(hwnd, SW_HIDE);\n KillTimer(hwnd, 1);\n elapsed_time = CLOCK_TOTAL_TIME;\n CLOCK_IS_PAUSED = TRUE;\n message_shown = TRUE;\n countdown_message_shown = TRUE;\n countup_message_shown = TRUE;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n LOG_INFO(\"Setting to show current time mode\");\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_LAST_TIME_UPDATE = 0;\n } else {\n LOG_INFO(\"Using default countdown mode\");\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/Catime/src/shortcut_checker.c", "/**\n * @file shortcut_checker.c\n * @brief Implementation of desktop shortcut detection and creation\n *\n * Detects if the program is installed from the App Store or WinGet,\n * and creates a desktop shortcut when necessary.\n */\n\n#include \"../include/shortcut_checker.h\"\n#include \"../include/config.h\"\n#include \"../include/log.h\" // Include log header\n#include // For printf debug output\n#include \n#include \n#include \n#include \n#include \n#include \n\n// Import required COM interfaces\n#include \n\n// We don't need to manually define IID_IShellLinkA, it's already defined in system headers\n\n/**\n * @brief Check if a string starts with a specified prefix\n * \n * @param str The string to check\n * @param prefix The prefix string\n * @return bool true if the string starts with the specified prefix, false otherwise\n */\nstatic bool StartsWith(const char* str, const char* prefix) {\n size_t prefix_len = strlen(prefix);\n size_t str_len = strlen(str);\n \n if (str_len < prefix_len) {\n return false;\n }\n \n return strncmp(str, prefix, prefix_len) == 0;\n}\n\n/**\n * @brief Check if a string contains a specified substring\n * \n * @param str The string to check\n * @param substring The substring\n * @return bool true if the string contains the specified substring, false otherwise\n */\nstatic bool Contains(const char* str, const char* substring) {\n return strstr(str, substring) != NULL;\n}\n\n/**\n * @brief Check if the program is installed from the App Store or WinGet\n * \n * @param exe_path Buffer to output the program path\n * @param path_size Buffer size\n * @return bool true if installed from the App Store or WinGet, false otherwise\n */\nstatic bool IsStoreOrWingetInstall(char* exe_path, size_t path_size) {\n // Get program path\n if (GetModuleFileNameA(NULL, exe_path, path_size) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n return false;\n }\n \n LOG_DEBUG(\"Checking program path: %s\", exe_path);\n \n // Check if it's an App Store installation path (starts with C:\\Program Files\\WindowsApps)\n if (StartsWith(exe_path, \"C:\\\\Program Files\\\\WindowsApps\")) {\n LOG_DEBUG(\"Detected App Store installation path\");\n return true;\n }\n \n // Check if it's a WinGet installation path\n // 1. Regular path containing \\AppData\\Local\\Microsoft\\WinGet\\Packages\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\WinGet\\\\Packages\")) {\n LOG_DEBUG(\"Detected WinGet installation path (regular)\");\n return true;\n }\n \n // 2. Possible custom WinGet installation path (if in C:\\Users\\username\\AppData\\Local\\Microsoft\\*)\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\\") && Contains(exe_path, \"WinGet\")) {\n LOG_DEBUG(\"Detected possible WinGet installation path (custom)\");\n return true;\n }\n \n // Force test: When the path contains specific strings, consider it a path that needs to create shortcuts\n // This test path matches the installation path seen in user logs\n if (Contains(exe_path, \"\\\\WinGet\\\\catime.exe\")) {\n LOG_DEBUG(\"Detected specific WinGet installation path\");\n return true;\n }\n \n LOG_DEBUG(\"Not a Store or WinGet installation path\");\n return false;\n}\n\n/**\n * @brief Check if the desktop already has a shortcut and if the shortcut points to the current program\n * \n * @param exe_path Program path\n * @param shortcut_path_out If a shortcut is found, output the shortcut path\n * @param shortcut_path_size Shortcut path buffer size\n * @param target_path_out If a shortcut is found, output the shortcut target path\n * @param target_path_size Target path buffer size\n * @return int 0=shortcut not found, 1=shortcut found and points to current program, 2=shortcut found but points to another path\n */\nstatic int CheckShortcutTarget(const char* exe_path, char* shortcut_path_out, size_t shortcut_path_size, \n char* target_path_out, size_t target_path_size) {\n char desktop_path[MAX_PATH];\n char public_desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char link_target[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n WIN32_FIND_DATAA find_data;\n int result = 0;\n \n // Get user desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n LOG_DEBUG(\"User desktop path: %s\", desktop_path);\n \n // Get public desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_COMMON_DESKTOPDIRECTORY, NULL, 0, public_desktop_path);\n if (FAILED(hr)) {\n LOG_WARNING(\"Failed to get public desktop path, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_DEBUG(\"Public desktop path: %s\", public_desktop_path);\n }\n \n // First check user desktop - build complete shortcut path (Catime.lnk)\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n LOG_DEBUG(\"Checking user desktop shortcut: %s\", shortcut_path);\n \n // Check if the user desktop shortcut file exists\n bool file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n \n // If not found on user desktop, check public desktop\n if (!file_exists && SUCCEEDED(hr)) {\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", public_desktop_path);\n LOG_DEBUG(\"Checking public desktop shortcut: %s\", shortcut_path);\n \n file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n }\n \n // If no shortcut file is found, return 0 directly\n if (!file_exists) {\n LOG_DEBUG(\"No shortcut files found\");\n return 0;\n }\n \n // Save the found shortcut path to the output parameter\n if (shortcut_path_out && shortcut_path_size > 0) {\n strncpy(shortcut_path_out, shortcut_path, shortcut_path_size);\n shortcut_path_out[shortcut_path_size - 1] = '\\0';\n }\n \n // Found shortcut file, get its target\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Convert to wide character\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_ACP, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Load shortcut\n hr = ppf->lpVtbl->Load(ppf, wide_path, STGM_READ);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to load shortcut, hr=0x%08X\", (unsigned int)hr);\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Get shortcut target path\n hr = psl->lpVtbl->GetPath(psl, link_target, MAX_PATH, &find_data, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get shortcut target path, hr=0x%08X\", (unsigned int)hr);\n result = 0;\n } else {\n LOG_DEBUG(\"Shortcut target path: %s\", link_target);\n LOG_DEBUG(\"Current program path: %s\", exe_path);\n \n // Save target path to output parameter\n if (target_path_out && target_path_size > 0) {\n strncpy(target_path_out, link_target, target_path_size);\n target_path_out[target_path_size - 1] = '\\0';\n }\n \n // Check if the shortcut points to the current program\n if (_stricmp(link_target, exe_path) == 0) {\n LOG_DEBUG(\"Shortcut points to current program\");\n result = 1;\n } else {\n LOG_DEBUG(\"Shortcut points to another path\");\n result = 2;\n }\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return result;\n}\n\n/**\n * @brief Create or update desktop shortcut\n * \n * @param exe_path Program path\n * @param existing_shortcut_path Existing shortcut path, create new one if NULL\n * @return bool true for successful creation/update, false for failure\n */\nstatic bool CreateOrUpdateDesktopShortcut(const char* exe_path, const char* existing_shortcut_path) {\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char icon_path[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n bool success = false;\n \n // If an existing shortcut path is provided, use it; otherwise create a new shortcut on the user's desktop\n if (existing_shortcut_path && *existing_shortcut_path) {\n LOG_INFO(\"Starting to update desktop shortcut: %s pointing to: %s\", existing_shortcut_path, exe_path);\n strcpy(shortcut_path, existing_shortcut_path);\n } else {\n LOG_INFO(\"Starting to create desktop shortcut, program path: %s\", exe_path);\n \n // Get desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n LOG_DEBUG(\"Desktop path: %s\", desktop_path);\n \n // Build complete shortcut path\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n }\n \n LOG_DEBUG(\"Shortcut path: %s\", shortcut_path);\n \n // Use program path as icon path\n strcpy(icon_path, exe_path);\n \n // Create IShellLink interface\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n \n // Set target path\n hr = psl->lpVtbl->SetPath(psl, exe_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set shortcut target path, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Set working directory (use the directory where the executable is located)\n char work_dir[MAX_PATH];\n strcpy(work_dir, exe_path);\n char* last_slash = strrchr(work_dir, '\\\\');\n if (last_slash) {\n *last_slash = '\\0';\n }\n LOG_DEBUG(\"Working directory: %s\", work_dir);\n \n hr = psl->lpVtbl->SetWorkingDirectory(psl, work_dir);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set working directory, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set icon\n hr = psl->lpVtbl->SetIconLocation(psl, icon_path, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set icon, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set description\n hr = psl->lpVtbl->SetDescription(psl, \"A very useful timer (Pomodoro Clock)\");\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set description, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set window style (normal window)\n psl->lpVtbl->SetShowCmd(psl, SW_SHOWNORMAL);\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Convert to wide characters\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Save shortcut\n hr = ppf->lpVtbl->Save(ppf, wide_path, TRUE);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to save shortcut, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_INFO(\"Desktop shortcut %s successful: %s\", existing_shortcut_path ? \"update\" : \"creation\", shortcut_path);\n success = true;\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return success;\n}\n\n/**\n * @brief Check and create desktop shortcut\n * \n * All installation types will check if the desktop shortcut exists and points to the current program.\n * If the shortcut already exists but points to another program, it will be updated to the current path.\n * But only versions installed from the Windows App Store or WinGet will create a new shortcut.\n * If SHORTCUT_CHECK_DONE=TRUE is marked in the configuration file, no new shortcut will be created even if the shortcut is deleted.\n * \n * @return int 0 means no need to create/update or create/update successful, 1 means failure\n */\nint CheckAndCreateShortcut(void) {\n char exe_path[MAX_PATH];\n char config_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char target_path[MAX_PATH];\n bool shortcut_check_done = false;\n bool isStoreInstall = false;\n \n // Initialize COM library, needed for creating shortcuts later\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM library initialization failed, hr=0x%08X\", (unsigned int)hr);\n return 1;\n }\n \n LOG_DEBUG(\"Starting shortcut check\");\n \n // Read the flag from the configuration file to determine if it has been checked\n GetConfigPath(config_path, MAX_PATH);\n shortcut_check_done = IsShortcutCheckDone();\n \n LOG_DEBUG(\"Configuration path: %s, already checked: %d\", config_path, shortcut_check_done);\n \n // Get current program path\n if (GetModuleFileNameA(NULL, exe_path, MAX_PATH) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n CoUninitialize();\n return 1;\n }\n LOG_DEBUG(\"Program path: %s\", exe_path);\n \n // Check if it's an App Store or WinGet installation (only affects the behavior of creating new shortcuts)\n isStoreInstall = IsStoreOrWingetInstall(exe_path, MAX_PATH);\n LOG_DEBUG(\"Is Store/WinGet installation: %d\", isStoreInstall);\n \n // Check if the shortcut exists and points to the current program\n // Return value: 0=does not exist, 1=exists and points to the current program, 2=exists but points to another path\n int shortcut_status = CheckShortcutTarget(exe_path, shortcut_path, MAX_PATH, target_path, MAX_PATH);\n \n if (shortcut_status == 0) {\n // Shortcut does not exist\n if (shortcut_check_done) {\n // If the configuration has already been marked as checked, don't create it even if there's no shortcut\n LOG_INFO(\"No shortcut found on desktop, but configuration marked as checked, not creating\");\n CoUninitialize();\n return 0;\n } else if (isStoreInstall) {\n // Only first-run Store or WinGet installations create shortcuts\n LOG_INFO(\"No shortcut found on desktop, first run of Store/WinGet installation, starting to create\");\n bool success = CreateOrUpdateDesktopShortcut(exe_path, NULL);\n \n // Mark as checked, regardless of whether creation was successful\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return success ? 0 : 1;\n } else {\n LOG_INFO(\"No shortcut found on desktop, not a Store/WinGet installation, not creating shortcut\");\n \n // Mark as checked\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return 0;\n }\n } else if (shortcut_status == 1) {\n // Shortcut exists and points to the current program, no action needed\n LOG_INFO(\"Desktop shortcut already exists and points to the current program\");\n \n // Mark as checked\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return 0;\n } else if (shortcut_status == 2) {\n // Shortcut exists but points to another program, any installation method will update it\n LOG_INFO(\"Desktop shortcut points to another path: %s, will update to: %s\", target_path, exe_path);\n bool success = CreateOrUpdateDesktopShortcut(exe_path, shortcut_path);\n \n // Mark as checked, regardless of whether the update was successful\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return success ? 0 : 1;\n }\n \n // Should not reach here\n LOG_ERROR(\"Unknown shortcut check status\");\n CoUninitialize();\n return 1;\n} "], ["/Catime/src/window_procedure.c", "/**\n * @file window_procedure.c\n * @brief Window message processing implementation\n * \n * This file implements the message processing callback function for the application's main window,\n * handling all message events for the window.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\" \n#include \"../include/window.h\" \n#include \"../include/startup.h\" \n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/window_events.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/drawing.h\"\n#include \"../include/timer_events.h\"\n#include \"../include/tray_events.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/notification.h\" // Add notification header\n\n// Variables imported from main.c\nextern char inputText[256];\nextern int elapsed_time;\nextern int message_shown;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void PauseMediaPlayback(void);\n\n// Add these external variable declarations at the beginning of the file\nextern int POMODORO_TIMES[10]; // Pomodoro time array\nextern int POMODORO_TIMES_COUNT; // Number of pomodoro time options\nextern int current_pomodoro_time_index; // Current pomodoro time index\nextern int complete_pomodoro_cycles; // Completed pomodoro cycles\n\n// If ShowInputDialog function needs to be declared, add at the beginning\nextern BOOL ShowInputDialog(HWND hwnd, char* text);\n\n// Modify to match the correct function declaration in config.h\nextern void WriteConfigPomodoroTimeOptions(int* times, int count);\n\n// If the function doesn't exist, use an existing similar function\n// For example, modify calls to WriteConfigPomodoroTimeOptions to WriteConfigPomodoroTimes\n\n// Add at the beginning of the file\ntypedef struct {\n const wchar_t* title;\n const wchar_t* prompt;\n const wchar_t* defaultText;\n wchar_t* result;\n size_t maxLen;\n} INPUTBOX_PARAMS;\n\n// Add declaration for ShowPomodoroLoopDialog function at the beginning of the file\nextern void ShowPomodoroLoopDialog(HWND hwndParent);\n\n// Add declaration for OpenUserGuide function\nextern void OpenUserGuide(void);\n\n// Add declaration for OpenSupportPage function\nextern void OpenSupportPage(void);\n\n// Add declaration for OpenFeedbackPage function\nextern void OpenFeedbackPage(void);\n\n// Helper function: Check if a string contains only spaces\nstatic BOOL isAllSpacesOnly(const char* str) {\n for (int i = 0; str[i]; i++) {\n if (!isspace((unsigned char)str[i])) {\n return FALSE;\n }\n }\n return TRUE;\n}\n\n/**\n * @brief Input dialog callback function\n * @param hwndDlg Dialog handle\n * @param uMsg Message\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return Processing result\n */\nINT_PTR CALLBACK InputBoxProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {\n static wchar_t* result;\n static size_t maxLen;\n \n switch (uMsg) {\n case WM_INITDIALOG: {\n // Get passed parameters\n INPUTBOX_PARAMS* params = (INPUTBOX_PARAMS*)lParam;\n result = params->result;\n maxLen = params->maxLen;\n \n // Set dialog title\n SetWindowTextW(hwndDlg, params->title);\n \n // Set prompt message\n SetDlgItemTextW(hwndDlg, IDC_STATIC_PROMPT, params->prompt);\n \n // Set default text\n SetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, params->defaultText);\n \n // Select text\n SendDlgItemMessageW(hwndDlg, IDC_EDIT_INPUT, EM_SETSEL, 0, -1);\n \n // Set focus\n SetFocus(GetDlgItem(hwndDlg, IDC_EDIT_INPUT));\n return FALSE;\n }\n \n case WM_COMMAND:\n switch (LOWORD(wParam)) {\n case IDOK: {\n // Get input text\n GetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, result, (int)maxLen);\n EndDialog(hwndDlg, TRUE);\n return TRUE;\n }\n \n case IDCANCEL:\n // Cancel operation\n EndDialog(hwndDlg, FALSE);\n return TRUE;\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display input dialog\n * @param hwndParent Parent window handle\n * @param title Dialog title\n * @param prompt Prompt message\n * @param defaultText Default text\n * @param result Result buffer\n * @param maxLen Maximum buffer length\n * @return TRUE if successful, FALSE if canceled\n */\nBOOL InputBox(HWND hwndParent, const wchar_t* title, const wchar_t* prompt, \n const wchar_t* defaultText, wchar_t* result, size_t maxLen) {\n // Prepare parameters to pass to dialog\n INPUTBOX_PARAMS params;\n params.title = title;\n params.prompt = prompt;\n params.defaultText = defaultText;\n params.result = result;\n params.maxLen = maxLen;\n \n // Display modal dialog\n return DialogBoxParamW(GetModuleHandle(NULL), \n MAKEINTRESOURCEW(IDD_INPUTBOX), \n hwndParent, \n InputBoxProc, \n (LPARAM)¶ms) == TRUE;\n}\n\nvoid ExitProgram(HWND hwnd) {\n RemoveTrayIcon();\n\n PostQuitMessage(0);\n}\n\n#define HOTKEY_ID_SHOW_TIME 100 // Hotkey ID to show current time\n#define HOTKEY_ID_COUNT_UP 101 // Hotkey ID for count up timer\n#define HOTKEY_ID_COUNTDOWN 102 // Hotkey ID for countdown timer\n#define HOTKEY_ID_QUICK_COUNTDOWN1 103 // Hotkey ID for quick countdown 1\n#define HOTKEY_ID_QUICK_COUNTDOWN2 104 // Hotkey ID for quick countdown 2\n#define HOTKEY_ID_QUICK_COUNTDOWN3 105 // Hotkey ID for quick countdown 3\n#define HOTKEY_ID_POMODORO 106 // Hotkey ID for pomodoro timer\n#define HOTKEY_ID_TOGGLE_VISIBILITY 107 // Hotkey ID for hide/show\n#define HOTKEY_ID_EDIT_MODE 108 // Hotkey ID for edit mode\n#define HOTKEY_ID_PAUSE_RESUME 109 // Hotkey ID for pause/resume\n#define HOTKEY_ID_RESTART_TIMER 110 // Hotkey ID for restart timer\n#define HOTKEY_ID_CUSTOM_COUNTDOWN 111 // Hotkey ID for custom countdown\n\n/**\n * @brief Register global hotkeys\n * @param hwnd Window handle\n * \n * Reads and registers global hotkey settings from the configuration file for quickly switching between\n * displaying current time, count up timer, and default countdown.\n * If a hotkey is already registered, it will be unregistered before re-registering.\n * If a hotkey cannot be registered (possibly because it's being used by another program),\n * that hotkey setting will be set to none and the configuration file will be updated.\n * \n * @return BOOL Whether at least one hotkey was successfully registered\n */\nBOOL RegisterGlobalHotkeys(HWND hwnd) {\n // First unregister all previously registered hotkeys\n UnregisterGlobalHotkeys(hwnd);\n \n // Use new function to read hotkey configuration\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n BOOL success = FALSE;\n BOOL configChanged = FALSE;\n \n // Register show current time hotkey\n if (showTimeHotkey != 0) {\n BYTE vk = LOBYTE(showTimeHotkey); // Virtual key code\n BYTE mod = HIBYTE(showTimeHotkey); // Modifier keys\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n showTimeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register count up hotkey\n if (countUpHotkey != 0) {\n BYTE vk = LOBYTE(countUpHotkey);\n BYTE mod = HIBYTE(countUpHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNT_UP, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countUpHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register countdown hotkey\n if (countdownHotkey != 0) {\n BYTE vk = LOBYTE(countdownHotkey);\n BYTE mod = HIBYTE(countdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 1 hotkey\n if (quickCountdown1Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown1Hotkey);\n BYTE mod = HIBYTE(quickCountdown1Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown1Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 2 hotkey\n if (quickCountdown2Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown2Hotkey);\n BYTE mod = HIBYTE(quickCountdown2Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown2Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 3 hotkey\n if (quickCountdown3Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown3Hotkey);\n BYTE mod = HIBYTE(quickCountdown3Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown3Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pomodoro hotkey\n if (pomodoroHotkey != 0) {\n BYTE vk = LOBYTE(pomodoroHotkey);\n BYTE mod = HIBYTE(pomodoroHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_POMODORO, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pomodoroHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register hide/show window hotkey\n if (toggleVisibilityHotkey != 0) {\n BYTE vk = LOBYTE(toggleVisibilityHotkey);\n BYTE mod = HIBYTE(toggleVisibilityHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n toggleVisibilityHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register edit mode hotkey\n if (editModeHotkey != 0) {\n BYTE vk = LOBYTE(editModeHotkey);\n BYTE mod = HIBYTE(editModeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n editModeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pause/resume hotkey\n if (pauseResumeHotkey != 0) {\n BYTE vk = LOBYTE(pauseResumeHotkey);\n BYTE mod = HIBYTE(pauseResumeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pauseResumeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register restart timer hotkey\n if (restartTimerHotkey != 0) {\n BYTE vk = LOBYTE(restartTimerHotkey);\n BYTE mod = HIBYTE(restartTimerHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n restartTimerHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // If any hotkey registration failed, update config file\n if (configChanged) {\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n \n // Check if custom countdown hotkey was cleared, if so, update config\n if (customCountdownHotkey == 0) {\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", \"None\");\n }\n }\n \n // Added after reading hotkey configuration\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Added after registering countdown hotkey\n // Register custom countdown hotkey\n if (customCountdownHotkey != 0) {\n BYTE vk = LOBYTE(customCountdownHotkey);\n BYTE mod = HIBYTE(customCountdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n customCountdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n return success;\n}\n\n/**\n * @brief Unregister global hotkeys\n * @param hwnd Window handle\n * \n * Unregister all previously registered global hotkeys.\n */\nvoid UnregisterGlobalHotkeys(HWND hwnd) {\n // Unregister all previously registered hotkeys\n UnregisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNT_UP);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3);\n UnregisterHotKey(hwnd, HOTKEY_ID_POMODORO);\n UnregisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY);\n UnregisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE);\n UnregisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME);\n UnregisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER);\n UnregisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN);\n}\n\n/**\n * @brief Main window message processing callback function\n * @param hwnd Window handle\n * @param msg Message type\n * @param wp Message parameter (specific meaning depends on message type)\n * @param lp Message parameter (specific meaning depends on message type)\n * @return LRESULT Message processing result\n * \n * Handles all message events for the main window, including:\n * - Window creation/destruction\n * - Mouse events (dragging, wheel scaling)\n * - Timer events\n * - System tray interaction\n * - Drawing events\n * - Menu command processing\n */\nLRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)\n{\n static char time_text[50];\n UINT uID;\n UINT uMouseMsg;\n\n // Check if this is a TaskbarCreated message\n // TaskbarCreated is a system message broadcasted when Windows Explorer restarts\n // At this time all tray icons are destroyed and need to be recreated by applications\n // Handling this message solves the issue of the tray icon disappearing while the program is still running\n if (msg == WM_TASKBARCREATED) {\n // Explorer has restarted, need to recreate the tray icon\n RecreateTaskbarIcon(hwnd, GetModuleHandle(NULL));\n return 0;\n }\n\n switch(msg)\n {\n case WM_CREATE: {\n // Register global hotkeys when window is created\n RegisterGlobalHotkeys(hwnd);\n HandleWindowCreate(hwnd);\n break;\n }\n\n case WM_SETCURSOR: {\n // When in edit mode, always use default arrow cursor\n if (CLOCK_EDIT_MODE && LOWORD(lp) == HTCLIENT) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE; // Indicates we've handled this message\n }\n \n // Also use default arrow cursor when handling tray icon operations\n if (LOWORD(lp) == HTCLIENT || msg == CLOCK_WM_TRAYICON) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE;\n }\n break;\n }\n\n case WM_LBUTTONDOWN: {\n StartDragWindow(hwnd);\n break;\n }\n\n case WM_LBUTTONUP: {\n EndDragWindow(hwnd);\n break;\n }\n\n case WM_MOUSEWHEEL: {\n int delta = GET_WHEEL_DELTA_WPARAM(wp);\n HandleScaleWindow(hwnd, delta);\n break;\n }\n\n case WM_MOUSEMOVE: {\n if (HandleDragWindow(hwnd)) {\n return 0;\n }\n break;\n }\n\n case WM_PAINT: {\n PAINTSTRUCT ps;\n BeginPaint(hwnd, &ps);\n HandleWindowPaint(hwnd, &ps);\n EndPaint(hwnd, &ps);\n break;\n }\n case WM_TIMER: {\n if (HandleTimerEvent(hwnd, wp)) {\n break;\n }\n break;\n }\n case WM_DESTROY: {\n // Unregister global hotkeys when window is destroyed\n UnregisterGlobalHotkeys(hwnd);\n HandleWindowDestroy(hwnd);\n return 0;\n }\n case CLOCK_WM_TRAYICON: {\n HandleTrayIconMessage(hwnd, (UINT)wp, (UINT)lp);\n break;\n }\n case WM_COMMAND: {\n // Handle preset color options (ID: 201 ~ 201+COLOR_OPTIONS_COUNT-1)\n if (LOWORD(wp) >= 201 && LOWORD(wp) < 201 + COLOR_OPTIONS_COUNT) {\n int colorIndex = LOWORD(wp) - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n // Update current color\n strncpy(CLOCK_TEXT_COLOR, COLOR_OPTIONS[colorIndex].hexColor, \n sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n \n // Write to config file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n \n // Redraw window to show new color\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n WORD cmd = LOWORD(wp);\n switch (cmd) {\n case 101: { \n if (CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_LAST_TIME_UPDATE = 0;\n KillTimer(hwnd, 1);\n }\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n // Handle quick time options (102-102+MAX_TIME_OPTIONS)\n case 102: case 103: case 104: case 105: case 106:\n case 107: case 108: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n int index = cmd - 102;\n if (index >= 0 && index < time_options_count) {\n int minutes = time_options[index];\n if (minutes > 0) {\n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = minutes * 60; // Convert to seconds\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n break;\n }\n // Handle exit option\n case 109: {\n ExitProgram(hwnd);\n break;\n }\n case CLOCK_IDC_MODIFY_TIME_OPTIONS: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_SHORTCUT_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_SHORTCUT_DIALOG);\n\n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n // If input is empty or contains only spaces, exit the loop\n if (inputText[0] == '\\0' || isAllSpaces) {\n break;\n }\n\n char* token = strtok(inputText, \" \");\n char options[256] = {0};\n int valid = 1;\n int count = 0;\n \n while (token && count < MAX_TIME_OPTIONS) {\n int num = atoi(token);\n if (num <= 0) {\n valid = 0;\n break;\n }\n \n if (count > 0) {\n strcat(options, \",\");\n }\n strcat(options, token);\n count++;\n token = strtok(NULL, \" \");\n }\n\n if (valid && count > 0) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigTimeOptions(options);\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd,\n GetLocalizedString(\n L\"请输入用空格分隔的数字\\n\"\n L\"例如: 25 10 5\",\n L\"Enter numbers separated by spaces\\n\"\n L\"Example: 25 10 5\"),\n GetLocalizedString(L\"无效输入\", L\"Invalid Input\"), \n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_MODIFY_DEFAULT_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_STARTUP_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_STARTUP_DIALOG);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case 200: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // First, stop all timers to ensure no timer events will be processed\n KillTimer(hwnd, 1);\n \n // Unregister all global hotkeys to ensure they don't remain active after reset\n UnregisterGlobalHotkeys(hwnd);\n \n // Fully reset timer state - critical part\n // Import all timer state variables that need to be reset\n extern int elapsed_time; // from main.c\n extern int countdown_elapsed_time; // from timer.c\n extern int countup_elapsed_time; // from timer.c\n extern BOOL message_shown; // from main.c \n extern BOOL countdown_message_shown;// from timer.c\n extern BOOL countup_message_shown; // from timer.c\n \n // Import high-precision timer initialization function from timer.c\n extern BOOL InitializeHighPrecisionTimer(void);\n extern void ResetTimer(void); // Use a dedicated reset function\n extern void ReadNotificationMessagesConfig(void); // Read notification message configuration\n \n // Reset all timer state variables - order matters!\n CLOCK_TOTAL_TIME = 25 * 60; // 1. First set total time to 25 minutes\n elapsed_time = 0; // 2. Reset elapsed_time in main.c\n countdown_elapsed_time = 0; // 3. Reset countdown_elapsed_time in timer.c\n countup_elapsed_time = 0; // 4. Reset countup_elapsed_time in timer.c\n message_shown = FALSE; // 5. Reset message status\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set timer state to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Call the dedicated timer reset function - this is crucial!\n // This function reinitializes the high-precision timer and resets all timing states\n ResetTimer();\n \n // Reset UI state\n CLOCK_EDIT_MODE = FALSE;\n SetClickThrough(hwnd, TRUE);\n SendMessage(hwnd, WM_SETREDRAW, FALSE, 0);\n \n // Reset file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n \n // Default language initialization\n AppLanguage defaultLanguage;\n LANGID langId = GetUserDefaultUILanguage();\n WORD primaryLangId = PRIMARYLANGID(langId);\n WORD subLangId = SUBLANGID(langId);\n \n switch (primaryLangId) {\n case LANG_CHINESE:\n defaultLanguage = (subLangId == SUBLANG_CHINESE_SIMPLIFIED) ? \n APP_LANG_CHINESE_SIMP : APP_LANG_CHINESE_TRAD;\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n break;\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n break;\n }\n \n if (CURRENT_LANGUAGE != defaultLanguage) {\n CURRENT_LANGUAGE = defaultLanguage;\n }\n \n // Delete and recreate the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure the file is closed and deleted\n FILE* test = fopen(config_path, \"r\");\n if (test) {\n fclose(test);\n remove(config_path);\n }\n \n // Recreate default configuration\n CreateDefaultConfig(config_path);\n \n // Reread the configuration\n ReadConfig();\n \n // Ensure notification messages are reread\n ReadNotificationMessagesConfig();\n \n // Restore default font\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0) { \n LoadFontFromResource(hInstance, fontResources[i].resourceId);\n break;\n }\n }\n \n // Reset window scale\n CLOCK_WINDOW_SCALE = 1.0f;\n CLOCK_FONT_SCALE_FACTOR = 1.0f;\n \n // Recalculate window size\n HDC hdc = GetDC(hwnd);\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE, \n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, FONT_INTERNAL_NAME\n );\n HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);\n \n char time_text[50];\n FormatTime(CLOCK_TOTAL_TIME, time_text);\n SIZE textSize;\n GetTextExtentPoint32(hdc, time_text, strlen(time_text), &textSize);\n \n SelectObject(hdc, hOldFont);\n DeleteObject(hFont);\n ReleaseDC(hwnd, hdc);\n \n // Set default scale based on screen height\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n float defaultScale = (screenHeight * 0.03f) / 20.0f;\n CLOCK_WINDOW_SCALE = defaultScale;\n CLOCK_FONT_SCALE_FACTOR = defaultScale;\n \n // Reset window position\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n textSize.cx * defaultScale, textSize.cy * defaultScale,\n SWP_NOZORDER | SWP_NOACTIVATE\n );\n \n // Ensure window is visible\n ShowWindow(hwnd, SW_SHOW);\n \n // Restart the timer - ensure it's started after all states are reset\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n SendMessage(hwnd, WM_SETREDRAW, TRUE, 0);\n RedrawWindow(hwnd, NULL, NULL, \n RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);\n \n // Reregister default hotkeys\n RegisterGlobalHotkeys(hwnd);\n \n break;\n }\n case CLOCK_IDM_TIMER_PAUSE_RESUME: {\n PauseResumeTimer(hwnd);\n break;\n }\n case CLOCK_IDM_TIMER_RESTART: {\n // Close all notification windows\n CloseAllNotifications();\n RestartTimer(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE: {\n SetLanguage(APP_LANG_CHINESE_SIMP);\n WriteConfigLanguage(APP_LANG_CHINESE_SIMP);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE_TRAD: {\n SetLanguage(APP_LANG_CHINESE_TRAD);\n WriteConfigLanguage(APP_LANG_CHINESE_TRAD);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_ENGLISH: {\n SetLanguage(APP_LANG_ENGLISH);\n WriteConfigLanguage(APP_LANG_ENGLISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_SPANISH: {\n SetLanguage(APP_LANG_SPANISH);\n WriteConfigLanguage(APP_LANG_SPANISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_FRENCH: {\n SetLanguage(APP_LANG_FRENCH);\n WriteConfigLanguage(APP_LANG_FRENCH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_GERMAN: {\n SetLanguage(APP_LANG_GERMAN);\n WriteConfigLanguage(APP_LANG_GERMAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_RUSSIAN: {\n SetLanguage(APP_LANG_RUSSIAN);\n WriteConfigLanguage(APP_LANG_RUSSIAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_PORTUGUESE: {\n SetLanguage(APP_LANG_PORTUGUESE);\n WriteConfigLanguage(APP_LANG_PORTUGUESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_JAPANESE: {\n SetLanguage(APP_LANG_JAPANESE);\n WriteConfigLanguage(APP_LANG_JAPANESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_KOREAN: {\n SetLanguage(APP_LANG_KOREAN);\n WriteConfigLanguage(APP_LANG_KOREAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_ABOUT:\n ShowAboutDialog(hwnd);\n return 0;\n case CLOCK_IDM_TOPMOST: {\n // Toggle the topmost state in configuration\n BOOL newTopmost = !CLOCK_WINDOW_TOPMOST;\n \n // If in edit mode, just update the stored state but don't apply it yet\n if (CLOCK_EDIT_MODE) {\n // Update the configuration and saved state only\n PREVIOUS_TOPMOST_STATE = newTopmost;\n CLOCK_WINDOW_TOPMOST = newTopmost;\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n } else {\n // Not in edit mode, apply it immediately\n SetWindowTopmost(hwnd, newTopmost);\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n }\n break;\n }\n case CLOCK_IDM_COUNTDOWN_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = FALSE; // Switch to countdown mode\n }\n \n // Reset the countdown timer\n extern void ResetTimer(void);\n ResetTimer();\n \n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDC_EDIT_MODE: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n } else {\n StartEditMode(hwnd);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n case CLOCK_IDC_CUSTOMIZE_LEFT: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n char hex_color[10];\n snprintf(hex_color, sizeof(hex_color), \"#%02X%02X%02X\", \n GetRValue(color), GetGValue(color), GetBValue(color));\n WriteConfigColor(hex_color);\n ReadConfig();\n }\n break;\n }\n case CLOCK_IDC_FONT_RECMONO: {\n WriteConfigFont(\"RecMonoCasual Nerd Font Mono Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DEPARTURE: {\n WriteConfigFont(\"DepartureMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_TERMINESS: {\n WriteConfigFont(\"Terminess Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PINYON_SCRIPT: {\n WriteConfigFont(\"Pinyon Script Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ARBUTUS: {\n WriteConfigFont(\"Arbutus Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_BERKSHIRE: {\n WriteConfigFont(\"Berkshire Swash Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CAVEAT: {\n WriteConfigFont(\"Caveat Brush Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CREEPSTER: {\n WriteConfigFont(\"Creepster Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DOTO: { \n WriteConfigFont(\"Doto ExtraBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FOLDIT: {\n WriteConfigFont(\"Foldit SemiBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FREDERICKA: {\n WriteConfigFont(\"Fredericka the Great Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FRIJOLE: {\n WriteConfigFont(\"Frijole Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_GWENDOLYN: {\n WriteConfigFont(\"Gwendolyn Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_HANDJET: {\n WriteConfigFont(\"Handjet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_INKNUT: {\n WriteConfigFont(\"Inknut Antiqua Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARD: {\n WriteConfigFont(\"Jacquard 12 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARDA: {\n WriteConfigFont(\"Jacquarda Bastarda 9 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KAVOON: {\n WriteConfigFont(\"Kavoon Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE: {\n WriteConfigFont(\"Kumar One Outline Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE: {\n WriteConfigFont(\"Kumar One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LAKKI_REDDY: {\n WriteConfigFont(\"Lakki Reddy Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LICORICE: {\n WriteConfigFont(\"Licorice Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MA_SHAN_ZHENG: {\n WriteConfigFont(\"Ma Shan Zheng Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MOIRAI_ONE: {\n WriteConfigFont(\"Moirai One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MYSTERY_QUEST: {\n WriteConfigFont(\"Mystery Quest Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_NOTO_NASTALIQ: {\n WriteConfigFont(\"Noto Nastaliq Urdu Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIEDRA: {\n WriteConfigFont(\"Piedra Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIXELIFY: {\n WriteConfigFont(\"Pixelify Sans Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PRESS_START: {\n WriteConfigFont(\"Press Start 2P Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BUBBLES: {\n WriteConfigFont(\"Rubik Bubbles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BURNED: {\n WriteConfigFont(\"Rubik Burned Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_GLITCH: {\n WriteConfigFont(\"Rubik Glitch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_MARKER_HATCH: {\n WriteConfigFont(\"Rubik Marker Hatch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_PUDDLES: {\n WriteConfigFont(\"Rubik Puddles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_VINYL: {\n WriteConfigFont(\"Rubik Vinyl Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_WET_PAINT: {\n WriteConfigFont(\"Rubik Wet Paint Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUGE_BOOGIE: {\n WriteConfigFont(\"Ruge Boogie Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SEVILLANA: {\n WriteConfigFont(\"Sevillana Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SILKSCREEN: {\n WriteConfigFont(\"Silkscreen Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_STICK: {\n WriteConfigFont(\"Stick Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_UNDERDOG: {\n WriteConfigFont(\"Underdog Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_WALLPOET: {\n WriteConfigFont(\"Wallpoet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_YESTERYEAR: {\n WriteConfigFont(\"Yesteryear Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ZCOOL_KUAILE: {\n WriteConfigFont(\"ZCOOL KuaiLe Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PROFONT: {\n WriteConfigFont(\"ProFont IIx Nerd Font Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DADDYTIME: {\n WriteConfigFont(\"DaddyTimeMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDM_SHOW_CURRENT_TIME: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_SHOW_CURRENT_TIME = !CLOCK_SHOW_CURRENT_TIME;\n if (CLOCK_SHOW_CURRENT_TIME) {\n ShowWindow(hwnd, SW_SHOW); \n \n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1); \n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0; // Ensure total time is reset\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n SetTimer(hwnd, 1, 100, NULL); // Reduce interval to 100ms for higher refresh rate\n } else {\n KillTimer(hwnd, 1); \n // When canceling showing current time, fully reset state instead of restoring previous state\n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0;\n message_shown = 0; // Reset message shown state\n // Set timer with longer interval because second-level updates are no longer needed\n SetTimer(hwnd, 1, 1000, NULL); \n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_24HOUR_FORMAT: { \n CLOCK_USE_24HOUR = !CLOCK_USE_24HOUR;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_SHOW_SECONDS: { \n CLOCK_SHOW_SECONDS = !CLOCK_SHOW_SECONDS;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_RECENT_FILE_1:\n case CLOCK_IDM_RECENT_FILE_2:\n case CLOCK_IDM_RECENT_FILE_3:\n case CLOCK_IDM_RECENT_FILE_4:\n case CLOCK_IDM_RECENT_FILE_5: {\n int index = cmd - CLOCK_IDM_RECENT_FILE_1;\n if (index < CLOCK_RECENT_FILES_COUNT) {\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[index].path, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(CLOCK_RECENT_FILES[index].path);\n \n // Step 2: Update the recent files list (move this file to the top)\n SaveRecentFile(CLOCK_RECENT_FILES[index].path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n \n // Clear invalid file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n \n // Remove this file from the recent files list\n for (int i = index; i < CLOCK_RECENT_FILES_COUNT - 1; i++) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i + 1];\n }\n CLOCK_RECENT_FILES_COUNT--;\n \n // Update recent files list in the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n }\n }\n break;\n }\n case CLOCK_IDM_BROWSE_FILE: {\n wchar_t szFile[MAX_PATH] = {0};\n \n OPENFILENAMEW ofn = {0};\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile) / sizeof(wchar_t);\n ofn.lpstrFilter = L\"所有文件\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n \n if (GetOpenFileNameW(&ofn)) {\n // Convert wide character path to UTF-8 to save in the configuration file\n char utf8Path[MAX_PATH * 3] = {0}; // Larger buffer to accommodate UTF-8 encoding\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n \n if (GetFileAttributesW(szFile) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case CLOCK_IDC_TIMEOUT_BROWSE: {\n OPENFILENAMEW ofn;\n wchar_t szFile[MAX_PATH] = L\"\";\n \n ZeroMemory(&ofn, sizeof(ofn));\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile);\n ofn.lpstrFilter = L\"All Files (*.*)\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n\n if (GetOpenFileNameW(&ofn)) {\n char utf8Path[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, \n utf8Path, \n sizeof(utf8Path), \n NULL, NULL);\n \n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n }\n break;\n }\n case CLOCK_IDM_COUNT_UP: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_COUNT_UP = !CLOCK_COUNT_UP;\n if (CLOCK_COUNT_UP) {\n ShowWindow(hwnd, SW_SHOW);\n \n elapsed_time = 0;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (!CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = TRUE;\n \n // Ensure the timer starts from 0 every time it switches to count-up mode\n countup_elapsed_time = 0;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n } else {\n // Already in count-up mode, so toggle pause/run state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n // Reset the count-up counter\n extern void ResetTimer(void);\n ResetTimer();\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDC_SET_COUNTDOWN_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n \n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n \n CLOCK_DEFAULT_START_TIME = total_seconds;\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_START_SHOW_TIME: {\n WriteConfigStartupMode(\"SHOW_TIME\");\n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_CHECKED);\n break;\n }\n case CLOCK_IDC_START_COUNT_UP: {\n WriteConfigStartupMode(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDC_START_NO_DISPLAY: {\n WriteConfigStartupMode(\"NO_DISPLAY\");\n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n case CLOCK_IDC_AUTO_START: {\n BOOL isEnabled = IsAutoStartEnabled();\n if (isEnabled) {\n if (RemoveShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_UNCHECKED);\n }\n } else {\n if (CreateShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_CHECKED);\n }\n }\n break;\n }\n case CLOCK_IDC_COLOR_VALUE: {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_COLOR_DIALOG), \n hwnd, \n (DLGPROC)ColorDlgProc);\n break;\n }\n case CLOCK_IDC_COLOR_PANEL: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case CLOCK_IDM_POMODORO_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n if (!IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_SHOW);\n }\n \n // Reset timer state\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // Set work time\n CLOCK_TOTAL_TIME = POMODORO_WORK_TIME;\n \n // Initialize Pomodoro phase\n extern void InitializePomodoro(void);\n InitializePomodoro();\n \n // Save original timeout action\n TimeoutActionType originalAction = CLOCK_TIMEOUT_ACTION;\n \n // Force set to show message\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n \n // Start the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Reset message state\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_POMODORO_WORK:\n case CLOCK_IDM_POMODORO_BREAK:\n case CLOCK_IDM_POMODORO_LBREAK:\n // Keep original menu item ID handling\n {\n int selectedIndex = 0;\n if (LOWORD(wp) == CLOCK_IDM_POMODORO_WORK) {\n selectedIndex = 0;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_BREAK) {\n selectedIndex = 1;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_LBREAK) {\n selectedIndex = 2;\n }\n \n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n break;\n\n // Also handle new dynamic ID range\n case 600: case 601: case 602: case 603: case 604:\n case 605: case 606: case 607: case 608: case 609:\n // Handle Pomodoro time setting options (dynamic ID range)\n {\n // Calculate the selected option index\n int selectedIndex = LOWORD(wp) - CLOCK_IDM_POMODORO_TIME_BASE;\n \n if (selectedIndex >= 0 && selectedIndex < POMODORO_TIMES_COUNT) {\n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n }\n break;\n case CLOCK_IDM_POMODORO_LOOP_COUNT:\n ShowPomodoroLoopDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Call ResetTimer to reset the timer state\n extern void ResetTimer(void);\n ResetTimer();\n \n // If currently in Pomodoro mode, reset related states\n if (CLOCK_TOTAL_TIME == POMODORO_WORK_TIME || \n CLOCK_TOTAL_TIME == POMODORO_SHORT_BREAK || \n CLOCK_TOTAL_TIME == POMODORO_LONG_BREAK) {\n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDM_TIMEOUT_SHOW_TIME: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n WriteConfigTimeoutAction(\"SHOW_TIME\");\n break;\n }\n case CLOCK_IDM_TIMEOUT_COUNT_UP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n WriteConfigTimeoutAction(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDM_SHOW_MESSAGE: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n break;\n }\n case CLOCK_IDM_LOCK_SCREEN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n WriteConfigTimeoutAction(\"LOCK\");\n break;\n }\n case CLOCK_IDM_SHUTDOWN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHUTDOWN;\n WriteConfigTimeoutAction(\"SHUTDOWN\");\n break;\n }\n case CLOCK_IDM_RESTART: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RESTART;\n WriteConfigTimeoutAction(\"RESTART\");\n break;\n }\n case CLOCK_IDM_SLEEP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n WriteConfigTimeoutAction(\"SLEEP\");\n break;\n }\n case CLOCK_IDM_RUN_COMMAND: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n WriteConfigTimeoutAction(\"RUN_COMMAND\");\n break;\n }\n case CLOCK_IDM_HTTP_REQUEST: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n WriteConfigTimeoutAction(\"HTTP_REQUEST\");\n break;\n }\n case CLOCK_IDM_CHECK_UPDATE: {\n // Call async update check function - non-silent mode\n CheckForUpdateAsync(hwnd, FALSE);\n break;\n }\n case CLOCK_IDM_OPEN_WEBSITE:\n // Don't set action type immediately, wait for dialog result\n ShowWebsiteDialog(hwnd);\n break;\n \n case CLOCK_IDM_CURRENT_WEBSITE:\n ShowWebsiteDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_COMBINATION:\n ShowPomodoroComboDialog(hwnd);\n break;\n case CLOCK_IDM_NOTIFICATION_CONTENT: {\n ShowNotificationMessagesDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_DISPLAY: {\n ShowNotificationDisplayDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_SETTINGS: {\n ShowNotificationSettingsDialog(hwnd);\n break;\n }\n case CLOCK_IDM_HOTKEY_SETTINGS: {\n ShowHotkeySettingsDialog(hwnd);\n // Register/reregister global hotkeys\n RegisterGlobalHotkeys(hwnd);\n break;\n }\n case CLOCK_IDM_HELP: {\n OpenUserGuide();\n break;\n }\n case CLOCK_IDM_SUPPORT: {\n OpenSupportPage();\n break;\n }\n case CLOCK_IDM_FEEDBACK: {\n OpenFeedbackPage();\n break;\n }\n }\n break;\n\nrefresh_window:\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case WM_WINDOWPOSCHANGED: {\n if (CLOCK_EDIT_MODE) {\n SaveWindowSettings(hwnd);\n }\n break;\n }\n case WM_RBUTTONUP: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_MEASUREITEM:\n {\n LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT)lp;\n if (lpmis->CtlType == ODT_MENU) {\n lpmis->itemHeight = 25;\n lpmis->itemWidth = 100;\n return TRUE;\n }\n return FALSE;\n }\n case WM_DRAWITEM:\n {\n LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT)lp;\n if (lpdis->CtlType == ODT_MENU) {\n int colorIndex = lpdis->itemID - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n const char* hexColor = COLOR_OPTIONS[colorIndex].hexColor;\n int r, g, b;\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n \n HBRUSH hBrush = CreateSolidBrush(RGB(r, g, b));\n HPEN hPen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n \n HGDIOBJ oldBrush = SelectObject(lpdis->hDC, hBrush);\n HGDIOBJ oldPen = SelectObject(lpdis->hDC, hPen);\n \n Rectangle(lpdis->hDC, lpdis->rcItem.left, lpdis->rcItem.top,\n lpdis->rcItem.right, lpdis->rcItem.bottom);\n \n SelectObject(lpdis->hDC, oldPen);\n SelectObject(lpdis->hDC, oldBrush);\n DeleteObject(hPen);\n DeleteObject(hBrush);\n \n if (lpdis->itemState & ODS_SELECTED) {\n DrawFocusRect(lpdis->hDC, &lpdis->rcItem);\n }\n \n return TRUE;\n }\n }\n return FALSE;\n }\n case WM_MENUSELECT: {\n UINT menuItem = LOWORD(wp);\n UINT flags = HIWORD(wp);\n HMENU hMenu = (HMENU)lp;\n\n if (!(flags & MF_POPUP) && hMenu != NULL) {\n int colorIndex = menuItem - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n strncpy(PREVIEW_COLOR, COLOR_OPTIONS[colorIndex].hexColor, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (fontResources[i].menuId == menuItem) {\n strncpy(PREVIEW_FONT_NAME, fontResources[i].fontName, 99);\n PREVIEW_FONT_NAME[99] = '\\0';\n \n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, 99);\n PREVIEW_INTERNAL_NAME[99] = '\\0';\n char* dot = strrchr(PREVIEW_INTERNAL_NAME, '.');\n if (dot) *dot = '\\0';\n \n LoadFontByName((HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), \n fontResources[i].fontName);\n \n IS_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n \n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n } else if (flags & MF_POPUP) {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n break;\n }\n case WM_EXITMENULOOP: {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case WM_RBUTTONDOWN: {\n if (GetKeyState(VK_CONTROL) & 0x8000) {\n // Toggle edit mode\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Entering edit mode\n SetClickThrough(hwnd, FALSE);\n } else {\n // Exiting edit mode\n SetClickThrough(hwnd, TRUE);\n SaveWindowSettings(hwnd); // Save settings when exiting edit mode\n WriteConfigColor(CLOCK_TEXT_COLOR); // Save the current color to config\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n break;\n }\n case WM_CLOSE: {\n SaveWindowSettings(hwnd); // Save window settings before closing\n DestroyWindow(hwnd); // Close the window\n break;\n }\n case WM_LBUTTONDBLCLK: {\n if (!CLOCK_EDIT_MODE) {\n // Enter edit mode\n StartEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_HOTKEY: {\n // WM_HOTKEY message's lp contains key information\n if (wp == HOTKEY_ID_SHOW_TIME) {\n ToggleShowTimeMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNT_UP) {\n StartCountUp(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNTDOWN) {\n StartDefaultCountDown(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_CUSTOM_COUNTDOWN) {\n // Check if the input dialog already exists\n if (g_hwndInputDialog != NULL && IsWindow(g_hwndInputDialog)) {\n // The dialog already exists, close it\n SendMessage(g_hwndInputDialog, WM_CLOSE, 0, 0);\n return 0;\n }\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Show input dialog to set countdown\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Clear input text\n memset(inputText, 0, sizeof(inputText));\n \n // Show input dialog\n INT_PTR result = DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), \n hwnd, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n \n // If the dialog has input and was confirmed\n if (inputText[0] != '\\0') {\n // Check if input is valid\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Set countdown state\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n \n // Switch to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Stop and restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN1) {\n // Start quick countdown 1\n StartQuickCountdown1(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN2) {\n // Start quick countdown 2\n StartQuickCountdown2(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN3) {\n // Start quick countdown 3\n StartQuickCountdown3(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_POMODORO) {\n // Start Pomodoro timer\n StartPomodoroTimer(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_TOGGLE_VISIBILITY) {\n // Hide/show window\n if (IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_HIDE);\n } else {\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n }\n return 0;\n } else if (wp == HOTKEY_ID_EDIT_MODE) {\n // Enter edit mode\n ToggleEditMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_PAUSE_RESUME) {\n // Pause/resume timer\n TogglePauseResume(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_RESTART_TIMER) {\n // Close all notification windows\n CloseAllNotifications();\n // Restart current timer\n RestartCurrentTimer(hwnd);\n return 0;\n }\n break;\n }\n // Handle reregistration message after hotkey settings change\n case WM_APP+1: {\n // Only reregister hotkeys, do not open dialog\n RegisterGlobalHotkeys(hwnd);\n return 0;\n }\n default:\n return DefWindowProc(hwnd, msg, wp, lp);\n }\n return 0;\n}\n\n// External variable declarations\nextern int CLOCK_DEFAULT_START_TIME;\nextern int countdown_elapsed_time;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern int CLOCK_TOTAL_TIME;\n\n// Remove menu items\nvoid RemoveMenuItems(HMENU hMenu, int count);\n\n// Add menu item\nvoid AddMenuItem(HMENU hMenu, UINT id, const char* text, BOOL isEnabled);\n\n// Modify menu item text\nvoid ModifyMenuItemText(HMENU hMenu, UINT id, const char* text);\n\n/**\n * @brief Toggle show current time mode\n * @param hwnd Window handle\n */\nvoid ToggleShowTimeMode(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // If not currently in show current time mode, then enable it\n // If already in show current time mode, do nothing (don't turn it off)\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Switch to show current time mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n \n // Reset the timer to ensure the update frequency is correct\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 100, NULL); // Use 100ms update frequency to keep the time display smooth\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n }\n // Already in show current time mode, do nothing\n}\n\n/**\n * @brief Start count up timer\n * @param hwnd Window handle\n */\nvoid StartCountUp(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Declare external variables\n extern int countup_elapsed_time;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Reset count up counter\n countup_elapsed_time = 0;\n \n // Set to count up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start default countdown\n * @param hwnd Window handle\n */\nvoid StartDefaultCountDown(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Set mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n if (CLOCK_DEFAULT_START_TIME > 0) {\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n } else {\n // If no default countdown is set, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, 101, 0);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start Pomodoro timer\n * @param hwnd Window handle\n */\nvoid StartPomodoroTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // If it was previously in show current time mode, stop the old timer\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n }\n \n // Use the Pomodoro menu item command to start the Pomodoro timer\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDM_POMODORO_START, 0);\n}\n\n/**\n * @brief Toggle edit mode\n * @param hwnd Window handle\n */\nvoid ToggleEditMode(HWND hwnd) {\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Record the current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If not currently topmost, set it to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure the window is visible and in the foreground\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n } else {\n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, TRUE);\n \n // If it was not topmost before, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Save window settings and color settings\n SaveWindowSettings(hwnd);\n WriteConfigColor(CLOCK_TEXT_COLOR);\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Pause/resume timer\n * @param hwnd Window handle\n */\nvoid TogglePauseResume(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart the current timer\n * @param hwnd Window handle\n */\nvoid RestartCurrentTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Variables imported from main.c\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Reset message shown state to allow notification and sound to be played again when timer ends\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n if (CLOCK_COUNT_UP) {\n // Reset count up timer\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else {\n // Reset countdown timer\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n }\n CLOCK_IS_PAUSED = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Start quick countdown 1\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown1(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there is at least one preset time option\n if (time_options_count > 0) {\n CLOCK_TOTAL_TIME = time_options[0] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are no preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 2\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown2(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least two preset time options\n if (time_options_count > 1) {\n CLOCK_TOTAL_TIME = time_options[1] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 3\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown3(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least three preset time options\n if (time_options_count > 2) {\n CLOCK_TOTAL_TIME = time_options[2] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n"], ["/Catime/src/log.c", "/**\n * @file log.c\n * @brief Log recording functionality implementation\n * \n * Implements logging functionality, including file writing, error code retrieval, etc.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/log.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n\n// Add check for ARM64 macro\n#ifndef PROCESSOR_ARCHITECTURE_ARM64\n#define PROCESSOR_ARCHITECTURE_ARM64 12\n#endif\n\n// Log file path\nstatic char LOG_FILE_PATH[MAX_PATH] = {0};\nstatic FILE* logFile = NULL;\nstatic CRITICAL_SECTION logCS;\n\n// Log level string representations\nstatic const char* LOG_LEVEL_STRINGS[] = {\n \"DEBUG\",\n \"INFO\",\n \"WARNING\",\n \"ERROR\",\n \"FATAL\"\n};\n\n/**\n * @brief Get operating system version information\n * \n * Use Windows API to get operating system version, version number, build and other information\n */\nstatic void LogSystemInformation(void) {\n // Get system information\n SYSTEM_INFO si;\n GetNativeSystemInfo(&si);\n \n // Use RtlGetVersion to get system version more accurately, because GetVersionEx was changed in newer Windows versions\n typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);\n HMODULE hNtdll = GetModuleHandleW(L\"ntdll.dll\");\n \n DWORD major = 0, minor = 0, build = 0;\n BOOL isWorkstation = TRUE;\n BOOL isServer = FALSE;\n \n if (hNtdll) {\n RtlGetVersionPtr pRtlGetVersion = (RtlGetVersionPtr)GetProcAddress(hNtdll, \"RtlGetVersion\");\n if (pRtlGetVersion) {\n RTL_OSVERSIONINFOW rovi = { 0 };\n rovi.dwOSVersionInfoSize = sizeof(rovi);\n if (pRtlGetVersion(&rovi) == 0) { // STATUS_SUCCESS = 0\n major = rovi.dwMajorVersion;\n minor = rovi.dwMinorVersion;\n build = rovi.dwBuildNumber;\n }\n }\n }\n \n // If the above method fails, try the method below\n if (major == 0) {\n OSVERSIONINFOEXA osvi;\n ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA));\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA);\n \n typedef LONG (WINAPI* PRTLGETVERSION)(OSVERSIONINFOEXW*);\n PRTLGETVERSION pRtlGetVersion;\n pRtlGetVersion = (PRTLGETVERSION)GetProcAddress(GetModuleHandle(TEXT(\"ntdll.dll\")), \"RtlGetVersion\");\n \n if (pRtlGetVersion) {\n pRtlGetVersion((OSVERSIONINFOEXW*)&osvi);\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n // Finally try using GetVersionExA, although it may not be accurate\n if (GetVersionExA((OSVERSIONINFOA*)&osvi)) {\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n WriteLog(LOG_LEVEL_WARNING, \"Unable to get operating system version information\");\n }\n }\n }\n \n // Detect specific Windows version\n const char* windowsVersion = \"Unknown version\";\n \n // Determine specific version based on version number\n if (major == 10) {\n if (build >= 22000) {\n windowsVersion = \"Windows 11\";\n } else {\n windowsVersion = \"Windows 10\";\n }\n } else if (major == 6) {\n if (minor == 3) {\n windowsVersion = \"Windows 8.1\";\n } else if (minor == 2) {\n windowsVersion = \"Windows 8\";\n } else if (minor == 1) {\n windowsVersion = \"Windows 7\";\n } else if (minor == 0) {\n windowsVersion = \"Windows Vista\";\n }\n } else if (major == 5) {\n if (minor == 2) {\n windowsVersion = \"Windows Server 2003\";\n if (isWorkstation && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {\n windowsVersion = \"Windows XP Professional x64\";\n }\n } else if (minor == 1) {\n windowsVersion = \"Windows XP\";\n } else if (minor == 0) {\n windowsVersion = \"Windows 2000\";\n }\n }\n \n WriteLog(LOG_LEVEL_INFO, \"Operating System: %s (%d.%d) Build %d %s\", \n windowsVersion,\n major, minor, \n build, \n isWorkstation ? \"Workstation\" : \"Server\");\n \n // CPU architecture\n const char* arch;\n switch (si.wProcessorArchitecture) {\n case PROCESSOR_ARCHITECTURE_AMD64:\n arch = \"x64 (AMD64)\";\n break;\n case PROCESSOR_ARCHITECTURE_INTEL:\n arch = \"x86 (Intel)\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM:\n arch = \"ARM\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM64:\n arch = \"ARM64\";\n break;\n default:\n arch = \"Unknown\";\n break;\n }\n WriteLog(LOG_LEVEL_INFO, \"CPU Architecture: %s\", arch);\n \n // System memory information\n MEMORYSTATUSEX memInfo;\n memInfo.dwLength = sizeof(MEMORYSTATUSEX);\n if (GlobalMemoryStatusEx(&memInfo)) {\n WriteLog(LOG_LEVEL_INFO, \"Physical Memory: %.2f GB / %.2f GB (%d%% used)\", \n (memInfo.ullTotalPhys - memInfo.ullAvailPhys) / (1024.0 * 1024 * 1024), \n memInfo.ullTotalPhys / (1024.0 * 1024 * 1024),\n memInfo.dwMemoryLoad);\n }\n \n // Don't get screen resolution information as it's not accurate and not necessary for debugging\n \n // Check if UAC is enabled\n BOOL uacEnabled = FALSE;\n HANDLE hToken;\n if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {\n TOKEN_ELEVATION_TYPE elevationType;\n DWORD dwSize;\n if (GetTokenInformation(hToken, TokenElevationType, &elevationType, sizeof(elevationType), &dwSize)) {\n uacEnabled = (elevationType != TokenElevationTypeDefault);\n }\n CloseHandle(hToken);\n }\n WriteLog(LOG_LEVEL_INFO, \"UAC Status: %s\", uacEnabled ? \"Enabled\" : \"Disabled\");\n \n // Check if running as administrator\n BOOL isAdmin = FALSE;\n SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;\n PSID AdministratorsGroup;\n if (AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup)) {\n if (CheckTokenMembership(NULL, AdministratorsGroup, &isAdmin)) {\n WriteLog(LOG_LEVEL_INFO, \"Administrator Privileges: %s\", isAdmin ? \"Yes\" : \"No\");\n }\n FreeSid(AdministratorsGroup);\n }\n}\n\n/**\n * @brief Get log file path\n * \n * Build log filename based on config file path\n * \n * @param logPath Log path buffer\n * @param size Buffer size\n */\nstatic void GetLogFilePath(char* logPath, size_t size) {\n char configPath[MAX_PATH] = {0};\n \n // Get directory containing config file\n GetConfigPath(configPath, MAX_PATH);\n \n // Determine config file directory\n char* lastSeparator = strrchr(configPath, '\\\\');\n if (lastSeparator) {\n size_t dirLen = lastSeparator - configPath + 1;\n \n // Copy directory part\n strncpy(logPath, configPath, dirLen);\n \n // Use simple log filename\n _snprintf_s(logPath + dirLen, size - dirLen, _TRUNCATE, \"Catime_Logs.log\");\n } else {\n // If config directory can't be determined, use current directory\n _snprintf_s(logPath, size, _TRUNCATE, \"Catime_Logs.log\");\n }\n}\n\nBOOL InitializeLogSystem(void) {\n InitializeCriticalSection(&logCS);\n \n GetLogFilePath(LOG_FILE_PATH, MAX_PATH);\n \n // Open file in write mode each startup, which clears existing content\n logFile = fopen(LOG_FILE_PATH, \"w\");\n if (!logFile) {\n // Failed to create log file\n return FALSE;\n }\n \n // Record log system initialization information\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n // First record software version\n WriteLog(LOG_LEVEL_INFO, \"Catime Version: %s\", CATIME_VERSION);\n // Then record system environment information (before any possible errors)\n WriteLog(LOG_LEVEL_INFO, \"-----------------System Information-----------------\");\n LogSystemInformation();\n WriteLog(LOG_LEVEL_INFO, \"-----------------Application Information-----------------\");\n WriteLog(LOG_LEVEL_INFO, \"Log system initialization complete, Catime started\");\n \n return TRUE;\n}\n\nvoid WriteLog(LogLevel level, const char* format, ...) {\n if (!logFile) {\n return;\n }\n \n EnterCriticalSection(&logCS);\n \n // Get current time\n time_t now;\n struct tm local_time;\n char timeStr[32] = {0};\n \n time(&now);\n localtime_s(&local_time, &now);\n strftime(timeStr, sizeof(timeStr), \"%Y-%m-%d %H:%M:%S\", &local_time);\n \n // Write log header\n fprintf(logFile, \"[%s] [%s] \", timeStr, LOG_LEVEL_STRINGS[level]);\n \n // Format and write log content\n va_list args;\n va_start(args, format);\n vfprintf(logFile, format, args);\n va_end(args);\n \n // New line\n fprintf(logFile, \"\\n\");\n \n // Flush buffer immediately to ensure logs are saved even if program crashes\n fflush(logFile);\n \n LeaveCriticalSection(&logCS);\n}\n\nvoid GetLastErrorDescription(DWORD errorCode, char* buffer, int bufferSize) {\n if (!buffer || bufferSize <= 0) {\n return;\n }\n \n LPSTR messageBuffer = NULL;\n DWORD size = FormatMessageA(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | \n FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL,\n errorCode,\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n (LPSTR)&messageBuffer,\n 0, NULL);\n \n if (size > 0) {\n // Remove trailing newlines\n if (size >= 2 && messageBuffer[size-2] == '\\r' && messageBuffer[size-1] == '\\n') {\n messageBuffer[size-2] = '\\0';\n }\n \n strncpy_s(buffer, bufferSize, messageBuffer, _TRUNCATE);\n LocalFree(messageBuffer);\n } else {\n _snprintf_s(buffer, bufferSize, _TRUNCATE, \"Unknown error (code: %lu)\", errorCode);\n }\n}\n\n// Signal handler function - used to handle various C standard signals\nvoid SignalHandler(int signal) {\n char errorMsg[256] = {0};\n \n switch (signal) {\n case SIGFPE:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Floating point exception\");\n break;\n case SIGILL:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Illegal instruction\");\n break;\n case SIGSEGV:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Segmentation fault/memory access error\");\n break;\n case SIGTERM:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Termination signal\");\n break;\n case SIGABRT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Abnormal termination/abort\");\n break;\n case SIGINT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"User interrupt\");\n break;\n default:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Unknown signal\");\n break;\n }\n \n // Record exception information\n if (logFile) {\n fprintf(logFile, \"[FATAL] Fatal signal occurred: %s (signal number: %d)\\n\", \n errorMsg, signal);\n fflush(logFile);\n \n // Close log file\n fclose(logFile);\n logFile = NULL;\n }\n \n // Display error message box\n MessageBox(NULL, \"The program encountered a serious error. Please check the log file for detailed information.\", \"Fatal Error\", MB_ICONERROR | MB_OK);\n \n // Terminate program\n exit(signal);\n}\n\nvoid SetupExceptionHandler(void) {\n // Set up standard C signal handlers\n signal(SIGFPE, SignalHandler); // Floating point exception\n signal(SIGILL, SignalHandler); // Illegal instruction\n signal(SIGSEGV, SignalHandler); // Segmentation fault\n signal(SIGTERM, SignalHandler); // Termination signal\n signal(SIGABRT, SignalHandler); // Abnormal termination\n signal(SIGINT, SignalHandler); // User interrupt\n}\n\n// Call this function when program exits to clean up log resources\nvoid CleanupLogSystem(void) {\n if (logFile) {\n WriteLog(LOG_LEVEL_INFO, \"Catime exited normally\");\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n fclose(logFile);\n logFile = NULL;\n }\n \n DeleteCriticalSection(&logCS);\n}\n"], ["/Catime/src/update_checker.c", "/**\n * @file update_checker.c\n * @brief Minimalist application update check functionality implementation\n * \n * This file implements functions for checking versions, opening browser for downloads, and deleting configuration files.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/language.h\"\n#include \"../include/dialog_language.h\"\n#include \"../resource/resource.h\"\n\n#pragma comment(lib, \"wininet.lib\")\n\n// Update source URL\n#define GITHUB_API_URL \"https://api.github.com/repos/vladelaina/Catime/releases/latest\"\n#define USER_AGENT \"Catime Update Checker\"\n\n// Version information structure definition\ntypedef struct {\n const char* currentVersion;\n const char* latestVersion;\n const char* downloadUrl;\n} UpdateVersionInfo;\n\n// Function declarations\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\n/**\n * @brief Compare version numbers\n * @param version1 First version string\n * @param version2 Second version string\n * @return Returns 1 if version1 > version2, 0 if equal, -1 if version1 < version2\n */\nint CompareVersions(const char* version1, const char* version2) {\n LOG_DEBUG(\"Comparing versions: '%s' vs '%s'\", version1, version2);\n \n int major1, minor1, patch1;\n int major2, minor2, patch2;\n \n // Parse version numbers\n sscanf(version1, \"%d.%d.%d\", &major1, &minor1, &patch1);\n sscanf(version2, \"%d.%d.%d\", &major2, &minor2, &patch2);\n \n LOG_DEBUG(\"Parsed version1: %d.%d.%d, version2: %d.%d.%d\", major1, minor1, patch1, major2, minor2, patch2);\n \n // Compare major version\n if (major1 > major2) return 1;\n if (major1 < major2) return -1;\n \n // Compare minor version\n if (minor1 > minor2) return 1;\n if (minor1 < minor2) return -1;\n \n // Compare patch version\n if (patch1 > patch2) return 1;\n if (patch1 < patch2) return -1;\n \n return 0;\n}\n\n/**\n * @brief Parse JSON response to get latest version and download URL\n */\nBOOL ParseLatestVersionFromJson(const char* jsonResponse, char* latestVersion, size_t maxLen, \n char* downloadUrl, size_t urlMaxLen) {\n LOG_DEBUG(\"Starting to parse JSON response, extracting version information\");\n \n // Find version number\n const char* tagNamePos = strstr(jsonResponse, \"\\\"tag_name\\\":\");\n if (!tagNamePos) {\n LOG_ERROR(\"JSON parsing failed: tag_name field not found\");\n return FALSE;\n }\n \n const char* firstQuote = strchr(tagNamePos + 11, '\\\"');\n if (!firstQuote) return FALSE;\n \n const char* secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy version number\n size_t versionLen = secondQuote - (firstQuote + 1);\n if (versionLen >= maxLen) versionLen = maxLen - 1;\n \n strncpy(latestVersion, firstQuote + 1, versionLen);\n latestVersion[versionLen] = '\\0';\n \n // If version starts with 'v', remove it\n if (latestVersion[0] == 'v' || latestVersion[0] == 'V') {\n memmove(latestVersion, latestVersion + 1, versionLen);\n }\n \n // Find download URL\n const char* downloadUrlPos = strstr(jsonResponse, \"\\\"browser_download_url\\\":\");\n if (!downloadUrlPos) {\n LOG_ERROR(\"JSON parsing failed: browser_download_url field not found\");\n return FALSE;\n }\n \n firstQuote = strchr(downloadUrlPos + 22, '\\\"');\n if (!firstQuote) return FALSE;\n \n secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy download URL\n size_t urlLen = secondQuote - (firstQuote + 1);\n if (urlLen >= urlMaxLen) urlLen = urlMaxLen - 1;\n \n strncpy(downloadUrl, firstQuote + 1, urlLen);\n downloadUrl[urlLen] = '\\0';\n \n return TRUE;\n}\n\n/**\n * @brief Exit message dialog procedure\n */\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Get localized exit text\n const wchar_t* exitText = GetLocalizedString(L\"程序即将退出\", L\"The application will exit now\");\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, exitText);\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, L\"\"); // Clear version text\n \n // Set OK button text\n const wchar_t* okText = GetLocalizedString(L\"确定\", L\"OK\");\n SetDlgItemTextW(hwndDlg, IDOK, okText);\n \n // Hide Yes/No buttons, only show OK button\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_SHOW);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"Catime - 更新提示\", L\"Catime - Update Notice\");\n SetWindowTextW(hwndDlg, titleText);\n \n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display custom exit message dialog\n */\nvoid ShowExitMessageDialog(HWND hwnd) {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n ExitMsgDlgProc);\n}\n\n/**\n * @brief Update dialog procedure\n */\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static UpdateVersionInfo* versionInfo = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Save version information\n versionInfo = (UpdateVersionInfo*)lParam;\n \n // Format display text\n if (versionInfo) {\n // Convert ASCII version numbers to Unicode\n wchar_t currentVersionW[64] = {0};\n wchar_t newVersionW[64] = {0};\n \n // Convert version numbers to wide characters\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->currentVersion, -1, \n currentVersionW, sizeof(currentVersionW)/sizeof(wchar_t));\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->latestVersion, -1, \n newVersionW, sizeof(newVersionW)/sizeof(wchar_t));\n \n // Use pre-formatted strings instead of trying to format ourselves\n wchar_t displayText[256];\n \n // Get localized version text (pre-formatted)\n const wchar_t* currentVersionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n const wchar_t* newVersionText = GetLocalizedString(L\"新版本:\", L\"New version:\");\n\n // Manually build formatted string\n StringCbPrintfW(displayText, sizeof(displayText),\n L\"%s %s\\n%s %s\",\n currentVersionText, currentVersionW,\n newVersionText, newVersionW);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, displayText);\n \n // Set button text\n const wchar_t* yesText = GetLocalizedString(L\"是\", L\"Yes\");\n const wchar_t* noText = GetLocalizedString(L\"否\", L\"No\");\n \n // Explicitly set button text, not relying on dialog resource\n SetDlgItemTextW(hwndDlg, IDYES, yesText);\n SetDlgItemTextW(hwndDlg, IDNO, noText);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"发现新版本\", L\"Update Available\");\n SetWindowTextW(hwndDlg, titleText);\n \n // Hide exit text and OK button, show Yes/No buttons\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, L\"\");\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_HIDE);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDNO);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update notification dialog\n */\nint ShowUpdateNotification(HWND hwnd, const char* currentVersion, const char* latestVersion, const char* downloadUrl) {\n // Create version info structure\n UpdateVersionInfo versionInfo;\n versionInfo.currentVersion = currentVersion;\n versionInfo.latestVersion = latestVersion;\n versionInfo.downloadUrl = downloadUrl;\n \n // Display custom dialog\n return DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n UpdateDlgProc, \n (LPARAM)&versionInfo);\n}\n\n/**\n * @brief Update error dialog procedure\n */\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Get error message text\n const wchar_t* errorMsg = (const wchar_t*)lParam;\n if (errorMsg) {\n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_ERROR_TEXT, errorMsg);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update error dialog\n */\nvoid ShowUpdateErrorDialog(HWND hwnd, const wchar_t* errorMsg) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_ERROR_DIALOG), \n hwnd, \n UpdateErrorDlgProc, \n (LPARAM)errorMsg);\n}\n\n/**\n * @brief No update required dialog procedure\n */\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_NO_UPDATE_DIALOG);\n \n // Get current version information\n const char* currentVersion = (const char*)lParam;\n if (currentVersion) {\n // Get localized basic text\n const wchar_t* baseText = GetDialogLocalizedString(IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT);\n if (!baseText) {\n // If localized text not found, use default text\n baseText = L\"You are already using the latest version!\";\n }\n \n // Get localized \"Current version\" text\n const wchar_t* versionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n \n // Create complete message including version number\n wchar_t fullMessage[256];\n StringCbPrintfW(fullMessage, sizeof(fullMessage),\n L\"%s\\n%s %hs\", baseText, versionText, currentVersion);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_NO_UPDATE_TEXT, fullMessage);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display no update required dialog\n * @param hwnd Parent window handle\n * @param currentVersion Current version number\n */\nvoid ShowNoUpdateDialog(HWND hwnd, const char* currentVersion) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_NO_UPDATE_DIALOG), \n hwnd, \n NoUpdateDlgProc, \n (LPARAM)currentVersion);\n}\n\n/**\n * @brief Open browser to download update and exit program\n */\nBOOL OpenBrowserForUpdateAndExit(const char* url, HWND hwnd) {\n // Open browser\n HINSTANCE hInstance = ShellExecuteA(hwnd, \"open\", url, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)hInstance <= 32) {\n // Failed to open browser\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法打开浏览器下载更新\", L\"Could not open browser to download update\"));\n return FALSE;\n }\n \n LOG_INFO(\"Successfully opened browser, preparing to exit program\");\n \n // Prompt user\n wchar_t message[512];\n StringCbPrintfW(message, sizeof(message),\n L\"即将退出程序\");\n \n LOG_INFO(\"Sending exit message to main window\");\n // Use custom dialog to display exit message\n ShowExitMessageDialog(hwnd);\n \n // Exit program\n PostMessage(hwnd, WM_CLOSE, 0, 0);\n return TRUE;\n}\n\n/**\n * @brief General update check function\n */\nvoid CheckForUpdateInternal(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Starting update check process, silent mode: %s\", silentCheck ? \"yes\" : \"no\");\n \n // Create Internet session\n LOG_INFO(\"Attempting to create Internet session\");\n HINTERNET hInternet = InternetOpenA(USER_AGENT, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);\n if (!hInternet) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to create Internet session, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法创建Internet连接\", L\"Could not create Internet connection\"));\n }\n return;\n }\n LOG_INFO(\"Internet session created successfully\");\n \n // Connect to update API\n LOG_INFO(\"Attempting to connect to GitHub API: %s\", GITHUB_API_URL);\n HINTERNET hConnect = InternetOpenUrlA(hInternet, GITHUB_API_URL, NULL, 0, \n INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, 0);\n if (!hConnect) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to connect to GitHub API, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n InternetCloseHandle(hInternet);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法连接到更新服务器\", L\"Could not connect to update server\"));\n }\n return;\n }\n LOG_INFO(\"Successfully connected to GitHub API\");\n \n // Allocate buffer\n LOG_INFO(\"Allocating memory buffer for API response\");\n char* buffer = (char*)malloc(8192);\n if (!buffer) {\n LOG_ERROR(\"Memory allocation failed, could not allocate buffer for API response\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n \n // Read response\n LOG_INFO(\"Starting to read response data from API\");\n DWORD bytesRead = 0;\n DWORD totalBytes = 0;\n size_t bufferSize = 8192;\n \n while (InternetReadFile(hConnect, buffer + totalBytes, \n bufferSize - totalBytes - 1, &bytesRead) && bytesRead > 0) {\n LOG_DEBUG(\"Read %lu bytes of data, accumulated %lu bytes\", bytesRead, totalBytes + bytesRead);\n totalBytes += bytesRead;\n if (totalBytes >= bufferSize - 256) {\n size_t newSize = bufferSize * 2;\n char* newBuffer = (char*)realloc(buffer, newSize);\n if (!newBuffer) {\n // Fix: If realloc fails, free the original buffer and abort\n LOG_ERROR(\"Failed to reallocate buffer, current size: %zu bytes\", bufferSize);\n free(buffer);\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n LOG_DEBUG(\"Buffer expanded, new size: %zu bytes\", newSize);\n buffer = newBuffer;\n bufferSize = newSize;\n }\n }\n \n buffer[totalBytes] = '\\0';\n LOG_INFO(\"Successfully read API response, total %lu bytes of data\", totalBytes);\n \n // Close connection\n LOG_INFO(\"Closing Internet connection\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n \n // Parse version and download URL\n LOG_INFO(\"Starting to parse API response, extracting version info and download URL\");\n char latestVersion[32] = {0};\n char downloadUrl[256] = {0};\n if (!ParseLatestVersionFromJson(buffer, latestVersion, sizeof(latestVersion), \n downloadUrl, sizeof(downloadUrl))) {\n LOG_ERROR(\"Failed to parse version information, response may not be valid JSON format\");\n free(buffer);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法解析版本信息\", L\"Could not parse version information\"));\n }\n return;\n }\n LOG_INFO(\"Successfully parsed version information, GitHub latest version: %s, download URL: %s\", latestVersion, downloadUrl);\n \n free(buffer);\n \n // Get current version\n const char* currentVersion = CATIME_VERSION;\n LOG_INFO(\"Current application version: %s\", currentVersion);\n \n // Compare versions\n LOG_INFO(\"Comparing version numbers: current version %s vs. latest version %s\", currentVersion, latestVersion);\n int versionCompare = CompareVersions(latestVersion, currentVersion);\n if (versionCompare > 0) {\n // New version available\n LOG_INFO(\"New version found! Current: %s, Available update: %s\", currentVersion, latestVersion);\n int response = ShowUpdateNotification(hwnd, currentVersion, latestVersion, downloadUrl);\n LOG_INFO(\"Update prompt dialog result: %s\", response == IDYES ? \"User agreed to update\" : \"User declined update\");\n \n if (response == IDYES) {\n LOG_INFO(\"User chose to update now, preparing to open browser and exit program\");\n OpenBrowserForUpdateAndExit(downloadUrl, hwnd);\n }\n } else if (!silentCheck) {\n // Already using latest version\n LOG_INFO(\"Current version %s is already the latest, no update needed\", currentVersion);\n \n // Use localized strings instead of building complete message\n ShowNoUpdateDialog(hwnd, currentVersion);\n } else {\n LOG_INFO(\"Silent check mode: Current version %s is already the latest, no prompt shown\", currentVersion);\n }\n \n LOG_INFO(\"Update check process complete\");\n}\n\n/**\n * @brief Check for application updates\n */\nvoid CheckForUpdate(HWND hwnd) {\n CheckForUpdateInternal(hwnd, FALSE);\n}\n\n/**\n * @brief Silently check for application updates\n */\nvoid CheckForUpdateSilent(HWND hwnd, BOOL silentCheck) {\n CheckForUpdateInternal(hwnd, silentCheck);\n} \n"], ["/Catime/src/window.c", "/**\n * @file window.c\n * @brief Window management functionality implementation\n * \n * This file implements the functionality related to application window management,\n * including window creation, position adjustment, transparency, click-through, and drag functionality.\n */\n\n#include \"../include/window.h\"\n#include \"../include/timer.h\"\n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n\n// Forward declaration of WindowProcedure (defined in main.c)\nextern LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\n\n// Add declaration for SetProcessDPIAware function\n#ifndef _INC_WINUSER\n// If not included by windows.h, add SetProcessDPIAware function declaration\nWINUSERAPI BOOL WINAPI SetProcessDPIAware(VOID);\n#endif\n\n// Window size and position variables\nint CLOCK_BASE_WINDOW_WIDTH = 200;\nint CLOCK_BASE_WINDOW_HEIGHT = 100;\nfloat CLOCK_WINDOW_SCALE = 1.0f;\nint CLOCK_WINDOW_POS_X = 100;\nint CLOCK_WINDOW_POS_Y = 100;\n\n// Window state variables\nBOOL CLOCK_EDIT_MODE = FALSE;\nBOOL CLOCK_IS_DRAGGING = FALSE;\nPOINT CLOCK_LAST_MOUSE_POS = {0, 0};\nBOOL CLOCK_WINDOW_TOPMOST = TRUE; // Default topmost\n\n// Text area variables\nRECT CLOCK_TEXT_RECT = {0, 0, 0, 0};\nBOOL CLOCK_TEXT_RECT_VALID = FALSE;\n\n// DWM function pointer type definition\ntypedef HRESULT (WINAPI *pfnDwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);\nstatic pfnDwmEnableBlurBehindWindow _DwmEnableBlurBehindWindow = NULL;\n\n// Window composition attribute type definition\ntypedef enum _WINDOWCOMPOSITIONATTRIB {\n WCA_UNDEFINED = 0,\n WCA_NCRENDERING_ENABLED = 1,\n WCA_NCRENDERING_POLICY = 2,\n WCA_TRANSITIONS_FORCEDISABLED = 3,\n WCA_ALLOW_NCPAINT = 4,\n WCA_CAPTION_BUTTON_BOUNDS = 5,\n WCA_NONCLIENT_RTL_LAYOUT = 6,\n WCA_FORCE_ICONIC_REPRESENTATION = 7,\n WCA_EXTENDED_FRAME_BOUNDS = 8,\n WCA_HAS_ICONIC_BITMAP = 9,\n WCA_THEME_ATTRIBUTES = 10,\n WCA_NCRENDERING_EXILED = 11,\n WCA_NCADORNMENTINFO = 12,\n WCA_EXCLUDED_FROM_LIVEPREVIEW = 13,\n WCA_VIDEO_OVERLAY_ACTIVE = 14,\n WCA_FORCE_ACTIVEWINDOW_APPEARANCE = 15,\n WCA_DISALLOW_PEEK = 16,\n WCA_CLOAK = 17,\n WCA_CLOAKED = 18,\n WCA_ACCENT_POLICY = 19,\n WCA_FREEZE_REPRESENTATION = 20,\n WCA_EVER_UNCLOAKED = 21,\n WCA_VISUAL_OWNER = 22,\n WCA_HOLOGRAPHIC = 23,\n WCA_EXCLUDED_FROM_DDA = 24,\n WCA_PASSIVEUPDATEMODE = 25,\n WCA_USEDARKMODECOLORS = 26,\n WCA_LAST = 27\n} WINDOWCOMPOSITIONATTRIB;\n\ntypedef struct _WINDOWCOMPOSITIONATTRIBDATA {\n WINDOWCOMPOSITIONATTRIB Attrib;\n PVOID pvData;\n SIZE_T cbData;\n} WINDOWCOMPOSITIONATTRIBDATA;\n\nWINUSERAPI BOOL WINAPI SetWindowCompositionAttribute(HWND hwnd, WINDOWCOMPOSITIONATTRIBDATA* pData);\n\ntypedef enum _ACCENT_STATE {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5\n} ACCENT_STATE;\n\ntypedef struct _ACCENT_POLICY {\n ACCENT_STATE AccentState;\n DWORD AccentFlags;\n DWORD GradientColor;\n DWORD AnimationId;\n} ACCENT_POLICY;\n\nvoid SetClickThrough(HWND hwnd, BOOL enable) {\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n // Clear previously set related styles\n exStyle &= ~WS_EX_TRANSPARENT;\n \n if (enable) {\n // Set click-through\n exStyle |= WS_EX_TRANSPARENT;\n \n // If the window is a layered window, ensure it properly handles mouse input\n if (exStyle & WS_EX_LAYERED) {\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n }\n } else {\n // Ensure window receives all mouse input\n if (exStyle & WS_EX_LAYERED) {\n // Maintain transparency but allow receiving mouse input\n SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);\n }\n }\n \n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Update window to apply new style\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n}\n\nBOOL InitDWMFunctions() {\n HMODULE hDwmapi = LoadLibraryA(\"dwmapi.dll\");\n if (hDwmapi) {\n _DwmEnableBlurBehindWindow = (pfnDwmEnableBlurBehindWindow)GetProcAddress(hDwmapi, \"DwmEnableBlurBehindWindow\");\n return _DwmEnableBlurBehindWindow != NULL;\n }\n return FALSE;\n}\n\nvoid SetBlurBehind(HWND hwnd, BOOL enable) {\n if (enable) {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_ENABLE_BLURBEHIND;\n policy.AccentFlags = 0;\n policy.GradientColor = (180 << 24) | 0x00202020; // Changed to dark gray background with 180 transparency\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = TRUE;\n bb.hRgnBlur = NULL;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n } else {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_DISABLED;\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = FALSE;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n }\n}\n\nvoid AdjustWindowPosition(HWND hwnd, BOOL forceOnScreen) {\n if (!forceOnScreen) {\n // Do not force window to be on screen, return directly\n return;\n }\n \n // Original code to ensure window is on screen\n RECT rect;\n GetWindowRect(hwnd, &rect);\n \n int screenWidth = GetSystemMetrics(SM_CXSCREEN);\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n \n int width = rect.right - rect.left;\n int height = rect.bottom - rect.top;\n \n int x = rect.left;\n int y = rect.top;\n \n // Ensure window right edge doesn't exceed screen\n if (x + width > screenWidth) {\n x = screenWidth - width;\n }\n \n // Ensure window bottom edge doesn't exceed screen\n if (y + height > screenHeight) {\n y = screenHeight - height;\n }\n \n // Ensure window left edge doesn't exceed screen\n if (x < 0) {\n x = 0;\n }\n \n // Ensure window top edge doesn't exceed screen\n if (y < 0) {\n y = 0;\n }\n \n // If window position needs adjustment, move the window\n if (x != rect.left || y != rect.top) {\n SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n }\n}\n\nextern void GetConfigPath(char* path, size_t size);\nextern void WriteConfigEditMode(const char* mode);\n\nvoid SaveWindowSettings(HWND hwnd) {\n if (!hwnd) return;\n\n RECT rect;\n if (!GetWindowRect(hwnd, &rect)) return;\n \n CLOCK_WINDOW_POS_X = rect.left;\n CLOCK_WINDOW_POS_Y = rect.top;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n size_t buffer_size = 8192; \n char *config = malloc(buffer_size);\n char *new_config = malloc(buffer_size);\n if (!config || !new_config) {\n if (config) free(config);\n if (new_config) free(new_config);\n fclose(fp);\n return;\n }\n \n config[0] = new_config[0] = '\\0';\n char line[256];\n size_t total_len = 0;\n \n while (fgets(line, sizeof(line), fp)) {\n size_t line_len = strlen(line);\n if (total_len + line_len >= buffer_size - 1) {\n size_t new_size = buffer_size * 2;\n char *temp_config = realloc(config, new_size);\n char *temp_new_config = realloc(new_config, new_size);\n \n if (!temp_config || !temp_new_config) {\n free(config);\n free(new_config);\n fclose(fp);\n return;\n }\n \n config = temp_config;\n new_config = temp_new_config;\n buffer_size = new_size;\n }\n strcat(config, line);\n total_len += line_len;\n }\n fclose(fp);\n \n char *start = config;\n char *end = config + strlen(config);\n BOOL has_window_scale = FALSE;\n size_t new_config_len = 0;\n \n while (start < end) {\n char *newline = strchr(start, '\\n');\n if (!newline) newline = end;\n \n char temp[256] = {0};\n size_t line_len = newline - start;\n if (line_len >= sizeof(temp)) line_len = sizeof(temp) - 1;\n strncpy(temp, start, line_len);\n \n if (strncmp(temp, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len, \n buffer_size - new_config_len, \n \"CLOCK_WINDOW_POS_X=%d\\n\", CLOCK_WINDOW_POS_X);\n } else if (strncmp(temp, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"CLOCK_WINDOW_POS_Y=%d\\n\", CLOCK_WINDOW_POS_Y);\n } else if (strncmp(temp, \"WINDOW_SCALE=\", 13) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n has_window_scale = TRUE;\n } else {\n size_t remaining = buffer_size - new_config_len;\n if (remaining > line_len + 1) {\n strncpy(new_config + new_config_len, start, line_len);\n new_config_len += line_len;\n new_config[new_config_len++] = '\\n';\n }\n }\n \n start = newline + 1;\n if (start > end) break;\n }\n \n if (!has_window_scale && buffer_size - new_config_len > 50) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n }\n \n if (new_config_len < buffer_size) {\n new_config[new_config_len] = '\\0';\n } else {\n new_config[buffer_size - 1] = '\\0';\n }\n \n fp = fopen(config_path, \"w\");\n if (fp) {\n fputs(new_config, fp);\n fclose(fp);\n }\n \n free(config);\n free(new_config);\n}\n\nvoid LoadWindowSettings(HWND hwnd) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n line[strcspn(line, \"\\n\")] = 0;\n \n if (strncmp(line, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n CLOCK_WINDOW_POS_X = atoi(line + 19);\n } else if (strncmp(line, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n CLOCK_WINDOW_POS_Y = atoi(line + 19);\n } else if (strncmp(line, \"WINDOW_SCALE=\", 13) == 0) {\n CLOCK_WINDOW_SCALE = atof(line + 13);\n CLOCK_FONT_SCALE_FACTOR = CLOCK_WINDOW_SCALE;\n }\n }\n fclose(fp);\n \n // Apply position from config file directly, without additional adjustments\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, \n CLOCK_WINDOW_POS_Y,\n (int)(CLOCK_BASE_WINDOW_WIDTH * CLOCK_WINDOW_SCALE),\n (int)(CLOCK_BASE_WINDOW_HEIGHT * CLOCK_WINDOW_SCALE),\n SWP_NOZORDER\n );\n \n // Don't call AdjustWindowPosition to avoid overriding user settings\n}\n\nBOOL HandleMouseWheel(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n // Remove original position calculation logic, directly use window center as scaling reference point\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n // Use window center as scaling reference\n float relativeX = 0.5f;\n float relativeY = 0.5f;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings after resizing\n SaveWindowSettings(hwnd);\n }\n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleMouseMove(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update the position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nHWND CreateMainWindow(HINSTANCE hInstance, int nCmdShow) {\n // Window class registration\n WNDCLASS wc = {0};\n wc.lpfnWndProc = WindowProcedure;\n wc.hInstance = hInstance;\n wc.lpszClassName = \"CatimeWindow\";\n \n if (!RegisterClass(&wc)) {\n MessageBox(NULL, \"Window Registration Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n // Set extended style\n DWORD exStyle = WS_EX_LAYERED | WS_EX_TOOLWINDOW;\n \n // If not in topmost mode, add WS_EX_NOACTIVATE extended style\n if (!CLOCK_WINDOW_TOPMOST) {\n exStyle |= WS_EX_NOACTIVATE;\n }\n \n // Create window\n HWND hwnd = CreateWindowEx(\n exStyle,\n \"CatimeWindow\",\n \"Catime\",\n WS_POPUP,\n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n CLOCK_BASE_WINDOW_WIDTH, CLOCK_BASE_WINDOW_HEIGHT,\n NULL,\n NULL,\n hInstance,\n NULL\n );\n\n if (!hwnd) {\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n EnableWindow(hwnd, TRUE);\n SetFocus(hwnd);\n\n // Set window transparency\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n\n // Set blur effect\n SetBlurBehind(hwnd, FALSE);\n\n // Initialize tray icon\n InitTrayIcon(hwnd, hInstance);\n\n // Show window\n ShowWindow(hwnd, nCmdShow);\n UpdateWindow(hwnd);\n\n // Set window position and parent based on topmost status\n if (CLOCK_WINDOW_TOPMOST) {\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n } else {\n // Find desktop window and set as parent\n HWND hProgman = FindWindow(\"Progman\", NULL);\n if (hProgman != NULL) {\n // Try to find the real desktop window\n HWND hDesktop = hProgman;\n \n // Look for WorkerW window (common in Win10+)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n \n // Set as child window of desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, set to bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n\n return hwnd;\n}\n\nfloat CLOCK_FONT_SCALE_FACTOR = 1.0f;\nint CLOCK_BASE_FONT_SIZE = 24;\n\nBOOL InitializeApplication(HINSTANCE hInstance) {\n // Set DPI awareness mode to Per-Monitor DPI Aware to properly handle scaling when moving window between displays with different DPIs\n // Use newer API SetProcessDpiAwarenessContext if available, otherwise fallback to older APIs\n \n // Define DPI awareness related constants and types\n #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);\n #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n #endif\n \n // Define PROCESS_DPI_AWARENESS enum\n typedef enum {\n PROCESS_DPI_UNAWARE = 0,\n PROCESS_SYSTEM_DPI_AWARE = 1,\n PROCESS_PER_MONITOR_DPI_AWARE = 2\n } PROCESS_DPI_AWARENESS;\n \n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n typedef BOOL(WINAPI* SetProcessDpiAwarenessContextFunc)(DPI_AWARENESS_CONTEXT);\n SetProcessDpiAwarenessContextFunc setProcessDpiAwarenessContextFunc =\n (SetProcessDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetProcessDpiAwarenessContext\");\n \n if (setProcessDpiAwarenessContextFunc) {\n // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 is the latest DPI awareness mode\n // It provides better multi-monitor DPI support\n setProcessDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n } else {\n // Try using older API\n HMODULE hShcore = LoadLibraryA(\"shcore.dll\");\n if (hShcore) {\n typedef HRESULT(WINAPI* SetProcessDpiAwarenessFunc)(PROCESS_DPI_AWARENESS);\n SetProcessDpiAwarenessFunc setProcessDpiAwarenessFunc =\n (SetProcessDpiAwarenessFunc)GetProcAddress(hShcore, \"SetProcessDpiAwareness\");\n \n if (setProcessDpiAwarenessFunc) {\n // PROCESS_PER_MONITOR_DPI_AWARE corresponds to per-monitor DPI awareness\n setProcessDpiAwarenessFunc(PROCESS_PER_MONITOR_DPI_AWARE);\n } else {\n // Finally try the oldest API\n SetProcessDPIAware();\n }\n \n FreeLibrary(hShcore);\n } else {\n // If shcore.dll is not available, use the most basic DPI awareness API\n SetProcessDPIAware();\n }\n }\n }\n \n SetConsoleOutputCP(936);\n SetConsoleCP(936);\n\n // Modified initialization order: read config file first, then initialize other features\n ReadConfig();\n UpdateStartupShortcut();\n InitializeDefaultLanguage();\n\n int defaultFontIndex = -1;\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, FONT_FILE_NAME) == 0) {\n defaultFontIndex = i;\n break;\n }\n }\n\n if (defaultFontIndex != -1) {\n LoadFontFromResource(hInstance, fontResources[defaultFontIndex].resourceId);\n }\n\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n \n return TRUE;\n}\n\nBOOL OpenFileDialog(HWND hwnd, char* filePath, DWORD maxPath) {\n OPENFILENAME ofn = { 0 };\n ofn.lStructSize = sizeof(OPENFILENAME);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFilter = \"All Files\\0*.*\\0\";\n ofn.lpstrFile = filePath;\n ofn.nMaxFile = maxPath;\n ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;\n ofn.lpstrDefExt = \"\";\n \n return GetOpenFileName(&ofn);\n}\n\n// Add function to set window topmost state\nvoid SetWindowTopmost(HWND hwnd, BOOL topmost) {\n CLOCK_WINDOW_TOPMOST = topmost;\n \n // Get current window style\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n if (topmost) {\n // Topmost mode: remove no-activate style (if exists), add topmost style\n exStyle &= ~WS_EX_NOACTIVATE;\n \n // If window was previously set as desktop child window, need to restore\n // First set window as top-level window, clear parent window relationship\n SetParent(hwnd, NULL);\n \n // Reset window owner, ensure Z-order is correct\n SetWindowLongPtr(hwnd, GWLP_HWNDPARENT, 0);\n \n // Set window position to top layer, and force window update\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_FRAMECHANGED);\n } else {\n // Non-topmost mode: add no-activate style to prevent window from gaining focus\n exStyle |= WS_EX_NOACTIVATE;\n \n // Set as child window of desktop\n HWND hProgman = FindWindow(\"Progman\", NULL);\n HWND hDesktop = NULL;\n \n // Try to find the real desktop window\n if (hProgman != NULL) {\n // First try using Progman\n hDesktop = hProgman;\n \n // Look for WorkerW window (more common on Win10)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n // Found the real desktop container\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n }\n \n if (hDesktop != NULL) {\n // Set window as child of desktop, this keeps it on the desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, at least place at bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n \n // Apply new window style\n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Force window update\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n \n // Save window topmost setting\n WriteConfigTopmost(topmost ? \"TRUE\" : \"FALSE\");\n}\n"], ["/Catime/src/startup.c", "/**\n * @file startup.c\n * @brief Implementation of auto-start functionality\n * \n * This file implements the application's auto-start related functionality,\n * including checking if auto-start is enabled, creating and deleting auto-start shortcuts.\n */\n\n#include \"../include/startup.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/config.h\"\n#include \"../include/timer.h\"\n\n#ifndef CSIDL_STARTUP\n#define CSIDL_STARTUP 0x0007\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern int countup_elapsed_time;\nextern int CLOCK_DEFAULT_START_TIME;\nextern char CLOCK_STARTUP_MODE[20];\n/// @}\n\n/**\n * @brief Check if the application is set to auto-start at system boot\n * @return BOOL Returns TRUE if auto-start is enabled, otherwise FALSE\n */\nBOOL IsAutoStartEnabled(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n return GetFileAttributesW(startupPath) != INVALID_FILE_ATTRIBUTES;\n }\n return FALSE;\n}\n\n/**\n * @brief Create auto-start shortcut\n * @return BOOL Returns TRUE if creation was successful, otherwise FALSE\n */\nBOOL CreateShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n wchar_t exePath[MAX_PATH];\n IShellLinkW* pShellLink = NULL;\n IPersistFile* pPersistFile = NULL;\n BOOL success = FALSE;\n \n GetModuleFileNameW(NULL, exePath, MAX_PATH);\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n HRESULT hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkW, (void**)&pShellLink);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->SetPath(pShellLink, exePath);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->QueryInterface(pShellLink,\n &IID_IPersistFile,\n (void**)&pPersistFile);\n if (SUCCEEDED(hr)) {\n hr = pPersistFile->lpVtbl->Save(pPersistFile, startupPath, TRUE);\n if (SUCCEEDED(hr)) {\n success = TRUE;\n }\n pPersistFile->lpVtbl->Release(pPersistFile);\n }\n }\n pShellLink->lpVtbl->Release(pShellLink);\n }\n }\n \n return success;\n}\n\n/**\n * @brief Delete auto-start shortcut\n * @return BOOL Returns TRUE if deletion was successful, otherwise FALSE\n */\nBOOL RemoveShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n return DeleteFileW(startupPath);\n }\n return FALSE;\n}\n\n/**\n * @brief Update auto-start shortcut\n * \n * Check if auto-start is enabled, if so, delete the old shortcut and create a new one,\n * ensuring that the auto-start functionality works correctly even if the application location changes.\n * \n * @return BOOL Returns TRUE if update was successful, otherwise FALSE\n */\nBOOL UpdateStartupShortcut(void) {\n // If auto-start is already enabled\n if (IsAutoStartEnabled()) {\n // First delete the existing shortcut\n RemoveShortcut();\n // Create a new shortcut\n return CreateShortcut();\n }\n return TRUE; // Auto-start not enabled, considered successful\n}\n\n/**\n * @brief Apply startup mode settings\n * @param hwnd Window handle\n * \n * Initialize the application's display state according to the startup mode settings in the configuration file\n */\nvoid ApplyStartupMode(HWND hwnd) {\n // Read startup mode from configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", CLOCK_STARTUP_MODE);\n break;\n }\n }\n fclose(configFile);\n \n // Apply startup mode\n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n // Set to count-up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n // Set to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n // Set to no display mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n } else { // Default to countdown mode \"COUNTDOWN\"\n // Set to countdown mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n \n // Read default countdown time\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n \n // If countdown is set, start the timer\n if (CLOCK_TOTAL_TIME > 0) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n"], ["/Catime/src/async_update_checker.c", "/**\n * @file async_update_checker.c\n * @brief Asynchronous application update checking functionality\n */\n\n#include \n#include \n#include \"../include/async_update_checker.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n\ntypedef struct {\n HWND hwnd;\n BOOL silentCheck;\n} UpdateThreadParams;\n\nstatic HANDLE g_hUpdateThread = NULL;\nstatic BOOL g_bUpdateThreadRunning = FALSE;\n\n/**\n * @brief Clean up update check thread resources\n */\nvoid CleanupUpdateThread() {\n LOG_INFO(\"Cleaning up update check thread resources\");\n if (g_hUpdateThread != NULL) {\n DWORD waitResult = WaitForSingleObject(g_hUpdateThread, 1000);\n if (waitResult == WAIT_TIMEOUT) {\n LOG_WARNING(\"Wait for thread end timed out, forcibly closing thread handle\");\n } else if (waitResult == WAIT_OBJECT_0) {\n LOG_INFO(\"Thread has ended normally\");\n } else {\n LOG_WARNING(\"Wait for thread returned unexpected result: %lu\", waitResult);\n }\n\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n g_bUpdateThreadRunning = FALSE;\n LOG_INFO(\"Thread resources have been cleaned up\");\n } else {\n LOG_INFO(\"Update check thread not running, no cleanup needed\");\n }\n}\n\n/**\n * @brief Update check thread function\n * @param param Thread parameters\n */\nunsigned __stdcall UpdateCheckThreadProc(void* param) {\n LOG_INFO(\"Update check thread started\");\n\n UpdateThreadParams* threadParams = (UpdateThreadParams*)param;\n if (!threadParams) {\n LOG_ERROR(\"Thread parameters are null, cannot perform update check\");\n g_bUpdateThreadRunning = FALSE;\n _endthreadex(1);\n return 1;\n }\n\n HWND hwnd = threadParams->hwnd;\n BOOL silentCheck = threadParams->silentCheck;\n\n LOG_INFO(\"Thread parameters parsed successfully, window handle: 0x%p, silent check mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n\n free(threadParams);\n LOG_INFO(\"Thread parameter memory freed\");\n\n LOG_INFO(\"Starting update check\");\n CheckForUpdateSilent(hwnd, silentCheck);\n LOG_INFO(\"Update check completed\");\n\n g_bUpdateThreadRunning = FALSE;\n\n _endthreadex(0);\n return 0;\n}\n\n/**\n * @brief Check for application updates asynchronously\n * @param hwnd Window handle\n * @param silentCheck Whether to perform a silent check\n */\nvoid CheckForUpdateAsync(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Asynchronous update check requested, window handle: 0x%p, silent mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n\n if (g_bUpdateThreadRunning) {\n LOG_INFO(\"Update check thread already running, skipping this check request\");\n return;\n }\n\n if (g_hUpdateThread != NULL) {\n LOG_INFO(\"Found old thread handle, cleaning up...\");\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n LOG_INFO(\"Old thread handle closed\");\n }\n\n LOG_INFO(\"Allocating memory for thread parameters\");\n UpdateThreadParams* threadParams = (UpdateThreadParams*)malloc(sizeof(UpdateThreadParams));\n if (!threadParams) {\n LOG_ERROR(\"Thread parameter memory allocation failed, cannot start update check thread\");\n return;\n }\n\n threadParams->hwnd = hwnd;\n threadParams->silentCheck = silentCheck;\n LOG_INFO(\"Thread parameters set up\");\n\n g_bUpdateThreadRunning = TRUE;\n\n LOG_INFO(\"Preparing to create update check thread\");\n HANDLE hThread = (HANDLE)_beginthreadex(\n NULL,\n 0,\n UpdateCheckThreadProc,\n threadParams,\n 0,\n NULL\n );\n\n if (hThread) {\n LOG_INFO(\"Update check thread created successfully, thread handle: 0x%p\", hThread);\n g_hUpdateThread = hThread;\n } else {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Update check thread creation failed, error code: %lu, error message: %s\", errorCode, errorMsg);\n\n free(threadParams);\n g_bUpdateThreadRunning = FALSE;\n }\n}"], ["/Catime/src/config.c", "/**\n * @file config.c\n * @brief Configuration file management module implementation\n */\n\n#include \"../include/config.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define MAX_POMODORO_TIMES 10\n\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nint POMODORO_TIMES[MAX_POMODORO_TIMES] = {1500, 300, 1500, 600};\nint POMODORO_TIMES_COUNT = 4;\n\nchar CLOCK_TIMEOUT_MESSAGE_TEXT[100] = \"时间到啦!\";\nchar POMODORO_TIMEOUT_MESSAGE_TEXT[100] = \"番茄钟时间到!\";\nchar POMODORO_CYCLE_COMPLETE_TEXT[100] = \"所有番茄钟循环完成!\";\n\nint NOTIFICATION_TIMEOUT_MS = 3000;\nint NOTIFICATION_MAX_OPACITY = 95;\nNotificationType NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\nBOOL NOTIFICATION_DISABLED = FALSE;\n\nchar NOTIFICATION_SOUND_FILE[MAX_PATH] = \"\";\nint NOTIFICATION_SOUND_VOLUME = 100;\n\n/** @brief Read string value from INI file */\nDWORD ReadIniString(const char* section, const char* key, const char* defaultValue,\n char* returnValue, DWORD returnSize, const char* filePath) {\n return GetPrivateProfileStringA(section, key, defaultValue, returnValue, returnSize, filePath);\n}\n\n/** @brief Write string value to INI file */\nBOOL WriteIniString(const char* section, const char* key, const char* value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value, filePath);\n}\n\n/** @brief Read integer value from INI */\nint ReadIniInt(const char* section, const char* key, int defaultValue, \n const char* filePath) {\n return GetPrivateProfileIntA(section, key, defaultValue, filePath);\n}\n\n/** @brief Write integer value to INI file */\nBOOL WriteIniInt(const char* section, const char* key, int value,\n const char* filePath) {\n char valueStr[32];\n snprintf(valueStr, sizeof(valueStr), \"%d\", value);\n return WritePrivateProfileStringA(section, key, valueStr, filePath);\n}\n\n/** @brief Write boolean value to INI file */\nBOOL WriteIniBool(const char* section, const char* key, BOOL value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value ? \"TRUE\" : \"FALSE\", filePath);\n}\n\n/** @brief Read boolean value from INI */\nBOOL ReadIniBool(const char* section, const char* key, BOOL defaultValue, \n const char* filePath) {\n char value[8];\n GetPrivateProfileStringA(section, key, defaultValue ? \"TRUE\" : \"FALSE\", \n value, sizeof(value), filePath);\n return _stricmp(value, \"TRUE\") == 0;\n}\n\n/** @brief Check if configuration file exists */\nBOOL FileExists(const char* filePath) {\n return GetFileAttributesA(filePath) != INVALID_FILE_ATTRIBUTES;\n}\n\n/** @brief Get configuration file path */\nvoid GetConfigPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\config.ini\", appdata_path) >= size) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Create default configuration file */\nvoid CreateDefaultConfig(const char* config_path) {\n // Get system default language ID\n LANGID systemLangID = GetUserDefaultUILanguage();\n int defaultLanguage = APP_LANG_ENGLISH; // Default to English\n const char* langName = \"English\"; // Default language name\n \n // Set default language based on system language ID\n switch (PRIMARYLANGID(systemLangID)) {\n case LANG_CHINESE:\n if (SUBLANGID(systemLangID) == SUBLANG_CHINESE_SIMPLIFIED) {\n defaultLanguage = APP_LANG_CHINESE_SIMP;\n langName = \"Chinese_Simplified\";\n } else {\n defaultLanguage = APP_LANG_CHINESE_TRAD;\n langName = \"Chinese_Traditional\";\n }\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n langName = \"Spanish\";\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n langName = \"French\";\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n langName = \"German\";\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n langName = \"Russian\";\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n langName = \"Portuguese\";\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n langName = \"Japanese\";\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n langName = \"Korean\";\n break;\n case LANG_ENGLISH:\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n langName = \"English\";\n break;\n }\n \n // Choose default settings based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", \"TRUE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 1; i <= 5; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n config_path);\n}\n\n/** @brief Extract filename from file path */\nvoid ExtractFileName(const char* path, char* name, size_t nameSize) {\n if (!path || !name || nameSize == 0) return;\n \n // First convert to wide characters to properly handle Unicode paths\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, wPath, MAX_PATH);\n \n // Look for the last backslash or forward slash\n wchar_t* lastSlash = wcsrchr(wPath, L'\\\\');\n if (!lastSlash) lastSlash = wcsrchr(wPath, L'/');\n \n wchar_t wName[MAX_PATH] = {0};\n if (lastSlash) {\n wcscpy(wName, lastSlash + 1);\n } else {\n wcscpy(wName, wPath);\n }\n \n // Convert back to UTF-8\n WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, nameSize, NULL, NULL);\n}\n\n/** @brief Check and create resource folders */\nvoid CheckAndCreateResourceFolders() {\n char config_path[MAX_PATH];\n char base_path[MAX_PATH];\n char resource_path[MAX_PATH];\n char *last_slash;\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Copy configuration file path\n strncpy(base_path, config_path, MAX_PATH - 1);\n base_path[MAX_PATH - 1] = '\\0';\n \n // Find the last slash or backslash, which marks the beginning of the filename\n last_slash = strrchr(base_path, '\\\\');\n if (!last_slash) {\n last_slash = strrchr(base_path, '/');\n }\n \n if (last_slash) {\n // Truncate path to directory part\n *(last_slash + 1) = '\\0';\n \n // Create resources main directory\n snprintf(resource_path, MAX_PATH, \"%sresources\", base_path);\n DWORD attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create resources folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n return;\n }\n }\n \n // Create audio subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\audio\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create audio folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create images subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\images\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create images folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create animations subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\animations\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create animations folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create themes subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\themes\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create themes folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create plug-in subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\plug-in\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create plug-in folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n }\n}\n\n/** @brief Read and parse configuration file */\nvoid ReadConfig() {\n // Check and create resource folders\n CheckAndCreateResourceFolders();\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Check if configuration file exists, create default configuration if it doesn't\n if (!FileExists(config_path)) {\n CreateDefaultConfig(config_path);\n }\n \n // Check configuration file version\n char version[32] = {0};\n BOOL versionMatched = FALSE;\n \n // Read current version information\n ReadIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", \"\", version, sizeof(version), config_path);\n \n // Compare if version matches\n if (strcmp(version, CATIME_VERSION) == 0) {\n versionMatched = TRUE;\n }\n \n // If version doesn't match, recreate the configuration file\n if (!versionMatched) {\n CreateDefaultConfig(config_path);\n }\n\n // Reset time options\n time_options_count = 0;\n memset(time_options, 0, sizeof(time_options));\n \n // Reset recent files count\n CLOCK_RECENT_FILES_COUNT = 0;\n \n // Read basic settings\n // ======== [General] Section ========\n char language[32] = {0};\n ReadIniString(INI_SECTION_GENERAL, \"LANGUAGE\", \"English\", language, sizeof(language), config_path);\n \n // Convert language name to enum value\n int languageSetting = APP_LANG_ENGLISH; // Default to English\n \n if (strcmp(language, \"Chinese_Simplified\") == 0) {\n languageSetting = APP_LANG_CHINESE_SIMP;\n } else if (strcmp(language, \"Chinese_Traditional\") == 0) {\n languageSetting = APP_LANG_CHINESE_TRAD;\n } else if (strcmp(language, \"English\") == 0) {\n languageSetting = APP_LANG_ENGLISH;\n } else if (strcmp(language, \"Spanish\") == 0) {\n languageSetting = APP_LANG_SPANISH;\n } else if (strcmp(language, \"French\") == 0) {\n languageSetting = APP_LANG_FRENCH;\n } else if (strcmp(language, \"German\") == 0) {\n languageSetting = APP_LANG_GERMAN;\n } else if (strcmp(language, \"Russian\") == 0) {\n languageSetting = APP_LANG_RUSSIAN;\n } else if (strcmp(language, \"Portuguese\") == 0) {\n languageSetting = APP_LANG_PORTUGUESE;\n } else if (strcmp(language, \"Japanese\") == 0) {\n languageSetting = APP_LANG_JAPANESE;\n } else if (strcmp(language, \"Korean\") == 0) {\n languageSetting = APP_LANG_KOREAN;\n } else {\n // Try to parse as number (for backward compatibility)\n int langValue = atoi(language);\n if (langValue >= 0 && langValue < APP_LANG_COUNT) {\n languageSetting = langValue;\n } else {\n languageSetting = APP_LANG_ENGLISH; // Default to English\n }\n }\n \n // ======== [Display] Section ========\n ReadIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", CLOCK_TEXT_COLOR, sizeof(CLOCK_TEXT_COLOR), config_path);\n CLOCK_BASE_FONT_SIZE = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n ReadIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", FONT_FILE_NAME, sizeof(FONT_FILE_NAME), config_path);\n \n // Extract internal name from font filename\n size_t font_name_len = strlen(FONT_FILE_NAME);\n if (font_name_len > 4 && strcmp(FONT_FILE_NAME + font_name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = font_name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n CLOCK_WINDOW_POS_X = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n CLOCK_WINDOW_POS_Y = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n \n char scaleStr[16] = {0};\n ReadIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", scaleStr, sizeof(scaleStr), config_path);\n CLOCK_WINDOW_SCALE = atof(scaleStr);\n \n CLOCK_WINDOW_TOPMOST = ReadIniBool(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", TRUE, config_path);\n \n // Check and replace pure black color\n if (strcasecmp(CLOCK_TEXT_COLOR, \"#000000\") == 0) {\n strncpy(CLOCK_TEXT_COLOR, \"#000001\", sizeof(CLOCK_TEXT_COLOR) - 1);\n }\n \n // ======== [Timer] Section ========\n CLOCK_DEFAULT_START_TIME = ReadIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n CLOCK_USE_24HOUR = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", FALSE, config_path);\n CLOCK_SHOW_SECONDS = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", FALSE, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", CLOCK_TIMEOUT_TEXT, sizeof(CLOCK_TIMEOUT_TEXT), config_path);\n \n // Read timeout action\n char timeoutAction[32] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", timeoutAction, sizeof(timeoutAction), config_path);\n \n if (strcmp(timeoutAction, \"MESSAGE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"LOCK\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n } else if (strcmp(timeoutAction, \"SHUTDOWN\") == 0) {\n // Even if SHUTDOWN exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"RESTART\") == 0) {\n // Even if RESTART exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"OPEN_FILE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n } else if (strcmp(timeoutAction, \"SHOW_TIME\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n } else if (strcmp(timeoutAction, \"COUNT_UP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n } else if (strcmp(timeoutAction, \"OPEN_WEBSITE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n } else if (strcmp(timeoutAction, \"SLEEP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n } else if (strcmp(timeoutAction, \"RUN_COMMAND\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n } else if (strcmp(timeoutAction, \"HTTP_REQUEST\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n }\n \n // Read timeout file and website settings\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", CLOCK_TIMEOUT_FILE_PATH, MAX_PATH, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", CLOCK_TIMEOUT_WEBSITE_URL, MAX_PATH, config_path);\n \n // If file path is valid, ensure timeout action is set to open file\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n GetFileAttributesA(CLOCK_TIMEOUT_FILE_PATH) != INVALID_FILE_ATTRIBUTES) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n }\n \n // If URL is valid, ensure timeout action is set to open website\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n }\n \n // Read time options\n char timeOptions[256] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", timeOptions, sizeof(timeOptions), config_path);\n \n char *token = strtok(timeOptions, \",\");\n while (token && time_options_count < MAX_TIME_OPTIONS) {\n while (*token == ' ') token++;\n time_options[time_options_count++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Read startup mode\n ReadIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", CLOCK_STARTUP_MODE, sizeof(CLOCK_STARTUP_MODE), config_path);\n \n // ======== [Pomodoro] Section ========\n char pomodoroTimeOptions[256] = {0};\n ReadIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", pomodoroTimeOptions, sizeof(pomodoroTimeOptions), config_path);\n \n // Reset pomodoro time count\n POMODORO_TIMES_COUNT = 0;\n \n // Parse all pomodoro time values\n token = strtok(pomodoroTimeOptions, \",\");\n while (token && POMODORO_TIMES_COUNT < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[POMODORO_TIMES_COUNT++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Even though we now use a new array to store all times,\n // keep these three variables for backward compatibility\n if (POMODORO_TIMES_COUNT > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (POMODORO_TIMES_COUNT > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (POMODORO_TIMES_COUNT > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[3]; // Note this is the 4th value\n }\n \n // Read pomodoro loop count\n POMODORO_LOOP_COUNT = ReadIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n \n // ======== [Notification] Section ========\n ReadIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", \n CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", \n POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", \n POMODORO_CYCLE_COMPLETE_TEXT, sizeof(POMODORO_CYCLE_COMPLETE_TEXT), config_path);\n \n NOTIFICATION_TIMEOUT_MS = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n NOTIFICATION_MAX_OPACITY = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n \n // Ensure opacity is within valid range (1-100)\n if (NOTIFICATION_MAX_OPACITY < 1) NOTIFICATION_MAX_OPACITY = 1;\n if (NOTIFICATION_MAX_OPACITY > 100) NOTIFICATION_MAX_OPACITY = 100;\n \n char notificationType[32] = {0};\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", \"CATIME\", notificationType, sizeof(notificationType), config_path);\n \n // Set notification type\n if (strcmp(notificationType, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(notificationType, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(notificationType, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Read notification audio file path\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", \n NOTIFICATION_SOUND_FILE, MAX_PATH, config_path);\n \n // Read notification audio volume\n NOTIFICATION_SOUND_VOLUME = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n \n // Read whether to disable notification window\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n \n // Ensure volume is within valid range (0-100)\n if (NOTIFICATION_SOUND_VOLUME < 0) NOTIFICATION_SOUND_VOLUME = 0;\n if (NOTIFICATION_SOUND_VOLUME > 100) NOTIFICATION_SOUND_VOLUME = 100;\n \n // ======== [Colors] Section ========\n char colorOptions[1024] = {0};\n ReadIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n colorOptions, sizeof(colorOptions), config_path);\n \n // Parse color options\n token = strtok(colorOptions, \",\");\n COLOR_OPTIONS_COUNT = 0;\n while (token) {\n COLOR_OPTIONS = realloc(COLOR_OPTIONS, sizeof(PredefinedColor) * (COLOR_OPTIONS_COUNT + 1));\n if (COLOR_OPTIONS) {\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = strdup(token);\n COLOR_OPTIONS_COUNT++;\n }\n token = strtok(NULL, \",\");\n }\n \n // ======== [RecentFiles] Section ========\n // Read recent file records\n for (int i = 1; i <= MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n \n char filePath[MAX_PATH] = {0};\n ReadIniString(INI_SECTION_RECENTFILES, key, \"\", filePath, MAX_PATH, config_path);\n \n if (strlen(filePath) > 0) {\n // Convert to wide characters to properly check if the file exists\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, widePath, MAX_PATH);\n \n // Check if file exists\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n ExtractFileName(filePath, CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, MAX_PATH);\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n \n // ======== [Hotkeys] Section ========\n // Read hotkey configurations from INI file\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n // Read hotkey settings\n char hotkeyStr[32] = {0};\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n showTimeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countUpHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countdownHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown1Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown2Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown3Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pomodoroHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n toggleVisibilityHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n editModeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pauseResumeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n restartTimerHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n customCountdownHotkey = StringToHotkey(hotkeyStr);\n \n last_config_time = time(NULL);\n\n // Apply window position\n HWND hwnd = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwnd) {\n SetWindowPos(hwnd, NULL, CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n\n // Apply language settings\n SetLanguage((AppLanguage)languageSetting);\n}\n\n/** @brief Write timeout action configuration */\nvoid WriteConfigTimeoutAction(const char* action) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n // For shutdown or restart actions, don't write them to the config file, write \"MESSAGE\" instead\n const char* actual_action = action;\n if (strcmp(action, \"RESTART\") == 0 || strcmp(action, \"SHUTDOWN\") == 0 || strcmp(action, \"SLEEP\") == 0) {\n actual_action = \"MESSAGE\";\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write time options configuration */\nvoid WriteConfigTimeOptions(const char* options) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIME_OPTIONS=\", 19) == 0) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Load recently used file records */\nvoid LoadRecentFiles(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) return;\n\n char line[MAX_PATH];\n CLOCK_RECENT_FILES_COUNT = 0;\n\n while (fgets(line, sizeof(line), file)) {\n // Support for the CLOCK_RECENT_FILE_N=path format\n if (strncmp(line, \"CLOCK_RECENT_FILE_\", 18) == 0) {\n char *path = strchr(line + 18, '=');\n if (path) {\n path++; // Skip the equals sign\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n // Also update the old format for compatibility\n else if (strncmp(line, \"CLOCK_RECENT_FILE=\", 18) == 0) {\n char *path = line + 18;\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n\n fclose(file);\n}\n\n/** @brief Save recently used file record */\nvoid SaveRecentFile(const char* filePath) {\n // Check if the file path is valid\n if (!filePath || strlen(filePath) == 0) return;\n \n // Convert to wide characters to check if the file exists\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) == INVALID_FILE_ATTRIBUTES) {\n // File doesn't exist, don't add it\n return;\n }\n \n // Check if the file is already in the list\n int existingIndex = -1;\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n if (strcmp(CLOCK_RECENT_FILES[i].path, filePath) == 0) {\n existingIndex = i;\n break;\n }\n }\n \n if (existingIndex == 0) {\n // File is already at the top of the list, no action needed\n return;\n }\n \n if (existingIndex > 0) {\n // File is in the list, but not at the top, need to move it\n RecentFile temp = CLOCK_RECENT_FILES[existingIndex];\n \n // Move elements backward\n for (int i = existingIndex; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Put it at the first position\n CLOCK_RECENT_FILES[0] = temp;\n } else {\n // File is not in the list, need to add it\n // First ensure the list doesn't exceed 5 items\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n CLOCK_RECENT_FILES_COUNT++;\n }\n \n // Move elements backward\n for (int i = CLOCK_RECENT_FILES_COUNT - 1; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Add new file to the first position\n strncpy(CLOCK_RECENT_FILES[0].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[0].path[MAX_PATH - 1] = '\\0';\n \n // Extract filename\n ExtractFileName(filePath, CLOCK_RECENT_FILES[0].name, MAX_PATH);\n }\n \n // Update configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n WriteConfig(configPath);\n}\n\n/** @brief Convert UTF8 to ANSI encoding */\nchar* UTF8ToANSI(const char* utf8Str) {\n int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, NULL, 0);\n if (wlen == 0) {\n return _strdup(utf8Str);\n }\n\n wchar_t* wstr = (wchar_t*)malloc(sizeof(wchar_t) * wlen);\n if (!wstr) {\n return _strdup(utf8Str);\n }\n\n if (MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, wstr, wlen) == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n int len = WideCharToMultiByte(936, 0, wstr, -1, NULL, 0, NULL, NULL);\n if (len == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n char* str = (char*)malloc(len);\n if (!str) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n if (WideCharToMultiByte(936, 0, wstr, -1, str, len, NULL, NULL) == 0) {\n free(wstr);\n free(str);\n return _strdup(utf8Str);\n }\n\n free(wstr);\n return str;\n}\n\n/** @brief Write pomodoro time settings */\nvoid WriteConfigPomodoroTimes(int work, int short_break, int long_break) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n // Update global variables\n // Maintain backward compatibility, while updating the POMODORO_TIMES array\n POMODORO_WORK_TIME = work;\n POMODORO_SHORT_BREAK = short_break;\n POMODORO_LONG_BREAK = long_break;\n \n // Ensure at least these three time values exist\n POMODORO_TIMES[0] = work;\n if (POMODORO_TIMES_COUNT < 1) POMODORO_TIMES_COUNT = 1;\n \n if (POMODORO_TIMES_COUNT > 1) {\n POMODORO_TIMES[1] = short_break;\n } else if (short_break > 0) {\n POMODORO_TIMES[1] = short_break;\n POMODORO_TIMES_COUNT = 2;\n }\n \n if (POMODORO_TIMES_COUNT > 2) {\n POMODORO_TIMES[2] = long_break;\n } else if (long_break > 0) {\n POMODORO_TIMES[2] = long_break;\n POMODORO_TIMES_COUNT = 3;\n }\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n // Look for POMODORO_TIME_OPTIONS line\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write all pomodoro times\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If POMODORO_TIME_OPTIONS was not found, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro loop count configuration */\nvoid WriteConfigPomodoroLoopCount(int loop_count) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If the key was not found in the configuration file, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n POMODORO_LOOP_COUNT = loop_count;\n}\n\n/** @brief Write window topmost status configuration */\nvoid WriteConfigTopmost(const char* topmost) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"WINDOW_TOPMOST=\", 15) == 0) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write timeout open file path */\nvoid WriteConfigTimeoutFile(const char* filePath) {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n strncpy(CLOCK_TIMEOUT_FILE_PATH, filePath, MAX_PATH - 1);\n CLOCK_TIMEOUT_FILE_PATH[MAX_PATH - 1] = '\\0';\n \n // Use WriteConfig to completely rewrite the configuration file, maintaining structural consistency\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n}\n\n/** @brief Write all configuration settings to file */\nvoid WriteConfig(const char* config_path) {\n // Get the name of the current language\n AppLanguage currentLang = GetCurrentLanguage();\n const char* langName;\n \n switch (currentLang) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n case APP_LANG_ENGLISH:\n default:\n langName = \"English\";\n break;\n }\n \n // Choose string representation based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Read hotkey settings\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0};\n \n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Prepare time options string\n char timeOptionsStr[256] = {0};\n for (int i = 0; i < time_options_count; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", time_options[i]);\n \n if (i > 0) {\n strcat(timeOptionsStr, \",\");\n }\n strcat(timeOptionsStr, buffer);\n }\n \n // Prepare pomodoro time options string\n char pomodoroTimesStr[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", POMODORO_TIMES[i]);\n \n if (i > 0) {\n strcat(pomodoroTimesStr, \",\");\n }\n strcat(pomodoroTimesStr, buffer);\n }\n \n // Prepare color options string\n char colorOptionsStr[1024] = {0};\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (i > 0) {\n strcat(colorOptionsStr, \",\");\n }\n strcat(colorOptionsStr, COLOR_OPTIONS[i].hexColor);\n }\n \n // Determine timeout action string\n const char* timeoutActionStr;\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_LOCK:\n timeoutActionStr = \"LOCK\";\n break;\n case TIMEOUT_ACTION_SHUTDOWN:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RESTART:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_OPEN_FILE:\n timeoutActionStr = \"OPEN_FILE\";\n break;\n case TIMEOUT_ACTION_SHOW_TIME:\n timeoutActionStr = \"SHOW_TIME\";\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n timeoutActionStr = \"COUNT_UP\";\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n timeoutActionStr = \"OPEN_WEBSITE\";\n break;\n case TIMEOUT_ACTION_SLEEP:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n timeoutActionStr = \"RUN_COMMAND\";\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n timeoutActionStr = \"HTTP_REQUEST\";\n break;\n default:\n timeoutActionStr = \"MESSAGE\";\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", IsShortcutCheckDone() ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", CLOCK_TEXT_COLOR, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", CLOCK_BASE_FONT_SIZE, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", FONT_FILE_NAME, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", CLOCK_WINDOW_POS_X, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", CLOCK_WINDOW_POS_Y, config_path);\n \n char scaleStr[16];\n snprintf(scaleStr, sizeof(scaleStr), \"%.2f\", CLOCK_WINDOW_SCALE);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", scaleStr, config_path);\n \n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", CLOCK_WINDOW_TOPMOST ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", CLOCK_DEFAULT_START_TIME, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", CLOCK_USE_24HOUR ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", CLOCK_SHOW_SECONDS ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", CLOCK_TIMEOUT_TEXT, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", timeoutActionStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", CLOCK_TIMEOUT_FILE_PATH, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", CLOCK_TIMEOUT_WEBSITE_URL, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", timeOptionsStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", CLOCK_STARTUP_MODE, config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", pomodoroTimesStr, config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", POMODORO_LOOP_COUNT, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", CLOCK_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", POMODORO_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", POMODORO_CYCLE_COMPLETE_TEXT, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", NOTIFICATION_TIMEOUT_MS, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", NOTIFICATION_MAX_OPACITY, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", NOTIFICATION_SOUND_FILE, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", NOTIFICATION_SOUND_VOLUME, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", NOTIFICATION_DISABLED ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", showTimeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", countUpStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", countdownStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", quickCountdown1Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", quickCountdown2Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", quickCountdown3Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", pomodoroStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", toggleVisibilityStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", editModeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", pauseResumeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", restartTimerStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr, config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, CLOCK_RECENT_FILES[i].path, config_path);\n }\n \n // Clear unused file records\n for (int i = CLOCK_RECENT_FILES_COUNT; i < MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", colorOptionsStr, config_path);\n}\n\n/** @brief Write timeout open website URL */\nvoid WriteConfigTimeoutWebsite(const char* url) {\n // Only set timeout action to open website if a valid URL is provided\n if (url && url[0] != '\\0') {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n strncpy(CLOCK_TIMEOUT_WEBSITE_URL, url, MAX_PATH - 1);\n CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH - 1] = '\\0';\n \n // Then update the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL actionFound = FALSE;\n BOOL urlFound = FALSE;\n \n // Read original configuration file, update timeout action and URL\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n actionFound = TRUE;\n } else if (strncmp(line, \"CLOCK_TIMEOUT_WEBSITE=\", 22) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n urlFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If these items are not in the configuration, add them\n if (!actionFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n }\n if (!urlFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n }\n}\n\n/** @brief Write startup mode configuration */\nvoid WriteConfigStartupMode(const char* mode) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n // Update global variable\n strncpy(CLOCK_STARTUP_MODE, mode, sizeof(CLOCK_STARTUP_MODE) - 1);\n CLOCK_STARTUP_MODE[sizeof(CLOCK_STARTUP_MODE) - 1] = '\\0';\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro time options */\nvoid WriteConfigPomodoroTimeOptions(int* times, int count) {\n if (!times || count <= 0) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL optionsFound = FALSE;\n \n // Read original configuration file, update pomodoro time options\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write new time options\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n optionsFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If this item is not in the configuration, add it\n if (!optionsFound) {\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write notification message configuration */\nvoid WriteConfigNotificationMessages(const char* timeout_msg, const char* pomodoro_msg, const char* cycle_complete_msg) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n // Use standard C file operations instead of Windows API\n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL timeoutFound = FALSE;\n BOOL pomodoroFound = FALSE;\n BOOL cycleFound = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n timeoutFound = TRUE;\n } else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n pomodoroFound = TRUE;\n } else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n cycleFound = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If corresponding items are not found in the configuration, add them\n if (!timeoutFound) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n }\n \n if (!pomodoroFound) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n }\n \n if (!cycleFound) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variables\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, timeout_msg, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, pomodoro_msg, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, cycle_complete_msg, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n}\n\n/** @brief Read notification message text from configuration file */\nvoid ReadNotificationMessagesConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current values in memory or default values\n return;\n }\n\n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[1024];\n BOOL timeoutMsgFound = FALSE;\n BOOL pomodoroTimeoutMsgFound = FALSE;\n BOOL cycleCompleteMsgFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n // Process this line\n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, line + 27, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n timeoutMsgFound = TRUE;\n } \n else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, line + 30, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n pomodoroTimeoutMsgFound = TRUE;\n }\n else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, line + 29, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n cycleCompleteMsgFound = TRUE;\n }\n \n // If all messages have been found, can exit loop early\n if (timeoutMsgFound && pomodoroTimeoutMsgFound && cycleCompleteMsgFound) {\n break;\n }\n }\n \n CloseHandle(hFile);\n \n // If corresponding configuration items are not found in the file, ensure variables have default values\n if (!timeoutMsgFound) {\n strcpy(CLOCK_TIMEOUT_MESSAGE_TEXT, \"时间到啦!\"); // Default value\n }\n if (!pomodoroTimeoutMsgFound) {\n strcpy(POMODORO_TIMEOUT_MESSAGE_TEXT, \"番茄钟时间到!\"); // Default value\n }\n if (!cycleCompleteMsgFound) {\n strcpy(POMODORO_CYCLE_COMPLETE_TEXT, \"所有番茄钟循环完成!\"); // Default value\n }\n}\n\n/** @brief Read notification display time from configuration file */\nvoid ReadNotificationTimeoutConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL timeoutFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n int timeout = atoi(line + 24);\n if (timeout > 0) {\n NOTIFICATION_TIMEOUT_MS = timeout;\n }\n timeoutFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!timeoutFound) {\n NOTIFICATION_TIMEOUT_MS = 3000; // Ensure there's a default value\n }\n}\n\n/** @brief Write notification display time configuration */\nvoid WriteConfigNotificationTimeout(int timeout_ms) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_TIMEOUT_MS = timeout_ms;\n}\n\n/** @brief Read maximum notification opacity from configuration file */\nvoid ReadNotificationOpacityConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL opacityFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n int opacity = atoi(line + 25);\n // Ensure opacity is within valid range (1-100)\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n opacityFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!opacityFound) {\n NOTIFICATION_MAX_OPACITY = 95; // Ensure there's a default value\n }\n}\n\n/** @brief Write maximum notification opacity configuration */\nvoid WriteConfigNotificationOpacity(int opacity) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_MAX_OPACITY = opacity;\n}\n\n/** @brief Read notification type setting from configuration file */\nvoid ReadNotificationTypeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *file = fopen(config_path, \"r\");\n if (file) {\n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n char typeStr[32] = {0};\n sscanf(line + 18, \"%31s\", typeStr);\n \n // Set notification type based on the string\n if (strcmp(typeStr, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(typeStr, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(typeStr, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n // Use default value for invalid type\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n }\n break;\n }\n }\n fclose(file);\n }\n}\n\n/** @brief Write notification type configuration */\nvoid WriteConfigNotificationType(NotificationType type) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure type value is within valid range\n if (type < NOTIFICATION_TYPE_CATIME || type > NOTIFICATION_TYPE_OS) {\n type = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Update global variable\n NOTIFICATION_TYPE = type;\n \n // Convert enum to string\n const char* typeStr;\n switch (type) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Create temporary file path\n char temp_path[MAX_PATH];\n strncpy(temp_path, config_path, MAX_PATH - 5);\n strcat(temp_path, \".tmp\");\n \n FILE *source = fopen(config_path, \"r\");\n FILE *target = fopen(temp_path, \"w\");\n \n if (source && target) {\n char line[256];\n BOOL found = FALSE;\n \n // Copy file content, replace target configuration line\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n found = TRUE;\n } else {\n fputs(line, target);\n }\n }\n \n // If configuration item not found, add it to the end of file\n if (!found) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n }\n \n fclose(source);\n fclose(target);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n } else {\n // Clean up potentially open files\n if (source) fclose(source);\n if (target) fclose(target);\n }\n}\n\n/** @brief Get audio folder path */\nvoid GetAudioFolderPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) >= size) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Read notification audio settings from configuration file */\nvoid ReadNotificationSoundConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[1024];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n char* value = line + 23; // Correct offset, skip \"NOTIFICATION_SOUND_FILE=\"\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Ensure path doesn't contain equals sign\n if (value[0] == '=') {\n value++; // If first character is equals sign, skip it\n }\n \n // Copy to global variable, ensure cleared\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, value, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio configuration */\nvoid WriteConfigNotificationSound(const char* sound_file) {\n if (!sound_file) return;\n \n // Check if the path contains equals sign, remove if present\n char clean_path[MAX_PATH] = {0};\n const char* src = sound_file;\n char* dst = clean_path;\n \n while (*src && (dst - clean_path) < (MAX_PATH - 1)) {\n if (*src != '=') {\n *dst++ = *src;\n }\n src++;\n }\n *dst = '\\0';\n \n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Create temporary file path\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE* source = fopen(config_path, \"r\");\n if (!source) return;\n \n FILE* dest = fopen(temp_path, \"w\");\n if (!dest) {\n fclose(source);\n return;\n }\n \n char line[1024];\n int found = 0;\n \n // Copy file content, replace or add notification audio settings\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n found = 1;\n } else {\n fputs(line, dest);\n }\n }\n \n // If configuration item not found, add to end of file\n if (!found) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n }\n \n fclose(source);\n fclose(dest);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, clean_path, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n}\n\n/** @brief Read notification audio volume from configuration file */\nvoid ReadNotificationVolumeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n int volume = atoi(line + 26);\n if (volume >= 0 && volume <= 100) {\n NOTIFICATION_SOUND_VOLUME = volume;\n }\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio volume configuration */\nvoid WriteConfigNotificationVolume(int volume) {\n // Validate volume range\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n \n // Update global variable\n NOTIFICATION_SOUND_VOLUME = volume;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Read hotkey settings from configuration file */\nvoid ReadConfigHotkeys(WORD* showTimeHotkey, WORD* countUpHotkey, WORD* countdownHotkey,\n WORD* quickCountdown1Hotkey, WORD* quickCountdown2Hotkey, WORD* quickCountdown3Hotkey,\n WORD* pomodoroHotkey, WORD* toggleVisibilityHotkey, WORD* editModeHotkey,\n WORD* pauseResumeHotkey, WORD* restartTimerHotkey)\n{\n // Parameter validation\n if (!showTimeHotkey || !countUpHotkey || !countdownHotkey || \n !quickCountdown1Hotkey || !quickCountdown2Hotkey || !quickCountdown3Hotkey ||\n !pomodoroHotkey || !toggleVisibilityHotkey || !editModeHotkey || \n !pauseResumeHotkey || !restartTimerHotkey) return;\n \n // Initialize to 0 (indicates no hotkey set)\n *showTimeHotkey = 0;\n *countUpHotkey = 0;\n *countdownHotkey = 0;\n *quickCountdown1Hotkey = 0;\n *quickCountdown2Hotkey = 0;\n *quickCountdown3Hotkey = 0;\n *pomodoroHotkey = 0;\n *toggleVisibilityHotkey = 0;\n *editModeHotkey = 0;\n *pauseResumeHotkey = 0;\n *restartTimerHotkey = 0;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *showTimeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countUpHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countdownHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown1Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown2Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown3Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pomodoroHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n char* value = line + 25;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *toggleVisibilityHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *editModeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n char* value = line + 20;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pauseResumeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n char* value = line + 21;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *restartTimerHotkey = StringToHotkey(value);\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write hotkey configuration */\nvoid WriteConfigHotkeys(WORD showTimeHotkey, WORD countUpHotkey, WORD countdownHotkey,\n WORD quickCountdown1Hotkey, WORD quickCountdown2Hotkey, WORD quickCountdown3Hotkey,\n WORD pomodoroHotkey, WORD toggleVisibilityHotkey, WORD editModeHotkey,\n WORD pauseResumeHotkey, WORD restartTimerHotkey) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) {\n // If file doesn't exist, create new file\n file = fopen(config_path, \"w\");\n if (!file) return;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0}; // Add custom countdown hotkey\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n // Get custom countdown hotkey value\n WORD customCountdownHotkey = 0;\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Write hotkey configuration\n fprintf(file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n fprintf(file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n fprintf(file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n fprintf(file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n fprintf(file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n fprintf(file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n fprintf(file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n fprintf(file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n fprintf(file, \"HOTKEY_CUSTOM_COUNTDOWN=%s\\n\", customCountdownStr); // Add new hotkey\n \n fclose(file);\n return;\n }\n \n // File exists, read all lines and update hotkey settings\n char temp_path[MAX_PATH];\n sprintf(temp_path, \"%s.tmp\", config_path);\n FILE* temp_file = fopen(temp_path, \"w\");\n \n if (!temp_file) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL foundShowTime = FALSE;\n BOOL foundCountUp = FALSE;\n BOOL foundCountdown = FALSE;\n BOOL foundQuickCountdown1 = FALSE;\n BOOL foundQuickCountdown2 = FALSE;\n BOOL foundQuickCountdown3 = FALSE;\n BOOL foundPomodoro = FALSE;\n BOOL foundToggleVisibility = FALSE;\n BOOL foundEditMode = FALSE;\n BOOL foundPauseResume = FALSE;\n BOOL foundRestartTimer = FALSE;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n \n // Process each line\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n foundShowTime = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n foundCountUp = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n foundCountdown = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n foundQuickCountdown1 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n foundQuickCountdown2 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n foundQuickCountdown3 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n foundPomodoro = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n foundToggleVisibility = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n foundEditMode = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n foundPauseResume = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n foundRestartTimer = TRUE;\n }\n else {\n // Keep other lines\n fputs(line, temp_file);\n }\n }\n \n // Add hotkey configuration items not found\n if (!foundShowTime) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n }\n if (!foundCountUp) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n }\n if (!foundCountdown) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n }\n if (!foundQuickCountdown1) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n }\n if (!foundQuickCountdown2) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n }\n if (!foundQuickCountdown3) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n }\n if (!foundPomodoro) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n }\n if (!foundToggleVisibility) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n }\n if (!foundEditMode) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n }\n if (!foundPauseResume) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n }\n if (!foundRestartTimer) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n }\n \n fclose(file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Convert hotkey value to readable string */\nvoid HotkeyToString(WORD hotkey, char* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) return;\n \n // 如果热键为0,表示未设置\n if (hotkey == 0) {\n strncpy(buffer, \"None\", bufferSize - 1);\n buffer[bufferSize - 1] = '\\0';\n return;\n }\n \n BYTE vk = LOBYTE(hotkey); // 虚拟键码\n BYTE mod = HIBYTE(hotkey); // 修饰键\n \n buffer[0] = '\\0';\n size_t len = 0;\n \n // 添加修饰键\n if (mod & HOTKEYF_CONTROL) {\n strncpy(buffer, \"Ctrl\", bufferSize - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_SHIFT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Shift\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_ALT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Alt\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n // 添加虚拟键\n if (len > 0 && len < bufferSize - 1 && vk != 0) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n \n // 获取虚拟键名称\n if (vk >= 'A' && vk <= 'Z') {\n // 字母键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= '0' && vk <= '9') {\n // 数字键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= VK_F1 && vk <= VK_F24) {\n // 功能键\n char keyName[4];\n sprintf(keyName, \"F%d\", vk - VK_F1 + 1);\n strncat(buffer, keyName, bufferSize - len - 1);\n } else {\n // 其他特殊键\n switch (vk) {\n case VK_BACK: strncat(buffer, \"Backspace\", bufferSize - len - 1); break;\n case VK_TAB: strncat(buffer, \"Tab\", bufferSize - len - 1); break;\n case VK_RETURN: strncat(buffer, \"Enter\", bufferSize - len - 1); break;\n case VK_ESCAPE: strncat(buffer, \"Esc\", bufferSize - len - 1); break;\n case VK_SPACE: strncat(buffer, \"Space\", bufferSize - len - 1); break;\n case VK_PRIOR: strncat(buffer, \"PageUp\", bufferSize - len - 1); break;\n case VK_NEXT: strncat(buffer, \"PageDown\", bufferSize - len - 1); break;\n case VK_END: strncat(buffer, \"End\", bufferSize - len - 1); break;\n case VK_HOME: strncat(buffer, \"Home\", bufferSize - len - 1); break;\n case VK_LEFT: strncat(buffer, \"Left\", bufferSize - len - 1); break;\n case VK_UP: strncat(buffer, \"Up\", bufferSize - len - 1); break;\n case VK_RIGHT: strncat(buffer, \"Right\", bufferSize - len - 1); break;\n case VK_DOWN: strncat(buffer, \"Down\", bufferSize - len - 1); break;\n case VK_INSERT: strncat(buffer, \"Insert\", bufferSize - len - 1); break;\n case VK_DELETE: strncat(buffer, \"Delete\", bufferSize - len - 1); break;\n case VK_NUMPAD0: strncat(buffer, \"Num0\", bufferSize - len - 1); break;\n case VK_NUMPAD1: strncat(buffer, \"Num1\", bufferSize - len - 1); break;\n case VK_NUMPAD2: strncat(buffer, \"Num2\", bufferSize - len - 1); break;\n case VK_NUMPAD3: strncat(buffer, \"Num3\", bufferSize - len - 1); break;\n case VK_NUMPAD4: strncat(buffer, \"Num4\", bufferSize - len - 1); break;\n case VK_NUMPAD5: strncat(buffer, \"Num5\", bufferSize - len - 1); break;\n case VK_NUMPAD6: strncat(buffer, \"Num6\", bufferSize - len - 1); break;\n case VK_NUMPAD7: strncat(buffer, \"Num7\", bufferSize - len - 1); break;\n case VK_NUMPAD8: strncat(buffer, \"Num8\", bufferSize - len - 1); break;\n case VK_NUMPAD9: strncat(buffer, \"Num9\", bufferSize - len - 1); break;\n case VK_MULTIPLY: strncat(buffer, \"Num*\", bufferSize - len - 1); break;\n case VK_ADD: strncat(buffer, \"Num+\", bufferSize - len - 1); break;\n case VK_SUBTRACT: strncat(buffer, \"Num-\", bufferSize - len - 1); break;\n case VK_DECIMAL: strncat(buffer, \"Num.\", bufferSize - len - 1); break;\n case VK_DIVIDE: strncat(buffer, \"Num/\", bufferSize - len - 1); break;\n case VK_OEM_1: strncat(buffer, \";\", bufferSize - len - 1); break;\n case VK_OEM_PLUS: strncat(buffer, \"=\", bufferSize - len - 1); break;\n case VK_OEM_COMMA: strncat(buffer, \",\", bufferSize - len - 1); break;\n case VK_OEM_MINUS: strncat(buffer, \"-\", bufferSize - len - 1); break;\n case VK_OEM_PERIOD: strncat(buffer, \".\", bufferSize - len - 1); break;\n case VK_OEM_2: strncat(buffer, \"/\", bufferSize - len - 1); break;\n case VK_OEM_3: strncat(buffer, \"`\", bufferSize - len - 1); break;\n case VK_OEM_4: strncat(buffer, \"[\", bufferSize - len - 1); break;\n case VK_OEM_5: strncat(buffer, \"\\\\\", bufferSize - len - 1); break;\n case VK_OEM_6: strncat(buffer, \"]\", bufferSize - len - 1); break;\n case VK_OEM_7: strncat(buffer, \"'\", bufferSize - len - 1); break;\n default: \n // 对于其他未知键,使用十六进制表示\n {\n char keyName[8];\n sprintf(keyName, \"0x%02X\", vk);\n strncat(buffer, keyName, bufferSize - len - 1);\n }\n break;\n }\n }\n}\n\n/** @brief Convert string to hotkey value */\nWORD StringToHotkey(const char* str) {\n if (!str || str[0] == '\\0' || strcmp(str, \"None\") == 0) {\n return 0; // 未设置热键\n }\n \n // 尝试直接解析为数字(兼容旧格式)\n if (isdigit(str[0])) {\n return (WORD)atoi(str);\n }\n \n BYTE vk = 0; // 虚拟键码\n BYTE mod = 0; // 修饰键\n \n // 复制字符串以便使用strtok\n char buffer[256];\n strncpy(buffer, str, sizeof(buffer) - 1);\n buffer[sizeof(buffer) - 1] = '\\0';\n \n // 分割字符串,查找修饰键和主键\n char* token = strtok(buffer, \"+\");\n char* lastToken = NULL;\n \n while (token) {\n if (stricmp(token, \"Ctrl\") == 0) {\n mod |= HOTKEYF_CONTROL;\n } else if (stricmp(token, \"Shift\") == 0) {\n mod |= HOTKEYF_SHIFT;\n } else if (stricmp(token, \"Alt\") == 0) {\n mod |= HOTKEYF_ALT;\n } else {\n // 可能是主键\n lastToken = token;\n }\n token = strtok(NULL, \"+\");\n }\n \n // 解析主键\n if (lastToken) {\n // 检查是否是单个字符的字母或数字\n if (strlen(lastToken) == 1) {\n char ch = toupper(lastToken[0]);\n if ((ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) {\n vk = ch;\n }\n } \n // 检查是否是功能键\n else if (lastToken[0] == 'F' && isdigit(lastToken[1])) {\n int fNum = atoi(lastToken + 1);\n if (fNum >= 1 && fNum <= 24) {\n vk = VK_F1 + fNum - 1;\n }\n }\n // 检查特殊键名\n else if (stricmp(lastToken, \"Backspace\") == 0) vk = VK_BACK;\n else if (stricmp(lastToken, \"Tab\") == 0) vk = VK_TAB;\n else if (stricmp(lastToken, \"Enter\") == 0) vk = VK_RETURN;\n else if (stricmp(lastToken, \"Esc\") == 0) vk = VK_ESCAPE;\n else if (stricmp(lastToken, \"Space\") == 0) vk = VK_SPACE;\n else if (stricmp(lastToken, \"PageUp\") == 0) vk = VK_PRIOR;\n else if (stricmp(lastToken, \"PageDown\") == 0) vk = VK_NEXT;\n else if (stricmp(lastToken, \"End\") == 0) vk = VK_END;\n else if (stricmp(lastToken, \"Home\") == 0) vk = VK_HOME;\n else if (stricmp(lastToken, \"Left\") == 0) vk = VK_LEFT;\n else if (stricmp(lastToken, \"Up\") == 0) vk = VK_UP;\n else if (stricmp(lastToken, \"Right\") == 0) vk = VK_RIGHT;\n else if (stricmp(lastToken, \"Down\") == 0) vk = VK_DOWN;\n else if (stricmp(lastToken, \"Insert\") == 0) vk = VK_INSERT;\n else if (stricmp(lastToken, \"Delete\") == 0) vk = VK_DELETE;\n else if (stricmp(lastToken, \"Num0\") == 0) vk = VK_NUMPAD0;\n else if (stricmp(lastToken, \"Num1\") == 0) vk = VK_NUMPAD1;\n else if (stricmp(lastToken, \"Num2\") == 0) vk = VK_NUMPAD2;\n else if (stricmp(lastToken, \"Num3\") == 0) vk = VK_NUMPAD3;\n else if (stricmp(lastToken, \"Num4\") == 0) vk = VK_NUMPAD4;\n else if (stricmp(lastToken, \"Num5\") == 0) vk = VK_NUMPAD5;\n else if (stricmp(lastToken, \"Num6\") == 0) vk = VK_NUMPAD6;\n else if (stricmp(lastToken, \"Num7\") == 0) vk = VK_NUMPAD7;\n else if (stricmp(lastToken, \"Num8\") == 0) vk = VK_NUMPAD8;\n else if (stricmp(lastToken, \"Num9\") == 0) vk = VK_NUMPAD9;\n else if (stricmp(lastToken, \"Num*\") == 0) vk = VK_MULTIPLY;\n else if (stricmp(lastToken, \"Num+\") == 0) vk = VK_ADD;\n else if (stricmp(lastToken, \"Num-\") == 0) vk = VK_SUBTRACT;\n else if (stricmp(lastToken, \"Num.\") == 0) vk = VK_DECIMAL;\n else if (stricmp(lastToken, \"Num/\") == 0) vk = VK_DIVIDE;\n // 检查十六进制格式\n else if (strncmp(lastToken, \"0x\", 2) == 0) {\n vk = (BYTE)strtol(lastToken, NULL, 16);\n }\n }\n \n return MAKEWORD(vk, mod);\n}\n\n/**\n * @brief Read custom countdown hotkey setting from configuration file\n * @param hotkey Pointer to store the hotkey\n */\nvoid ReadCustomCountdownHotkey(WORD* hotkey) {\n if (!hotkey) return;\n \n *hotkey = 0; // 默认为0(未设置)\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_CUSTOM_COUNTDOWN=\", 24) == 0) {\n char* value = line + 24;\n // 去除末尾的换行符\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // 解析热键字符串\n *hotkey = StringToHotkey(value);\n break;\n }\n }\n \n fclose(file);\n}\n\n/**\n * @brief Write a single configuration item to the configuration file\n * @param key Configuration item key name\n * @param value Configuration item value\n * \n * Adds or updates a single configuration item in the configuration file, automatically selects section based on key name\n */\nvoid WriteConfigKeyValue(const char* key, const char* value) {\n if (!key || !value) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Determine which section to place in based on the key name\n const char* section;\n \n if (strcmp(key, \"CONFIG_VERSION\") == 0 ||\n strcmp(key, \"LANGUAGE\") == 0 ||\n strcmp(key, \"SHORTCUT_CHECK_DONE\") == 0) {\n section = INI_SECTION_GENERAL;\n }\n else if (strncmp(key, \"CLOCK_TEXT_COLOR\", 16) == 0 ||\n strncmp(key, \"FONT_FILE_NAME\", 14) == 0 ||\n strncmp(key, \"CLOCK_BASE_FONT_SIZE\", 20) == 0 ||\n strncmp(key, \"WINDOW_SCALE\", 12) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_X\", 18) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_Y\", 18) == 0 ||\n strncmp(key, \"WINDOW_TOPMOST\", 14) == 0) {\n section = INI_SECTION_DISPLAY;\n }\n else if (strncmp(key, \"CLOCK_DEFAULT_START_TIME\", 24) == 0 ||\n strncmp(key, \"CLOCK_USE_24HOUR\", 16) == 0 ||\n strncmp(key, \"CLOCK_SHOW_SECONDS\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIME_OPTIONS\", 18) == 0 ||\n strncmp(key, \"STARTUP_MODE\", 12) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_TEXT\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_ACTION\", 20) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_FILE\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_WEBSITE\", 21) == 0) {\n section = INI_SECTION_TIMER;\n }\n else if (strncmp(key, \"POMODORO_\", 9) == 0) {\n section = INI_SECTION_POMODORO;\n }\n else if (strncmp(key, \"NOTIFICATION_\", 13) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", 26) == 0) {\n section = INI_SECTION_NOTIFICATION;\n }\n else if (strncmp(key, \"HOTKEY_\", 7) == 0) {\n section = INI_SECTION_HOTKEYS;\n }\n else if (strncmp(key, \"CLOCK_RECENT_FILE\", 17) == 0) {\n section = INI_SECTION_RECENTFILES;\n }\n else if (strncmp(key, \"COLOR_OPTIONS\", 13) == 0) {\n section = INI_SECTION_COLORS;\n }\n else {\n // 其他设置放在OPTIONS节\n section = INI_SECTION_OPTIONS;\n }\n \n // 写入配置\n WriteIniString(section, key, value, config_path);\n}\n\n/** @brief Write current language setting to configuration file */\nvoid WriteConfigLanguage(int language) {\n const char* langName;\n \n // Convert language enum value to readable language name\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_ENGLISH:\n langName = \"English\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n default:\n langName = \"English\"; // Default to English\n break;\n }\n \n WriteConfigKeyValue(\"LANGUAGE\", langName);\n}\n\n/** @brief Determine if shortcut check has been performed */\nbool IsShortcutCheckDone(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n return ReadIniBool(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", FALSE, config_path);\n}\n\n/** @brief Set shortcut check status */\nvoid SetShortcutCheckDone(bool done) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // 使用INI写入方式设置状态\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", done ? \"TRUE\" : \"FALSE\", config_path);\n}\n\n/** @brief Read whether to disable notification setting from configuration file */\nvoid ReadNotificationDisabledConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n}\n\n/** @brief Write whether to disable notification configuration */\nvoid WriteConfigNotificationDisabled(BOOL disabled) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_DISABLED=\", 22) == 0) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If configuration item not found in the configuration, add it\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_DISABLED = disabled;\n}\n"], ["/Catime/src/dialog_procedure.c", "/**\n * @file dialog_procedure.c\n * @brief Implementation of dialog message handling procedures\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/audio_player.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/dialog_language.h\"\n\nstatic void DrawColorSelectButton(HDC hdc, HWND hwnd);\n\nextern char inputText[256];\n\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES];\nextern int POMODORO_TIMES_COUNT;\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nWNDPROC wpOrigEditProc;\n\nstatic HWND g_hwndAboutDlg = NULL;\nstatic HWND g_hwndErrorDlg = NULL;\nHWND g_hwndInputDialog = NULL;\nstatic WNDPROC wpOrigLoopEditProc;\n\n#define URL_GITHUB_REPO L\"https://github.com/vladelaina/Catime\"\n\nLRESULT APIENTRY EditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n static BOOL firstKeyProcessed = FALSE;\n\n switch (msg) {\n case WM_SETFOCUS:\n PostMessage(hwnd, EM_SETSEL, 0, -1);\n firstKeyProcessed = FALSE;\n break;\n\n case WM_KEYDOWN:\n if (!firstKeyProcessed) {\n firstKeyProcessed = TRUE;\n }\n\n if (wParam == VK_RETURN) {\n HWND hwndOkButton = GetDlgItem(GetParent(hwnd), CLOCK_IDC_BUTTON_OK);\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwndOkButton);\n return 0;\n }\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n\n case WM_CHAR:\n if (wParam == 1 || (wParam == 'a' || wParam == 'A') && GetKeyState(VK_CONTROL) < 0) {\n return 0;\n }\n if (wParam == VK_RETURN) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(wpOrigEditProc, hwnd, msg, wParam, lParam);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\nvoid ShowErrorDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDD_ERROR_DIALOG),\n hwndParent,\n ErrorDlgProc);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG:\n SetDlgItemTextW(hwndDlg, IDC_ERROR_TEXT,\n GetLocalizedString(L\"输入格式无效,请重新输入。\", L\"Invalid input format, please try again.\"));\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"错误\", L\"Error\"));\n return TRUE;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Input dialog procedure\n */\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n\n g_hwndInputDialog = hwndDlg;\n\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n DWORD dlgId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n\n ApplyDialogLanguage(hwndDlg, (int)dlgId);\n\n if (dlgId == CLOCK_IDD_SHORTCUT_DIALOG) {\n }\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n\n SetFocus(hwndEdit);\n\n PostMessage(hwndDlg, WM_APP+100, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+101, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+102, 0, (LPARAM)hwndEdit);\n\n SendDlgItemMessage(hwndDlg, CLOCK_IDC_EDIT, EM_SETSEL, 0, -1);\n\n SendMessage(hwndDlg, DM_SETDEFID, CLOCK_IDC_BUTTON_OK, 0);\n\n SetTimer(hwndDlg, 9999, 50, NULL);\n\n PostMessage(hwndDlg, WM_APP+103, 0, 0);\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return FALSE;\n }\n\n case WM_CLOSE: {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n\n case WM_CTLCOLOREDIT: {\n HDC hdcEdit = (HDC)wParam;\n SetBkColor(hdcEdit, RGB(0xFF, 0xFF, 0xFF));\n if (!hEditBrush) {\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n }\n return (INT_PTR)hEditBrush;\n }\n\n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, inputText, sizeof(inputText));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (inputText[0] == '\\0' || isAllSpaces) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n int total_seconds;\n if (ParseInput(inputText, &total_seconds)) {\n int dialogId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n if (dialogId == CLOCK_IDD_POMODORO_TIME_DIALOG) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_POMODORO_LOOP_DIALOG) {\n WriteConfigPomodoroLoopCount(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_STARTUP_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_SHORTCUT_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n }\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n return TRUE;\n }\n break;\n\n case WM_TIMER:\n if (wParam == 9999) {\n KillTimer(hwndDlg, 9999);\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit && IsWindow(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n return TRUE;\n }\n break;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n int dlgId = GetDlgCtrlID((HWND)lParam);\n if (dlgId == CLOCK_IDD_COLOR_DIALOG) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n } else {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n }\n return TRUE;\n }\n break;\n\n case WM_APP+100:\n case WM_APP+101:\n case WM_APP+102:\n if (lParam) {\n HWND hwndEdit = (HWND)lParam;\n if (IsWindow(hwndEdit) && IsWindowVisible(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n }\n return TRUE;\n\n case WM_APP+103:\n {\n INPUT inputs[8] = {0};\n int inputCount = 0;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n SendInput(inputCount, inputs, sizeof(INPUT));\n }\n return TRUE;\n\n case WM_DESTROY:\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n g_hwndInputDialog = NULL;\n }\n break;\n }\n return FALSE;\n}\n\nINT_PTR CALLBACK AboutDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HICON hLargeIcon = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n hLargeIcon = (HICON)LoadImage(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDI_CATIME),\n IMAGE_ICON,\n ABOUT_ICON_SIZE,\n ABOUT_ICON_SIZE,\n LR_DEFAULTCOLOR);\n\n if (hLargeIcon) {\n SendDlgItemMessage(hwndDlg, IDC_ABOUT_ICON, STM_SETICON, (WPARAM)hLargeIcon, 0);\n }\n\n ApplyDialogLanguage(hwndDlg, IDD_ABOUT_DIALOG);\n\n const wchar_t* versionFormat = GetDialogLocalizedString(IDD_ABOUT_DIALOG, IDC_VERSION_TEXT);\n if (versionFormat) {\n wchar_t versionText[256];\n StringCbPrintfW(versionText, sizeof(versionText), versionFormat, CATIME_VERSION);\n SetDlgItemTextW(hwndDlg, IDC_VERSION_TEXT, versionText);\n }\n\n SetDlgItemTextW(hwndDlg, IDC_CREDIT_LINK, GetLocalizedString(L\"特别感谢猫屋敷梨梨Official提供的图标\", L\"Special thanks to Neko House Lili Official for the icon\"));\n SetDlgItemTextW(hwndDlg, IDC_CREDITS, GetLocalizedString(L\"鸣谢\", L\"Credits\"));\n SetDlgItemTextW(hwndDlg, IDC_BILIBILI_LINK, GetLocalizedString(L\"BiliBili\", L\"BiliBili\"));\n SetDlgItemTextW(hwndDlg, IDC_GITHUB_LINK, GetLocalizedString(L\"GitHub\", L\"GitHub\"));\n SetDlgItemTextW(hwndDlg, IDC_COPYRIGHT_LINK, GetLocalizedString(L\"版权声明\", L\"Copyright Notice\"));\n SetDlgItemTextW(hwndDlg, IDC_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n const wchar_t* dateFormat = GetLocalizedString(L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\");\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), dateFormat,\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return TRUE;\n }\n\n case WM_DESTROY:\n if (hLargeIcon) {\n DestroyIcon(hLargeIcon);\n hLargeIcon = NULL;\n }\n g_hwndAboutDlg = NULL;\n break;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n g_hwndAboutDlg = NULL;\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDIT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://space.bilibili.com/26087398\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_BILIBILI_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_BILIBILI_SPACE, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_GITHUB_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_GITHUB_REPO, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDITS) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/#thanks\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_SUPPORT) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support.html\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_COPYRIGHT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime#️copyright-notice\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n break;\n\n case WM_CLOSE:\n // Close all child dialogs\n EndDialog(hwndDlg, 0);\n g_hwndAboutDlg = NULL; // Clear dialog handle\n return TRUE;\n\n case WM_CTLCOLORSTATIC:\n {\n HDC hdc = (HDC)wParam;\n HWND hwndCtl = (HWND)lParam;\n \n if (GetDlgCtrlID(hwndCtl) == IDC_CREDIT_LINK || \n GetDlgCtrlID(hwndCtl) == IDC_BILIBILI_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_GITHUB_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_CREDITS ||\n GetDlgCtrlID(hwndCtl) == IDC_COPYRIGHT_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_SUPPORT) {\n SetTextColor(hdc, 0x00D26919); // Keep the same orange color (BGR format)\n SetBkMode(hdc, TRANSPARENT);\n return (INT_PTR)GetStockObject(NULL_BRUSH);\n }\n break;\n }\n }\n return FALSE;\n}\n\n// Add DPI awareness related type definitions (if not provided by the compiler)\n#ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n// DPI_AWARENESS_CONTEXT is a HANDLE\ntypedef HANDLE DPI_AWARENESS_CONTEXT;\n// Related DPI context constants definition\n#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n#endif\n\n// Show the About dialog\nvoid ShowAboutDialog(HWND hwndParent) {\n // If an About dialog already exists, close it first\n if (g_hwndAboutDlg != NULL && IsWindow(g_hwndAboutDlg)) {\n EndDialog(g_hwndAboutDlg, 0);\n g_hwndAboutDlg = NULL;\n }\n \n // Save current DPI awareness context\n HANDLE hOldDpiContext = NULL;\n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n // Function pointer type definitions\n typedef HANDLE (WINAPI* GetThreadDpiAwarenessContextFunc)(void);\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n \n GetThreadDpiAwarenessContextFunc getThreadDpiAwarenessContextFunc = \n (GetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"GetThreadDpiAwarenessContext\");\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (getThreadDpiAwarenessContextFunc && setThreadDpiAwarenessContextFunc) {\n // Save current DPI context\n hOldDpiContext = getThreadDpiAwarenessContextFunc();\n // Set to per-monitor DPI awareness V2 mode\n setThreadDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n }\n }\n \n // Create new About dialog\n g_hwndAboutDlg = CreateDialog(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_ABOUT_DIALOG), \n hwndParent, \n AboutDlgProc);\n \n // Restore original DPI awareness context\n if (hUser32 && hOldDpiContext) {\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (setThreadDpiAwarenessContextFunc) {\n setThreadDpiAwarenessContextFunc(hOldDpiContext);\n }\n }\n \n ShowWindow(g_hwndAboutDlg, SW_SHOW);\n}\n\n// Add global variable to track pomodoro loop count setting dialog handle\nstatic HWND g_hwndPomodoroLoopDialog = NULL;\n\nvoid ShowPomodoroLoopDialog(HWND hwndParent) {\n if (!g_hwndPomodoroLoopDialog) {\n g_hwndPomodoroLoopDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_LOOP_DIALOG),\n hwndParent,\n PomodoroLoopDlgProc\n );\n if (g_hwndPomodoroLoopDialog) {\n ShowWindow(g_hwndPomodoroLoopDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroLoopDialog);\n }\n}\n\n// Add subclassing procedure for loop count edit box\nLRESULT APIENTRY LoopEditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n switch (uMsg) {\n case WM_KEYDOWN: {\n if (wParam == VK_RETURN) {\n // Send BM_CLICK message to the parent window (dialog)\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwnd);\n return 0;\n }\n // Handle Ctrl+A select all\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n }\n case WM_CHAR: {\n // Handle Ctrl+A character message to prevent alert sound\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n // Prevent Enter key from generating character messages for further processing to avoid alert sound\n if (wParam == VK_RETURN) { // VK_RETURN (0x0D) is the char code for Enter\n return 0;\n }\n break;\n }\n }\n return CallWindowProc(wpOrigLoopEditProc, hwnd, uMsg, wParam, lParam);\n}\n\n// Modify helper function to handle numeric input with spaces\nBOOL IsValidNumberInput(const wchar_t* str) {\n // Check if empty\n if (!str || !*str) {\n return FALSE;\n }\n \n BOOL hasDigit = FALSE; // Used to track if at least one digit is found\n wchar_t cleanStr[16] = {0}; // Used to store cleaned string\n int cleanIndex = 0;\n \n // Traverse string, ignore spaces, only keep digits\n for (int i = 0; str[i]; i++) {\n if (iswdigit(str[i])) {\n cleanStr[cleanIndex++] = str[i];\n hasDigit = TRUE;\n } else if (!iswspace(str[i])) { // If not a space and not a digit, then invalid\n return FALSE;\n }\n }\n \n return hasDigit; // Return TRUE as long as there is at least one digit\n}\n\n// Modify PomodoroLoopDlgProc function\nINT_PTR CALLBACK PomodoroLoopDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_LOOP_DIALOG);\n \n // Set static text\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_STATIC, GetLocalizedString(L\"请输入循环次数(1-100):\", L\"Please enter loop count (1-100):\"));\n \n // Set focus to edit box\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetFocus(hwndEdit);\n \n // Subclass edit control\n wpOrigLoopEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, \n (LONG_PTR)LoopEditSubclassProc);\n \n return FALSE;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n wchar_t input_str[16];\n GetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, input_str, sizeof(input_str)/sizeof(wchar_t));\n \n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; input_str[i]; i++) {\n if (!iswspace(input_str[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (input_str[0] == L'\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n \n // Validate input and handle spaces\n if (!IsValidNumberInput(input_str)) {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n \n // Extract digits (ignoring spaces)\n wchar_t cleanStr[16] = {0};\n int cleanIndex = 0;\n for (int i = 0; input_str[i]; i++) {\n if (iswdigit(input_str[i])) {\n cleanStr[cleanIndex++] = input_str[i];\n }\n }\n \n int new_loop_count = _wtoi(cleanStr);\n if (new_loop_count >= 1 && new_loop_count <= 100) {\n // Update configuration file and global variables\n WriteConfigPomodoroLoopCount(new_loop_count);\n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroLoopDialog = NULL;\n } else {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n break;\n\n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigLoopEditProc);\n }\n break;\n\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n return FALSE;\n}\n\n// Add global variable to track website URL dialog handle\nstatic HWND g_hwndWebsiteDialog = NULL;\n\n// Website URL input dialog procedure\nINT_PTR CALLBACK WebsiteDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n // Set dialog as modal\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n \n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // If URL already exists, prefill the edit box\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, CLOCK_TIMEOUT_WEBSITE_URL);\n }\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_WEBSITE_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n char url[MAX_PATH] = {0};\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, url, sizeof(url));\n \n // Check if the input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; url[i]; i++) {\n if (!isspace((unsigned char)url[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (url[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n // Validate URL format - simple check, should at least contain http:// or https://\n if (strncmp(url, \"http://\", 7) != 0 && strncmp(url, \"https://\", 8) != 0) {\n // Add https:// prefix\n char tempUrl[MAX_PATH] = \"https://\";\n StringCbCatA(tempUrl, sizeof(tempUrl), url);\n StringCbCopyA(url, sizeof(url), tempUrl);\n }\n \n // Update configuration\n WriteConfigTimeoutWebsite(url);\n EndDialog(hwndDlg, IDOK);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // User cancelled, don't change timeout action\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n return FALSE;\n}\n\n// Show website URL input dialog\nvoid ShowWebsiteDialog(HWND hwndParent) {\n // Use modal dialog instead of modeless dialog, so we can know whether the user confirmed or cancelled\n INT_PTR result = DialogBox(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_WEBSITE_DIALOG),\n hwndParent,\n WebsiteDialogProc\n );\n \n // Only when the user clicks OK and inputs a valid URL will IDOK be returned, at which point WebsiteDialogProc has already set CLOCK_TIMEOUT_ACTION\n // If the user cancels or closes the dialog, the timeout action won't be changed\n}\n\n// Set global variable to track the Pomodoro combination dialog handle\nstatic HWND g_hwndPomodoroComboDialog = NULL;\n\n// Add Pomodoro combination dialog procedure\nINT_PTR CALLBACK PomodoroComboDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Read current pomodoro time options from configuration and format for display\n char currentOptions[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char timeStr[32];\n int seconds = POMODORO_TIMES[i];\n \n // Format time into human-readable format\n if (seconds >= 3600) {\n int hours = seconds / 3600;\n int mins = (seconds % 3600) / 60;\n int secs = seconds % 60;\n if (mins == 0 && secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh \", hours);\n else if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm \", hours, mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm%ds \", hours, mins, secs);\n } else if (seconds >= 60) {\n int mins = seconds / 60;\n int secs = seconds % 60;\n if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm \", mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm%ds \", mins, secs);\n } else {\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%ds \", seconds);\n }\n \n StringCbCatA(currentOptions, sizeof(currentOptions), timeStr);\n }\n \n // Remove trailing space\n if (strlen(currentOptions) > 0 && currentOptions[strlen(currentOptions) - 1] == ' ') {\n currentOptions[strlen(currentOptions) - 1] = '\\0';\n }\n \n // Set edit box text\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, currentOptions);\n \n // Apply multilingual support - moved here to ensure all default text is covered\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_COMBO_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || LOWORD(wParam) == IDOK) {\n char input[256] = {0};\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, input, sizeof(input));\n \n // Parse input time format and convert to seconds array\n char *token, *saveptr;\n char input_copy[256];\n StringCbCopyA(input_copy, sizeof(input_copy), input);\n \n int times[MAX_POMODORO_TIMES] = {0};\n int times_count = 0;\n \n token = strtok_r(input_copy, \" \", &saveptr);\n while (token && times_count < MAX_POMODORO_TIMES) {\n int seconds = 0;\n if (ParseTimeInput(token, &seconds)) {\n times[times_count++] = seconds;\n }\n token = strtok_r(NULL, \" \", &saveptr);\n }\n \n if (times_count > 0) {\n // Update global variables\n POMODORO_TIMES_COUNT = times_count;\n for (int i = 0; i < times_count; i++) {\n POMODORO_TIMES[i] = times[i];\n }\n \n // Update basic pomodoro times\n if (times_count > 0) POMODORO_WORK_TIME = times[0];\n if (times_count > 1) POMODORO_SHORT_BREAK = times[1];\n if (times_count > 2) POMODORO_LONG_BREAK = times[2];\n \n // Write to configuration file\n WriteConfigPomodoroTimeOptions(times, times_count);\n }\n \n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n }\n \n return FALSE;\n}\n\nvoid ShowPomodoroComboDialog(HWND hwndParent) {\n if (!g_hwndPomodoroComboDialog) {\n g_hwndPomodoroComboDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_COMBO_DIALOG),\n hwndParent,\n PomodoroComboDialogProc\n );\n if (g_hwndPomodoroComboDialog) {\n ShowWindow(g_hwndPomodoroComboDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroComboDialog);\n }\n}\n\nBOOL ParseTimeInput(const char* input, int* seconds) {\n if (!input || !seconds) return FALSE;\n\n *seconds = 0;\n char* buffer = _strdup(input);\n if (!buffer) return FALSE;\n\n int len = strlen(buffer);\n char* pos = buffer;\n int value = 0;\n int tempSeconds = 0;\n\n while (*pos) {\n if (isdigit((unsigned char)*pos)) {\n value = 0;\n while (isdigit((unsigned char)*pos)) {\n value = value * 10 + (*pos - '0');\n pos++;\n }\n\n if (*pos == 'h' || *pos == 'H') {\n tempSeconds += value * 3600;\n pos++;\n } else if (*pos == 'm' || *pos == 'M') {\n tempSeconds += value * 60;\n pos++;\n } else if (*pos == 's' || *pos == 'S') {\n tempSeconds += value;\n pos++;\n } else if (*pos == '\\0') {\n tempSeconds += value * 60;\n } else {\n free(buffer);\n return FALSE;\n }\n } else {\n pos++;\n }\n }\n\n free(buffer);\n *seconds = tempSeconds;\n return TRUE;\n}\n\nstatic HWND g_hwndNotificationMessagesDialog = NULL;\n\nINT_PTR CALLBACK NotificationMessagesDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n\n ReadNotificationMessagesConfig();\n \n // For handling UTF-8 Chinese characters, we need to convert to Unicode\n wchar_t wideText[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT)];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL1, \n GetLocalizedString(L\"Countdown timeout message:\", L\"Countdown timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL2, \n GetLocalizedString(L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL3,\n GetLocalizedString(L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"));\n \n // Localize button text\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"OK\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"Cancel\", L\"Cancel\"));\n \n // Subclass edit boxes to support Ctrl+A for select all\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n // Save original window procedure\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Apply the same subclassing process to other edit boxes\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Select all text in the first edit box\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_EDIT1, EM_SETSEL, 0, -1);\n \n // Set focus to the first edit box\n SetFocus(GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1));\n \n return FALSE; // Return FALSE because we manually set focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n // Get text from edit boxes (Unicode method)\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Save to configuration file and update global variables\n WriteConfigNotificationMessages(timeout_msg, pomodoro_msg, cycle_complete_msg);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification message settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification message settings dialog for modifying various notification prompt texts.\n */\nvoid ShowNotificationMessagesDialog(HWND hwndParent) {\n if (!g_hwndNotificationMessagesDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationMessagesConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_MESSAGES_DIALOG), \n hwndParent, \n NotificationMessagesDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationMessagesDialog);\n }\n}\n\n// Add global variable to track notification display settings dialog handle\nstatic HWND g_hwndNotificationDisplayDialog = NULL;\n\n// Add notification display settings dialog procedure\nINT_PTR CALLBACK NotificationDisplayDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set window to topmost\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n \n // Create brushes\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n \n // Read latest configuration\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n // Set current values to edit boxes\n char buffer[32];\n \n // Display time (seconds, support decimal) - convert milliseconds to seconds\n StringCbPrintfA(buffer, sizeof(buffer), \"%.1f\", (float)NOTIFICATION_TIMEOUT_MS / 1000.0f);\n // Remove trailing .0\n if (strlen(buffer) > 2 && buffer[strlen(buffer)-2] == '.' && buffer[strlen(buffer)-1] == '0') {\n buffer[strlen(buffer)-2] = '\\0';\n }\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, buffer);\n \n // Opacity (percentage)\n StringCbPrintfA(buffer, sizeof(buffer), \"%d\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, buffer);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_LABEL, \n GetLocalizedString(L\"Notification display time (sec):\", L\"Notification display time (sec):\"));\n \n // Modify edit box style, remove ES_NUMBER to allow decimal point\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n LONG style = GetWindowLong(hEditTime, GWL_STYLE);\n SetWindowLong(hEditTime, GWL_STYLE, style & ~ES_NUMBER);\n \n // Subclass edit boxes to support Enter key submission and input restrictions\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Set focus to time edit box\n SetFocus(hEditTime);\n \n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n char timeStr[32] = {0};\n char opacityStr[32] = {0};\n \n // Get user input values\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, timeStr, sizeof(timeStr));\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, opacityStr, sizeof(opacityStr));\n \n // Use more robust method to replace Chinese period\n // First get the text in Unicode format\n wchar_t wTimeStr[32] = {0};\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, wTimeStr, sizeof(wTimeStr)/sizeof(wchar_t));\n \n // Replace Chinese punctuation marks in Unicode text\n for (int i = 0; wTimeStr[i] != L'\\0'; i++) {\n // Recognize various punctuation marks as decimal point\n if (wTimeStr[i] == L'。' || // Chinese period\n wTimeStr[i] == L',' || // Chinese comma\n wTimeStr[i] == L',' || // English comma\n wTimeStr[i] == L'·' || // Chinese middle dot\n wTimeStr[i] == L'`' || // Backtick\n wTimeStr[i] == L':' || // Chinese colon\n wTimeStr[i] == L':' || // English colon\n wTimeStr[i] == L';' || // Chinese semicolon\n wTimeStr[i] == L';' || // English semicolon\n wTimeStr[i] == L'/' || // Forward slash\n wTimeStr[i] == L'\\\\' || // Backslash\n wTimeStr[i] == L'~' || // Tilde\n wTimeStr[i] == L'~' || // Full-width tilde\n wTimeStr[i] == L'、' || // Chinese enumeration comma\n wTimeStr[i] == L'.') { // Full-width period\n wTimeStr[i] = L'.'; // Replace with English decimal point\n }\n }\n \n // Convert processed Unicode text back to ASCII\n WideCharToMultiByte(CP_ACP, 0, wTimeStr, -1, \n timeStr, sizeof(timeStr), NULL, NULL);\n \n // Parse time (seconds) and convert to milliseconds\n float timeInSeconds = atof(timeStr);\n int timeInMs = (int)(timeInSeconds * 1000.0f);\n \n // Allow time to be set to 0 (no notification) or at least 100 milliseconds\n if (timeInMs > 0 && timeInMs < 100) timeInMs = 100;\n \n // Parse opacity\n int opacity = atoi(opacityStr);\n \n // Ensure opacity is in range 1-100\n if (opacity < 1) opacity = 1;\n if (opacity > 100) opacity = 100;\n \n // Write to configuration\n WriteConfigNotificationTimeout(timeInMs);\n WriteConfigNotificationOpacity(opacity);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n }\n break;\n \n // Add handling for WM_CLOSE message\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n HWND hEditOpacity = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEditOpacity, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification display settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification display settings dialog for modifying notification display time and opacity.\n */\nvoid ShowNotificationDisplayDialog(HWND hwndParent) {\n if (!g_hwndNotificationDisplayDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_DISPLAY_DIALOG), \n hwndParent, \n NotificationDisplayDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationDisplayDialog);\n }\n}\n\n// Add global variable to track the integrated notification settings dialog handle\nstatic HWND g_hwndNotificationSettingsDialog = NULL;\n\n/**\n * @brief Audio playback completion callback function\n * @param hwnd Window handle\n * \n * When audio playback completes, changes \"Stop\" button back to \"Test\" button\n */\nstatic void OnAudioPlaybackComplete(HWND hwnd) {\n if (hwnd && IsWindow(hwnd)) {\n const wchar_t* testText = GetLocalizedString(L\"Test\", L\"Test\");\n SetDlgItemTextW(hwnd, IDC_TEST_SOUND_BUTTON, testText);\n \n // Get dialog data\n HWND hwndTestButton = GetDlgItem(hwnd, IDC_TEST_SOUND_BUTTON);\n \n // Send WM_SETTEXT message to update button text\n if (hwndTestButton && IsWindow(hwndTestButton)) {\n SendMessageW(hwndTestButton, WM_SETTEXT, 0, (LPARAM)testText);\n }\n \n // Update global playback state\n if (g_hwndNotificationSettingsDialog == hwnd) {\n // Send message to dialog to notify state change\n SendMessage(hwnd, WM_APP + 100, 0, 0);\n }\n }\n}\n\n/**\n * @brief Populate audio dropdown box\n * @param hwndDlg Dialog handle\n */\nstatic void PopulateSoundComboBox(HWND hwndDlg) {\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n if (!hwndCombo) return;\n\n // Clear dropdown list\n SendMessage(hwndCombo, CB_RESETCONTENT, 0, 0);\n\n // Add \"None\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"None\", L\"None\"));\n \n // Add \"System Beep\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"System Beep\", L\"System Beep\"));\n\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to wide character path\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n\n // Build search path\n wchar_t wSearchPath[MAX_PATH];\n StringCbPrintfW(wSearchPath, sizeof(wSearchPath), L\"%s\\\\*.*\", wAudioPath);\n\n // Find audio files - using Unicode version of API\n WIN32_FIND_DATAW find_data;\n HANDLE hFind = FindFirstFileW(wSearchPath, &find_data);\n if (hFind != INVALID_HANDLE_VALUE) {\n do {\n // Check file extension\n wchar_t* ext = wcsrchr(find_data.cFileName, L'.');\n if (ext && (\n _wcsicmp(ext, L\".flac\") == 0 ||\n _wcsicmp(ext, L\".mp3\") == 0 ||\n _wcsicmp(ext, L\".wav\") == 0\n )) {\n // Add Unicode filename directly to dropdown\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)find_data.cFileName);\n }\n } while (FindNextFileW(hFind, &find_data));\n FindClose(hFind);\n }\n\n // Set currently selected audio file\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n // Check if it's the special system beep marker\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n // Select \"System Beep\" option (index 1)\n SendMessage(hwndCombo, CB_SETCURSEL, 1, 0);\n } else {\n wchar_t wSoundFile[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, NOTIFICATION_SOUND_FILE, -1, wSoundFile, MAX_PATH);\n \n // Get filename part\n wchar_t* fileName = wcsrchr(wSoundFile, L'\\\\');\n if (fileName) fileName++;\n else fileName = wSoundFile;\n \n // Find and select the file in dropdown\n int index = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)fileName);\n if (index != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, index, 0);\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n }\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n}\n\n/**\n * @brief Integrated notification settings dialog procedure\n * @param hwndDlg Dialog handle\n * @param msg Message type\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return INT_PTR Message processing result\n * \n * Integrates notification content and notification display settings in a unified interface\n */\nINT_PTR CALLBACK NotificationSettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static BOOL isPlaying = FALSE; // Add a static variable to track playback status\n static int originalVolume = 0; // Add a static variable to store original volume\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Read latest configuration to global variables\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n // Save original volume value for restoration when canceling\n originalVolume = NOTIFICATION_SOUND_VOLUME;\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG);\n \n // Set notification message text - using Unicode functions\n wchar_t wideText[256];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Set notification display time\n SYSTEMTIME st = {0};\n GetLocalTime(&st);\n \n // Read notification disabled setting\n ReadNotificationDisabledConfig();\n \n // Set checkbox based on disabled state\n CheckDlgButton(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK, NOTIFICATION_DISABLED ? BST_CHECKED : BST_UNCHECKED);\n \n // Enable/disable time control based on state\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !NOTIFICATION_DISABLED);\n \n // Set time control value - display actual configured time regardless of disabled state\n int totalSeconds = NOTIFICATION_TIMEOUT_MS / 1000;\n st.wHour = totalSeconds / 3600;\n st.wMinute = (totalSeconds % 3600) / 60;\n st.wSecond = totalSeconds % 60;\n \n // Set time control's initial value\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_SETSYSTEMTIME, \n GDT_VALID, (LPARAM)&st);\n\n // Set notification opacity slider\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n SendMessage(hwndOpacitySlider, TBM_SETRANGE, TRUE, MAKELONG(1, 100));\n SendMessage(hwndOpacitySlider, TBM_SETPOS, TRUE, NOTIFICATION_MAX_OPACITY);\n \n // Update opacity text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n // Set notification type radio buttons\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_OS:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_OS, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, BST_CHECKED);\n break;\n }\n \n // Populate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Set volume slider\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n SendMessage(hwndSlider, TBM_SETRANGE, TRUE, MAKELONG(0, 100));\n SendMessage(hwndSlider, TBM_SETPOS, TRUE, NOTIFICATION_SOUND_VOLUME);\n \n // Update volume text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", NOTIFICATION_SOUND_VOLUME);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Reset playback state on initialization\n isPlaying = FALSE;\n \n // Set audio playback completion callback\n SetAudioPlaybackCompleteCallback(hwndDlg, OnAudioPlaybackComplete);\n \n // Save dialog handle\n g_hwndNotificationSettingsDialog = hwndDlg;\n \n return TRUE;\n }\n \n case WM_HSCROLL: {\n // Handle slider drag events\n if (GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER) == (HWND)lParam) {\n // Get slider's current position\n int volume = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update volume percentage text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", volume);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Apply volume setting in real-time\n SetAudioVolume(volume);\n \n return TRUE;\n }\n else if (GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT) == (HWND)lParam) {\n // Get slider's current position\n int opacity = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update opacity percentage text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", opacity);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND:\n // Handle notification disable checkbox state change\n if (LOWORD(wParam) == IDC_DISABLE_NOTIFICATION_CHECK && HIWORD(wParam) == BN_CLICKED) {\n BOOL isChecked = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !isChecked);\n return TRUE;\n }\n else if (LOWORD(wParam) == IDOK) {\n // Get notification message text - using Unicode functions\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Get notification display time\n SYSTEMTIME st = {0};\n \n // Check if notification disable checkbox is checked\n BOOL isDisabled = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n \n // Save disabled state\n NOTIFICATION_DISABLED = isDisabled;\n WriteConfigNotificationDisabled(isDisabled);\n \n // Get notification time settings\n // Get notification time settings\n if (SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_GETSYSTEMTIME, 0, (LPARAM)&st) == GDT_VALID) {\n // Calculate total seconds: hours*3600 + minutes*60 + seconds\n int totalSeconds = st.wHour * 3600 + st.wMinute * 60 + st.wSecond;\n \n if (totalSeconds == 0) {\n // If time is 00:00:00, set to 0 (meaning disable notifications)\n NOTIFICATION_TIMEOUT_MS = 0;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n \n } else if (!isDisabled) {\n // Only update non-zero notification time if not disabled\n NOTIFICATION_TIMEOUT_MS = totalSeconds * 1000;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n }\n }\n // If notifications are disabled, don't modify notification time configuration\n \n // Get notification opacity (from slider)\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n int opacity = (int)SendMessage(hwndOpacitySlider, TBM_GETPOS, 0, 0);\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n \n // Get notification type\n if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_OS)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n }\n \n // Get selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n if (index > 0) { // 0 is \"None\" option\n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Check if \"System Beep\" is selected\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker to represent system beep\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n } else {\n NOTIFICATION_SOUND_FILE[0] = '\\0';\n }\n \n // Get volume slider position\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n NOTIFICATION_SOUND_VOLUME = volume;\n \n // Save all settings\n WriteConfigNotificationMessages(\n timeout_msg,\n pomodoro_msg,\n cycle_complete_msg\n );\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n WriteConfigNotificationOpacity(NOTIFICATION_MAX_OPACITY);\n WriteConfigNotificationType(NOTIFICATION_TYPE);\n WriteConfigNotificationSound(NOTIFICATION_SOUND_FILE);\n WriteConfigNotificationVolume(NOTIFICATION_SOUND_VOLUME);\n \n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Restore original volume setting\n NOTIFICATION_SOUND_VOLUME = originalVolume;\n \n // Reapply original volume\n SetAudioVolume(originalVolume);\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDC_TEST_SOUND_BUTTON) {\n if (!isPlaying) {\n // Currently not playing, start playback and change button text to \"Stop\"\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n \n if (index > 0) { // 0 is the \"None\" option\n // Get current slider volume and apply it\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n SetAudioVolume(volume);\n \n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Temporarily save current audio settings\n char tempSoundFile[MAX_PATH];\n StringCbCopyA(tempSoundFile, sizeof(tempSoundFile), NOTIFICATION_SOUND_FILE);\n \n // Temporarily set audio file\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n \n // Play audio\n if (PlayNotificationSound(hwndDlg)) {\n // Playback successful, change button text to \"Stop\"\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Stop\", L\"Stop\"));\n isPlaying = TRUE;\n }\n \n // Restore previous settings\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), tempSoundFile);\n }\n } else {\n // Currently playing, stop playback and restore button text\n StopNotificationSound();\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Test\", L\"Test\"));\n isPlaying = FALSE;\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDC_OPEN_SOUND_DIR_BUTTON) {\n // Get audio directory path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Ensure directory exists\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n \n // Open directory\n ShellExecuteW(hwndDlg, L\"open\", wAudioPath, NULL, NULL, SW_SHOWNORMAL);\n \n // Record currently selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Try to restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n } else {\n // If previous selection not found, default to \"None\"\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0);\n }\n }\n \n return TRUE;\n } else if (LOWORD(wParam) == IDC_NOTIFICATION_SOUND_COMBO && HIWORD(wParam) == CBN_DROPDOWN) {\n // When dropdown is about to open, reload file list\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n \n // Record currently selected file\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n }\n }\n \n return TRUE;\n }\n break;\n \n // Add custom message handling for audio playback completion notification\n case WM_APP + 100:\n // Audio playback is complete, update button state\n isPlaying = FALSE;\n return TRUE;\n \n case WM_CLOSE:\n // Make sure to stop playback when closing dialog\n if (isPlaying) {\n StopNotificationSound();\n }\n \n // Clean up callback\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Clean up callback when dialog is destroyed\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n g_hwndNotificationSettingsDialog = NULL;\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Display integrated notification settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays a unified dialog that includes both notification content and display settings\n */\nvoid ShowNotificationSettingsDialog(HWND hwndParent) {\n if (!g_hwndNotificationSettingsDialog) {\n // Ensure the latest configuration values are read first\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG), \n hwndParent, \n NotificationSettingsDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationSettingsDialog);\n }\n}"], ["/Catime/src/timer_events.c", "/**\n * @file timer_events.c\n * @brief Implementation of timer event handling\n * \n * This file implements the functionality related to the application's timer event handling,\n * including countdown and count-up mode event processing.\n */\n\n#include \n#include \n#include \"../include/timer_events.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \"../include/window.h\"\n#include \"audio_player.h\" // Include header reference\n\n// Maximum capacity of Pomodoro time list\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Index of the currently executing Pomodoro time\nint current_pomodoro_time_index = 0;\n\n// Define current_pomodoro_phase variable, which is declared as extern in pomodoro.h\nPOMODORO_PHASE current_pomodoro_phase = POMODORO_PHASE_IDLE;\n\n// Number of completed Pomodoro cycles\nint complete_pomodoro_cycles = 0;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\n\n// Variable declarations imported from main.c, for timeout actions\nextern int elapsed_time;\nextern BOOL message_shown;\n\n// Custom message text imported from config.c\nextern char CLOCK_TIMEOUT_MESSAGE_TEXT[100];\nextern char POMODORO_TIMEOUT_MESSAGE_TEXT[100]; // New Pomodoro-specific prompt\nextern char POMODORO_CYCLE_COMPLETE_TEXT[100];\n\n// Define ClockState type\ntypedef enum {\n CLOCK_STATE_IDLE,\n CLOCK_STATE_COUNTDOWN,\n CLOCK_STATE_COUNTUP,\n CLOCK_STATE_POMODORO\n} ClockState;\n\n// Define PomodoroState type\ntypedef struct {\n BOOL isLastCycle;\n int cycleIndex;\n int totalCycles;\n} PomodoroState;\n\nextern HWND g_hwnd; // Main window handle\nextern ClockState g_clockState;\nextern PomodoroState g_pomodoroState;\n\n// Timer behavior function declarations\nextern void ShowTrayNotification(HWND hwnd, const char* message);\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void OpenFileByPath(const char* filePath);\nextern void OpenWebsite(const char* url);\nextern void SleepComputer(void);\nextern void ShutdownComputer(void);\nextern void RestartComputer(void);\nextern void SetTimeDisplay(void);\nextern void ShowCountUp(HWND hwnd);\n\n// Add external function declaration to the beginning of the file or before the function\nextern void StopNotificationSound(void);\n\n/**\n * @brief Convert UTF-8 encoded char* string to wchar_t* string\n * @param utf8String Input UTF-8 string\n * @return Converted wchar_t* string, memory needs to be freed with free() after use. Returns NULL if conversion fails.\n */\nstatic wchar_t* Utf8ToWideChar(const char* utf8String) {\n if (!utf8String || utf8String[0] == '\\0') {\n return NULL; // Return NULL to handle empty strings or NULL pointers\n }\n int size_needed = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, NULL, 0);\n if (size_needed == 0) {\n // Conversion failed\n return NULL;\n }\n wchar_t* wideString = (wchar_t*)malloc(size_needed * sizeof(wchar_t));\n if (!wideString) {\n // Memory allocation failed\n return NULL;\n }\n int result = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, wideString, size_needed);\n if (result == 0) {\n // Conversion failed\n free(wideString);\n return NULL;\n }\n return wideString;\n}\n\n/**\n * @brief Convert wide character string to UTF-8 encoded regular string and display notification\n * @param hwnd Window handle\n * @param message Wide character string message to display (read from configuration and converted)\n */\nstatic void ShowLocalizedNotification(HWND hwnd, const wchar_t* message) {\n // Don't display if message is empty\n if (!message || message[0] == L'\\0') {\n return;\n }\n\n // Calculate required buffer size\n int size_needed = WideCharToMultiByte(CP_UTF8, 0, message, -1, NULL, 0, NULL, NULL);\n if (size_needed == 0) return; // Conversion failed\n\n // Allocate memory\n char* utf8Msg = (char*)malloc(size_needed);\n if (utf8Msg) {\n // Convert to UTF-8\n int result = WideCharToMultiByte(CP_UTF8, 0, message, -1, utf8Msg, size_needed, NULL, NULL);\n\n if (result > 0) {\n // Display notification using the new ShowNotification function\n ShowNotification(hwnd, utf8Msg);\n \n // If timeout action is MESSAGE, play notification audio\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE) {\n // Read the latest audio settings\n ReadNotificationSoundConfig();\n \n // Play notification audio\n PlayNotificationSound(hwnd);\n }\n }\n\n // Free memory\n free(utf8Msg);\n }\n}\n\n/**\n * @brief Set Pomodoro to work phase\n * \n * Reset all timer counts and set Pomodoro to work phase\n */\nvoid InitializePomodoro(void) {\n // Use existing enum value POMODORO_PHASE_WORK instead of POMODORO_PHASE_RUNNING\n current_pomodoro_phase = POMODORO_PHASE_WORK;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Set initial countdown to the first time value\n if (POMODORO_TIMES_COUNT > 0) {\n CLOCK_TOTAL_TIME = POMODORO_TIMES[0];\n } else {\n // If no time is configured, use default 25 minutes\n CLOCK_TOTAL_TIME = 1500;\n }\n \n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n}\n\n/**\n * @brief Handle timer messages\n * @param hwnd Window handle\n * @param wp Message parameter\n * @return BOOL Whether the message was handled\n */\nBOOL HandleTimerEvent(HWND hwnd, WPARAM wp) {\n if (wp == 1) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // In current time display mode, reset the last displayed second on each timer trigger to ensure the latest time is displayed\n extern int last_displayed_second;\n last_displayed_second = -1; // Force reset of seconds cache to ensure the latest system time is displayed each time\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n return TRUE;\n }\n\n // If timer is paused, don't update time\n if (CLOCK_IS_PAUSED) {\n return TRUE;\n }\n\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time++;\n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n if (countdown_elapsed_time < CLOCK_TOTAL_TIME) {\n countdown_elapsed_time++;\n if (countdown_elapsed_time >= CLOCK_TOTAL_TIME && !countdown_message_shown) {\n countdown_message_shown = TRUE;\n\n // Re-read message text from config file before displaying notification\n ReadNotificationMessagesConfig();\n // Force re-read notification type config to ensure latest settings are used\n ReadNotificationTypeConfig();\n \n // Variable declaration before branches to ensure availability in all branches\n wchar_t* timeoutMsgW = NULL;\n\n // Check if in Pomodoro mode - must meet all three conditions:\n // 1. Current Pomodoro phase is not IDLE \n // 2. Pomodoro time configuration is valid\n // 3. Current countdown total time matches the time at current index in the Pomodoro time list\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE && \n POMODORO_TIMES_COUNT > 0 && \n current_pomodoro_time_index < POMODORO_TIMES_COUNT &&\n CLOCK_TOTAL_TIME == POMODORO_TIMES[current_pomodoro_time_index]) {\n \n // Use Pomodoro-specific prompt message\n timeoutMsgW = Utf8ToWideChar(POMODORO_TIMEOUT_MESSAGE_TEXT);\n \n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"番茄钟时间到!\"); // Fallback\n }\n \n // Move to next time period\n current_pomodoro_time_index++;\n \n // Check if a complete cycle has been finished\n if (current_pomodoro_time_index >= POMODORO_TIMES_COUNT) {\n // Reset index back to the first time\n current_pomodoro_time_index = 0;\n \n // Increase completed cycle count\n complete_pomodoro_cycles++;\n \n // Check if all configured loop counts have been completed\n if (complete_pomodoro_cycles >= POMODORO_LOOP_COUNT) {\n // All loop counts completed, end Pomodoro\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_TOTAL_TIME = 0;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n \n // Try to read and convert completion message from config\n wchar_t* cycleCompleteMsgW = Utf8ToWideChar(POMODORO_CYCLE_COMPLETE_TEXT);\n // Display completion prompt (using config or default value)\n if (cycleCompleteMsgW) {\n ShowLocalizedNotification(hwnd, cycleCompleteMsgW);\n free(cycleCompleteMsgW); // Free completion message memory\n } else {\n ShowLocalizedNotification(hwnd, L\"所有番茄钟循环完成!\"); // Fallback\n }\n \n // Switch to idle state - add the following code\n CLOCK_COUNT_UP = FALSE; // Ensure not in count-up mode\n CLOCK_SHOW_CURRENT_TIME = FALSE; // Ensure not in current time display mode\n message_shown = TRUE; // Mark message as shown\n \n // Force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n KillTimer(hwnd, 1);\n if (timeoutMsgW) free(timeoutMsgW); // Free timeout message memory\n return TRUE;\n }\n }\n \n // Set countdown for next time period\n CLOCK_TOTAL_TIME = POMODORO_TIMES[current_pomodoro_time_index];\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n \n // If it's the first time period in a new round, display cycle prompt\n if (current_pomodoro_time_index == 0 && complete_pomodoro_cycles > 0) {\n wchar_t cycleMsg[100];\n // GetLocalizedString needs to be reconsidered, or hardcode English/Chinese\n // Temporarily keep the original approach, but ideally should be configurable\n const wchar_t* formatStr = GetLocalizedString(L\"开始第 %d 轮番茄钟\", L\"Starting Pomodoro cycle %d\");\n swprintf(cycleMsg, 100, formatStr, complete_pomodoro_cycles + 1);\n ShowLocalizedNotification(hwnd, cycleMsg); // Call the modified function\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // Not in Pomodoro mode, or switched to normal countdown mode\n // Use normal countdown prompt message\n timeoutMsgW = Utf8ToWideChar(CLOCK_TIMEOUT_MESSAGE_TEXT);\n \n // Only display notification message if timeout action is not open file, lock, shutdown, or restart\n if (CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_OPEN_FILE && \n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_LOCK &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SHUTDOWN &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_RESTART &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SLEEP) {\n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"时间到!\"); // Fallback\n }\n }\n \n // If current mode is not Pomodoro (manually switched to normal countdown), ensure not to return to Pomodoro cycle\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n (current_pomodoro_time_index >= POMODORO_TIMES_COUNT ||\n CLOCK_TOTAL_TIME != POMODORO_TIMES[current_pomodoro_time_index])) {\n // If switched to normal countdown, reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n // If sleep option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute sleep command\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n return TRUE;\n }\n \n // If shutdown option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute shutdown command\n system(\"shutdown /s /t 0\");\n return TRUE;\n }\n \n // If restart option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute restart command\n system(\"shutdown /r /t 0\");\n return TRUE;\n }\n \n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n // Notification already displayed, no additional operation needed\n break;\n case TIMEOUT_ACTION_LOCK:\n LockWorkStation();\n break;\n case TIMEOUT_ACTION_OPEN_FILE: {\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0) {\n wchar_t wPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_FILE_PATH, -1, wPath, MAX_PATH);\n \n HINSTANCE result = ShellExecuteW(NULL, L\"open\", wPath, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)result <= 32) {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"无法打开文件\", L\"Failed to open file\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case TIMEOUT_ACTION_SHOW_TIME:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to count-up mode and reset\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countup_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set Pomodoro state to idle\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n wchar_t wideUrl[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_WEBSITE_URL, -1, wideUrl, MAX_PATH);\n ShellExecuteW(NULL, L\"open\", wideUrl, NULL, NULL, SW_NORMAL);\n }\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n }\n\n // Free converted wide string memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return TRUE;\n }\n return FALSE;\n}\n\nvoid OnTimerTimeout(HWND hwnd) {\n // Execute different behaviors based on timeout action\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE: {\n char utf8Msg[256] = {0};\n \n // Select different prompt messages based on current state\n if (g_clockState == CLOCK_STATE_POMODORO) {\n // Check if Pomodoro has completed all cycles\n if (g_pomodoroState.isLastCycle && g_pomodoroState.cycleIndex >= g_pomodoroState.totalCycles - 1) {\n strncpy(utf8Msg, POMODORO_CYCLE_COMPLETE_TEXT, sizeof(utf8Msg) - 1);\n } else {\n strncpy(utf8Msg, POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n } else {\n strncpy(utf8Msg, CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n \n utf8Msg[sizeof(utf8Msg) - 1] = '\\0'; // Ensure string ends with null character\n \n // Display custom prompt message\n ShowNotification(hwnd, utf8Msg);\n \n // Read latest audio settings and play alert sound\n ReadNotificationSoundConfig();\n PlayNotificationSound(hwnd);\n \n break;\n }\n case TIMEOUT_ACTION_RUN_COMMAND: {\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n case TIMEOUT_ACTION_HTTP_REQUEST: {\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n\n }\n}\n\n// Add missing global variable definitions (if not defined elsewhere)\n#ifndef STUB_VARIABLES_DEFINED\n#define STUB_VARIABLES_DEFINED\n// Main window handle\nHWND g_hwnd = NULL;\n// Current clock state\nClockState g_clockState = CLOCK_STATE_IDLE;\n// Pomodoro state\nPomodoroState g_pomodoroState = {FALSE, 0, 1};\n#endif\n\n// Add stub function definitions if needed\n#ifndef STUB_FUNCTIONS_DEFINED\n#define STUB_FUNCTIONS_DEFINED\n__attribute__((weak)) void SleepComputer(void) {\n // This is a weak symbol definition, if there's an actual implementation elsewhere, that implementation will be used\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n}\n\n__attribute__((weak)) void ShutdownComputer(void) {\n system(\"shutdown /s /t 0\");\n}\n\n__attribute__((weak)) void RestartComputer(void) {\n system(\"shutdown /r /t 0\");\n}\n\n__attribute__((weak)) void SetTimeDisplay(void) {\n // Stub implementation for setting time display\n}\n\n__attribute__((weak)) void ShowCountUp(HWND hwnd) {\n // Stub implementation for showing count-up\n}\n#endif\n"], ["/Catime/src/tray_menu.c", "/**\n * @file tray_menu.c\n * @brief Implementation of system tray menu functionality\n * \n * This file implements the system tray menu functionality for the application, including:\n * - Right-click menu and its submenus\n * - Color selection menu\n * - Font settings menu\n * - Timeout action settings\n * - Pomodoro functionality\n * - Preset time management\n * - Multi-language interface support\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/timer.h\"\n#include \"../resource/resource.h\"\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_USE_24HOUR;\nextern BOOL CLOCK_SHOW_SECONDS;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_EDIT_MODE;\nextern char CLOCK_STARTUP_MODE[20];\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\nextern int time_options[];\nextern int time_options_count;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern char CLOCK_TIMEOUT_FILE_PATH[MAX_PATH];\nextern char CLOCK_TIMEOUT_TEXT[50];\nextern BOOL CLOCK_WINDOW_TOPMOST; ///< Whether the window is always on top\n\n// Add Pomodoro related variable declarations\nextern int POMODORO_WORK_TIME; ///< Work time (seconds)\nextern int POMODORO_SHORT_BREAK; ///< Short break time (seconds)\nextern int POMODORO_LONG_BREAK; ///< Long break time (seconds)\nextern int POMODORO_LOOP_COUNT; ///< Loop count\n\n// Pomodoro time array and count variables\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Add to external variable declaration section\nextern char CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH]; ///< URL for timeout open website\nextern int current_pomodoro_time_index; // Current Pomodoro time index\nextern POMODORO_PHASE current_pomodoro_phase; // Pomodoro phase\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t size);\nextern BOOL IsAutoStartEnabled(void);\nextern void WriteConfigStartupMode(const char* mode);\nextern void ClearColorOptions(void);\nextern void AddColorOption(const char* color);\n/// @}\n\n/**\n * @brief Read timeout action settings from configuration file\n * \n * Read the timeout action settings saved in the configuration file and update the global variable CLOCK_TIMEOUT_ACTION\n */\nvoid ReadTimeoutActionFromConfig() {\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"TIMEOUT_ACTION=\", 15) == 0) {\n int action = 0;\n sscanf(line, \"TIMEOUT_ACTION=%d\", &action);\n CLOCK_TIMEOUT_ACTION = (TimeoutActionType)action;\n break;\n }\n }\n fclose(configFile);\n }\n}\n\n/**\n * @brief Recent file structure\n * \n * Store information about recently used files, including full path and display name\n */\ntypedef struct {\n char path[MAX_PATH]; ///< Full file path\n char name[MAX_PATH]; ///< File display name (may be truncated)\n} RecentFile;\n\nextern RecentFile CLOCK_RECENT_FILES[];\nextern int CLOCK_RECENT_FILES_COUNT;\n\n/**\n * @brief Format Pomodoro time to wide string\n * @param seconds Number of seconds\n * @param buffer Output buffer\n * @param bufferSize Buffer size\n */\nstatic void FormatPomodoroTime(int seconds, wchar_t* buffer, size_t bufferSize) {\n int minutes = seconds / 60;\n int secs = seconds % 60;\n int hours = minutes / 60;\n minutes %= 60;\n \n if (hours > 0) {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d:%02d\", hours, minutes, secs);\n } else {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d\", minutes, secs);\n }\n}\n\n/**\n * @brief Truncate long file names\n * \n * @param fileName Original file name\n * @param truncated Truncated file name buffer\n * @param maxLen Maximum display length (excluding terminator)\n * \n * If the file name exceeds the specified length, it uses the format \"first 12 characters...last 12 characters.extension\" for intelligent truncation.\n * This function preserves the file extension to ensure users can identify the file type.\n */\nvoid TruncateFileName(const wchar_t* fileName, wchar_t* truncated, size_t maxLen) {\n if (!fileName || !truncated || maxLen <= 7) return; // At least need to display \"x...y\"\n \n size_t nameLen = wcslen(fileName);\n if (nameLen <= maxLen) {\n // File name does not exceed the length limit, copy directly\n wcscpy(truncated, fileName);\n return;\n }\n \n // Find the position of the last dot (extension separator)\n const wchar_t* lastDot = wcsrchr(fileName, L'.');\n const wchar_t* fileNameNoExt = fileName;\n const wchar_t* ext = L\"\";\n size_t nameNoExtLen = nameLen;\n size_t extLen = 0;\n \n if (lastDot && lastDot != fileName) {\n // Has valid extension\n ext = lastDot; // Extension including dot\n extLen = wcslen(ext);\n nameNoExtLen = lastDot - fileName; // Length of file name without extension\n }\n \n // If the pure file name length is less than or equal to 27 characters (12+3+12), use the old truncation method\n if (nameNoExtLen <= 27) {\n // Simple truncation of main file name, preserving extension\n wcsncpy(truncated, fileName, maxLen - extLen - 3);\n truncated[maxLen - extLen - 3] = L'\\0';\n wcscat(truncated, L\"...\");\n wcscat(truncated, ext);\n return;\n }\n \n // Use new truncation method: first 12 characters + ... + last 12 characters + extension\n wchar_t buffer[MAX_PATH];\n \n // Copy first 12 characters\n wcsncpy(buffer, fileName, 12);\n buffer[12] = L'\\0';\n \n // Add ellipsis\n wcscat(buffer, L\"...\");\n \n // Copy last 12 characters (excluding extension part)\n wcsncat(buffer, fileName + nameNoExtLen - 12, 12);\n \n // Add extension\n wcscat(buffer, ext);\n \n // Copy result to output buffer\n wcscpy(truncated, buffer);\n}\n\n/**\n * @brief Display color and settings menu\n * \n * @param hwnd Window handle\n * \n * Create and display the application's main settings menu, including:\n * - Edit mode toggle\n * - Timeout action settings\n * - Preset time management\n * - Startup mode settings\n * - Font selection\n * - Color settings\n * - Language selection\n * - Help and about information\n */\nvoid ShowColorMenu(HWND hwnd) {\n // Read timeout action settings from the configuration file before creating the menu\n ReadTimeoutActionFromConfig();\n \n // Set mouse cursor to default arrow to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n HMENU hMenu = CreatePopupMenu();\n \n // Add edit mode option\n AppendMenuW(hMenu, MF_STRING | (CLOCK_EDIT_MODE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_EDIT_MODE, \n GetLocalizedString(L\"编辑模式\", L\"Edit Mode\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Timeout action menu\n HMENU hTimeoutMenu = CreatePopupMenu();\n \n // 1. Show message\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_SHOW_MESSAGE, \n GetLocalizedString(L\"显示消息\", L\"Show Message\"));\n\n // 2. Show current time\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHOW_TIME ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_SHOW_TIME, \n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n\n // 3. Count up\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_COUNT_UP ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_COUNT_UP, \n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n\n // 4. Lock screen\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_LOCK ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LOCK_SCREEN,\n GetLocalizedString(L\"锁定屏幕\", L\"Lock Screen\"));\n\n // First separator\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // 5. Open file (submenu)\n HMENU hFileMenu = CreatePopupMenu();\n\n // First add recent files list\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n wchar_t wFileName[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[i].name, -1, wFileName, MAX_PATH);\n \n // Truncate long file names\n wchar_t truncatedName[MAX_PATH];\n TruncateFileName(wFileName, truncatedName, 25); // Limit to 25 characters\n \n // Check if this is the currently selected file and the current timeout action is \"open file\"\n BOOL isCurrentFile = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE && \n strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n strcmp(CLOCK_RECENT_FILES[i].path, CLOCK_TIMEOUT_FILE_PATH) == 0);\n \n // Use menu item check state to indicate selection\n AppendMenuW(hFileMenu, MF_STRING | (isCurrentFile ? MF_CHECKED : 0), \n CLOCK_IDM_RECENT_FILE_1 + i, truncatedName);\n }\n \n // Add separator if there are recent files\n if (CLOCK_RECENT_FILES_COUNT > 0) {\n AppendMenuW(hFileMenu, MF_SEPARATOR, 0, NULL);\n }\n\n // Finally add \"Browse...\" option\n AppendMenuW(hFileMenu, MF_STRING, CLOCK_IDM_BROWSE_FILE,\n GetLocalizedString(L\"浏览...\", L\"Browse...\"));\n\n // Add \"Open File\" as a submenu to the timeout action menu\n AppendMenuW(hTimeoutMenu, MF_POPUP | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE ? MF_CHECKED : MF_UNCHECKED), \n (UINT_PTR)hFileMenu, \n GetLocalizedString(L\"打开文件/软件\", L\"Open File/Software\"));\n\n // 6. Open website\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_WEBSITE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_OPEN_WEBSITE,\n GetLocalizedString(L\"打开网站\", L\"Open Website\"));\n\n // Second separator\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // Add a non-selectable hint option\n AppendMenuW(hTimeoutMenu, MF_STRING | MF_GRAYED | MF_DISABLED, \n 0, // Use ID 0 to indicate non-selectable menu item\n GetLocalizedString(L\"以下超时动作为一次性\", L\"Following actions are one-time only\"));\n\n // 7. Shutdown\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHUTDOWN,\n GetLocalizedString(L\"关机\", L\"Shutdown\"));\n\n // 8. Restart\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RESTART,\n GetLocalizedString(L\"重启\", L\"Restart\"));\n\n // 9. Sleep\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SLEEP,\n GetLocalizedString(L\"睡眠\", L\"Sleep\"));\n\n // Third separator and Advanced menu\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // Create Advanced submenu\n HMENU hAdvancedMenu = CreatePopupMenu();\n\n // Add \"Run Command\" option\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RUN_COMMAND,\n GetLocalizedString(L\"运行命令\", L\"Run Command\"));\n\n // Add \"HTTP Request\" option\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_HTTP_REQUEST,\n GetLocalizedString(L\"HTTP 请求\", L\"HTTP Request\"));\n\n // Check if any advanced option is selected to determine if the Advanced submenu should be checked\n BOOL isAdvancedOptionSelected = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ||\n CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST);\n\n // Add Advanced submenu to timeout menu - mark as checked if any advanced option is selected\n AppendMenuW(hTimeoutMenu, MF_POPUP | (isAdvancedOptionSelected ? MF_CHECKED : MF_UNCHECKED),\n (UINT_PTR)hAdvancedMenu,\n GetLocalizedString(L\"高级\", L\"Advanced\"));\n\n // Add timeout action menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeoutMenu, \n GetLocalizedString(L\"超时动作\", L\"Timeout Action\"));\n\n // Preset management menu\n HMENU hTimeOptionsMenu = CreatePopupMenu();\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDC_MODIFY_TIME_OPTIONS,\n GetLocalizedString(L\"倒计时预设\", L\"Modify Quick Countdown Options\"));\n \n // Startup settings submenu\n HMENU hStartupSettingsMenu = CreatePopupMenu();\n\n // Read current startup mode\n char currentStartupMode[20] = \"COUNTDOWN\";\n char configPath[MAX_PATH]; \n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\"); \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(configFile);\n }\n \n // Add startup mode options\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNTDOWN\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_SET_COUNTDOWN_TIME,\n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNT_UP\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_COUNT_UP,\n GetLocalizedString(L\"正计时\", L\"Stopwatch\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"SHOW_TIME\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_SHOW_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"NO_DISPLAY\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_NO_DISPLAY,\n GetLocalizedString(L\"不显示\", L\"No Display\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_SEPARATOR, 0, NULL);\n\n // Add auto-start option\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (IsAutoStartEnabled() ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_AUTO_START,\n GetLocalizedString(L\"开机自启动\", L\"Start with Windows\"));\n\n // Add startup settings menu to preset management menu\n AppendMenuW(hTimeOptionsMenu, MF_POPUP, (UINT_PTR)hStartupSettingsMenu,\n GetLocalizedString(L\"启动设置\", L\"Startup Settings\"));\n\n // Add notification settings menu - changed to direct menu item, no longer using submenu\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDM_NOTIFICATION_SETTINGS,\n GetLocalizedString(L\"通知设置\", L\"Notification Settings\"));\n\n // Add preset management menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeOptionsMenu,\n GetLocalizedString(L\"预设管理\", L\"Preset Management\"));\n \n AppendMenuW(hTimeOptionsMenu, MF_STRING | (CLOCK_WINDOW_TOPMOST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TOPMOST,\n GetLocalizedString(L\"置顶\", L\"Always on Top\"));\n\n // Add \"Hotkey Settings\" option after preset management menu\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_HOTKEY_SETTINGS,\n GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Font menu\n HMENU hMoreFontsMenu = CreatePopupMenu();\n HMENU hFontSubMenu = CreatePopupMenu();\n \n // First add commonly used fonts to the main menu\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n // These fonts are kept in the main menu\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n \n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayName[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayName, 100);\n wchar_t* dot = wcsstr(wDisplayName, L\".ttf\");\n if (dot) *dot = L'\\0';\n \n AppendMenuW(hFontSubMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayName);\n }\n }\n\n AppendMenuW(hFontSubMenu, MF_SEPARATOR, 0, NULL);\n\n // Add other fonts to the \"More\" submenu\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n // Exclude fonts already added to the main menu\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n continue;\n }\n\n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayNameMore[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayNameMore, 100);\n wchar_t* dot = wcsstr(wDisplayNameMore, L\".ttf\");\n if (dot) *dot = L'\\0';\n \n AppendMenuW(hMoreFontsMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayNameMore);\n }\n\n // Add \"More\" submenu to main font menu\n AppendMenuW(hFontSubMenu, MF_POPUP, (UINT_PTR)hMoreFontsMenu, GetLocalizedString(L\"更多\", L\"More\"));\n\n // Color menu\n HMENU hColorSubMenu = CreatePopupMenu();\n // Preset color option menu IDs start from 201 to 201+COLOR_OPTIONS_COUNT-1\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n \n MENUITEMINFO mii = { sizeof(MENUITEMINFO) };\n mii.fMask = MIIM_STRING | MIIM_ID | MIIM_STATE | MIIM_FTYPE;\n mii.fType = MFT_STRING | MFT_OWNERDRAW;\n mii.fState = strcmp(CLOCK_TEXT_COLOR, hexColor) == 0 ? MFS_CHECKED : MFS_UNCHECKED;\n mii.wID = 201 + i; // Preset color menu item IDs start from 201\n mii.dwTypeData = (LPSTR)hexColor;\n \n InsertMenuItem(hColorSubMenu, i, TRUE, &mii);\n }\n AppendMenuW(hColorSubMenu, MF_SEPARATOR, 0, NULL);\n\n // Custom color options\n HMENU hCustomizeMenu = CreatePopupMenu();\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_VALUE, \n GetLocalizedString(L\"颜色值\", L\"Color Value\"));\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_PANEL, \n GetLocalizedString(L\"颜色面板\", L\"Color Panel\"));\n\n AppendMenuW(hColorSubMenu, MF_POPUP, (UINT_PTR)hCustomizeMenu, \n GetLocalizedString(L\"自定义\", L\"Customize\"));\n\n // Add font and color menus to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hFontSubMenu, \n GetLocalizedString(L\"字体\", L\"Font\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hColorSubMenu, \n GetLocalizedString(L\"颜色\", L\"Color\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // About menu\n HMENU hAboutMenu = CreatePopupMenu();\n\n // Add \"About\" menu item here\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_ABOUT, GetLocalizedString(L\"关于\", L\"About\"));\n\n // Add separator\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n\n // Add \"Support\" option - open sponsorship page\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n \n // Add \"Feedback\" option - open different feedback links based on language\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_FEEDBACK, GetLocalizedString(L\"反馈\", L\"Feedback\"));\n \n // Add separator\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n \n // Add \"Help\" option - open user guide webpage\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_HELP, GetLocalizedString(L\"使用指南\", L\"User Guide\"));\n\n // Add \"Check for Updates\" option\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_CHECK_UPDATE, \n GetLocalizedString(L\"检查更新\", L\"Check for Updates\"));\n\n // Language selection menu\n HMENU hLangMenu = CreatePopupMenu();\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE, L\"简体中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE_TRAD, L\"繁體中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_ENGLISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_ENGLISH, L\"English\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_SPANISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_SPANISH, L\"Español\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_FRENCH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_FRENCH, L\"Français\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_GERMAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_GERMAN, L\"Deutsch\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_RUSSIAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_RUSSIAN, L\"Русский\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_PORTUGUESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_PORTUGUESE, L\"Português\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_JAPANESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_JAPANESE, L\"日本語\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_KOREAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_KOREAN, L\"한국어\");\n\n AppendMenuW(hAboutMenu, MF_POPUP, (UINT_PTR)hLangMenu, GetLocalizedString(L\"语言\", L\"Language\"));\n\n // Add reset option to the end of the help menu\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, 200,\n GetLocalizedString(L\"重置\", L\"Reset\"));\n\n // Add about menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hAboutMenu,\n GetLocalizedString(L\"帮助\", L\"Help\"));\n\n // Only keep exit option\n AppendMenuW(hMenu, MF_STRING, 109,\n GetLocalizedString(L\"退出\", L\"Exit\"));\n \n // Display menu\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); // This will allow the menu to close automatically when clicking outside\n DestroyMenu(hMenu);\n}\n\n/**\n * @brief Display tray right-click menu\n * \n * @param hwnd Window handle\n * \n * Create and display the system tray right-click menu, dynamically adjusting menu items based on current application state. Includes:\n * - Timer control (pause/resume, restart)\n * - Time display settings (24-hour format, show seconds)\n * - Pomodoro clock settings\n * - Count-up and countdown mode switching\n * - Quick time preset options\n */\nvoid ShowContextMenu(HWND hwnd) {\n // Read timeout action settings from configuration file before creating the menu\n ReadTimeoutActionFromConfig();\n \n // Set mouse cursor to default arrow to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n HMENU hMenu = CreatePopupMenu();\n \n // Timer management menu - added at the top\n HMENU hTimerManageMenu = CreatePopupMenu();\n \n // Set conditions for whether submenu items should be enabled\n // Timer options should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress\n // 3. If in countdown mode, the timer hasn't ended yet (countdown elapsed time is less than total time)\n BOOL timerRunning = (!CLOCK_SHOW_CURRENT_TIME && \n (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0 && countdown_elapsed_time < CLOCK_TOTAL_TIME)));\n \n // Pause/Resume text changes based on current state\n const wchar_t* pauseResumeText = CLOCK_IS_PAUSED ? \n GetLocalizedString(L\"继续\", L\"Resume\") : \n GetLocalizedString(L\"暂停\", L\"Pause\");\n \n // Submenu items are disabled based on conditions, but parent menu item remains selectable\n AppendMenuW(hTimerManageMenu, MF_STRING | (timerRunning ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_PAUSE_RESUME, pauseResumeText);\n \n // Restart option should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress (regardless of whether countdown has ended)\n BOOL canRestart = (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0)));\n \n AppendMenuW(hTimerManageMenu, MF_STRING | (canRestart ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_RESTART, \n GetLocalizedString(L\"重新开始\", L\"Start Over\"));\n \n // Add timer management menu to main menu - parent menu item is always enabled\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimerManageMenu,\n GetLocalizedString(L\"计时管理\", L\"Timer Control\"));\n \n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n \n // Time display menu\n HMENU hTimeMenu = CreatePopupMenu();\n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_CURRENT_TIME ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_CURRENT_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_USE_24HOUR ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_24HOUR_FORMAT,\n GetLocalizedString(L\"24小时制\", L\"24-Hour Format\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_SECONDS ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_SECONDS,\n GetLocalizedString(L\"显示秒数\", L\"Show Seconds\"));\n \n AppendMenuW(hMenu, MF_POPUP,\n (UINT_PTR)hTimeMenu,\n GetLocalizedString(L\"时间显示\", L\"Time Display\"));\n\n // Before Pomodoro menu, first read the latest configuration values\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\");\n POMODORO_TIMES_COUNT = 0; // Initialize to 0\n \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n char* options = line + 22;\n char* token;\n int index = 0;\n \n token = strtok(options, \",\");\n while (token && index < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[index++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Set the actual number of time options\n POMODORO_TIMES_COUNT = index;\n \n // Ensure at least one valid value\n if (index > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (index > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (index > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[2];\n }\n }\n else if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n sscanf(line, \"POMODORO_LOOP_COUNT=%d\", &POMODORO_LOOP_COUNT);\n // Ensure loop count is at least 1\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n }\n }\n fclose(configFile);\n }\n\n // Pomodoro menu\n HMENU hPomodoroMenu = CreatePopupMenu();\n \n // Add timeBuffer declaration\n wchar_t timeBuffer[64]; // For storing formatted time string\n \n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_START,\n GetLocalizedString(L\"开始\", L\"Start\"));\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Create menu items for each Pomodoro time\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n FormatPomodoroTime(POMODORO_TIMES[i], timeBuffer, sizeof(timeBuffer)/sizeof(wchar_t));\n \n // Support both old and new ID systems\n UINT menuId;\n if (i == 0) menuId = CLOCK_IDM_POMODORO_WORK;\n else if (i == 1) menuId = CLOCK_IDM_POMODORO_BREAK;\n else if (i == 2) menuId = CLOCK_IDM_POMODORO_LBREAK;\n else menuId = CLOCK_IDM_POMODORO_TIME_BASE + i;\n \n // Check if this is the active Pomodoro phase\n BOOL isCurrentPhase = (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n current_pomodoro_time_index == i &&\n !CLOCK_SHOW_CURRENT_TIME &&\n !CLOCK_COUNT_UP && // Add check for not being in count-up mode\n CLOCK_TOTAL_TIME == POMODORO_TIMES[i]);\n \n // Add check mark if it's the current phase\n AppendMenuW(hPomodoroMenu, MF_STRING | (isCurrentPhase ? MF_CHECKED : MF_UNCHECKED), \n menuId, timeBuffer);\n }\n\n // Add loop count option\n wchar_t menuText[64];\n _snwprintf(menuText, sizeof(menuText)/sizeof(wchar_t),\n GetLocalizedString(L\"循环次数: %d\", L\"Loop Count: %d\"),\n POMODORO_LOOP_COUNT);\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_LOOP_COUNT, menuText);\n\n\n // Add separator\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Add combination option\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_COMBINATION,\n GetLocalizedString(L\"组合\", L\"Combination\"));\n \n // Add Pomodoro menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hPomodoroMenu,\n GetLocalizedString(L\"番茄时钟\", L\"Pomodoro\"));\n\n // Count-up menu - changed to direct click to start\n AppendMenuW(hMenu, MF_STRING | (CLOCK_COUNT_UP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_COUNT_UP_START,\n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n\n // Add \"Set Countdown\" option below Count-up\n AppendMenuW(hMenu, MF_STRING, 101, \n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Add quick time options\n for (int i = 0; i < time_options_count; i++) {\n wchar_t menu_item[20];\n _snwprintf(menu_item, sizeof(menu_item)/sizeof(wchar_t), L\"%d\", time_options[i]);\n AppendMenuW(hMenu, MF_STRING, 102 + i, menu_item);\n }\n\n // Display menu\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); // This will allow the menu to close automatically when clicking outside\n DestroyMenu(hMenu);\n}"], ["/Catime/src/notification.c", "/**\n * @file notification.c\n * @brief Application notification system implementation\n * \n * This module implements various notification functions of the application, including:\n * 1. Custom styled popup notification windows with fade-in/fade-out animation effects\n * 2. System tray notification message integration\n * 3. Creation, display and lifecycle management of notification windows\n * \n * The notification system supports UTF-8 encoded Chinese text to ensure correct display in multilingual environments.\n */\n\n#include \n#include \n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\" // Contains definitions of all IDs and constants\n#include // For GET_X_LPARAM and GET_Y_LPARAM macros\n\n// Imported from config.h\n// New: notification type configuration\nextern NotificationType NOTIFICATION_TYPE;\n\n/**\n * Notification window animation state enumeration\n * Tracks the current animation phase of the notification window\n */\ntypedef enum {\n ANIM_FADE_IN, // Fade-in phase - opacity increases from 0 to target value\n ANIM_VISIBLE, // Fully visible phase - maintains maximum opacity\n ANIM_FADE_OUT, // Fade-out phase - opacity decreases from maximum to 0\n} AnimationState;\n\n// Forward declarations\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid RegisterNotificationClass(HINSTANCE hInstance);\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius);\n\n/**\n * @brief Calculate the width required for text rendering\n * @param hdc Device context\n * @param text Text to measure\n * @param font Font to use\n * @return int Width required for text rendering (pixels)\n */\nint CalculateTextWidth(HDC hdc, const wchar_t* text, HFONT font) {\n HFONT oldFont = (HFONT)SelectObject(hdc, font);\n SIZE textSize;\n GetTextExtentPoint32W(hdc, text, wcslen(text), &textSize);\n SelectObject(hdc, oldFont);\n return textSize.cx;\n}\n\n/**\n * @brief Show notification (based on configured notification type)\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays different styles of notifications based on the configured notification type\n */\nvoid ShowNotification(HWND hwnd, const char* message) {\n // Read the latest notification type configuration\n ReadNotificationTypeConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Choose the corresponding notification method based on notification type\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n ShowToastNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n ShowModalNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_OS:\n ShowTrayNotification(hwnd, message);\n break;\n default:\n // Default to using Catime notification window\n ShowToastNotification(hwnd, message);\n break;\n }\n}\n\n/**\n * Modal dialog thread parameter structure\n */\ntypedef struct {\n HWND hwnd; // Parent window handle\n char message[512]; // Message content\n} DialogThreadParams;\n\n/**\n * @brief Thread function to display modal dialog\n * @param lpParam Thread parameter, pointer to DialogThreadParams structure\n * @return DWORD Thread return value\n */\nDWORD WINAPI ShowModalDialogThread(LPVOID lpParam) {\n DialogThreadParams* params = (DialogThreadParams*)lpParam;\n \n // Convert UTF-8 message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, params->message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, display English version directly\n MessageBoxA(params->hwnd, params->message, \"Catime\", MB_OK);\n free(params);\n return 0;\n }\n \n MultiByteToWideChar(CP_UTF8, 0, params->message, -1, wmessage, wlen);\n \n // Display modal dialog with fixed title \"Catime\"\n MessageBoxW(params->hwnd, wmessage, L\"Catime\", MB_OK);\n \n // Free allocated memory\n free(wmessage);\n free(params);\n \n return 0;\n}\n\n/**\n * @brief Display system modal dialog notification\n * @param hwnd Parent window handle\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a modal dialog in a separate thread, which won't block the main program\n */\nvoid ShowModalNotification(HWND hwnd, const char* message) {\n // Create thread parameter structure\n DialogThreadParams* params = (DialogThreadParams*)malloc(sizeof(DialogThreadParams));\n if (!params) return;\n \n // Copy parameters\n params->hwnd = hwnd;\n strncpy(params->message, message, sizeof(params->message) - 1);\n params->message[sizeof(params->message) - 1] = '\\0';\n \n // Create new thread to display dialog\n HANDLE hThread = CreateThread(\n NULL, // Default security attributes\n 0, // Default stack size\n ShowModalDialogThread, // Thread function\n params, // Thread parameter\n 0, // Run thread immediately\n NULL // Don't receive thread ID\n );\n \n // If thread creation fails, free resources\n if (hThread == NULL) {\n free(params);\n // Fall back to non-blocking notification method\n MessageBeep(MB_OK);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Close thread handle, let system clean up automatically\n CloseHandle(hThread);\n}\n\n/**\n * @brief Display custom styled toast notification\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a custom notification window with animation effects in the bottom right corner of the screen:\n * 1. Register notification window class (if needed)\n * 2. Calculate notification display position (bottom right of work area)\n * 3. Create notification window with fade-in/fade-out effects\n * 4. Set auto-close timer\n * \n * Note: If creating custom notification window fails, will fall back to using system tray notification\n */\nvoid ShowToastNotification(HWND hwnd, const char* message) {\n static BOOL isClassRegistered = FALSE;\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n \n // Dynamically read the latest notification settings before displaying notification\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Register notification window class (if not already registered)\n if (!isClassRegistered) {\n RegisterNotificationClass(hInstance);\n isClassRegistered = TRUE;\n }\n \n // Convert message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, fall back to system tray notification\n ShowTrayNotification(hwnd, message);\n return;\n }\n MultiByteToWideChar(CP_UTF8, 0, message, -1, wmessage, wlen);\n \n // Calculate width needed for text\n HDC hdc = GetDC(hwnd);\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Calculate text width and add margins\n int textWidth = CalculateTextWidth(hdc, wmessage, contentFont);\n int notificationWidth = textWidth + 40; // 20 pixel margin on each side\n \n // Ensure width is within allowed range\n if (notificationWidth < NOTIFICATION_MIN_WIDTH) \n notificationWidth = NOTIFICATION_MIN_WIDTH;\n if (notificationWidth > NOTIFICATION_MAX_WIDTH) \n notificationWidth = NOTIFICATION_MAX_WIDTH;\n \n DeleteObject(contentFont);\n ReleaseDC(hwnd, hdc);\n \n // Get work area size, calculate notification window position (bottom right)\n RECT workArea;\n SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);\n \n int x = workArea.right - notificationWidth - 20;\n int y = workArea.bottom - NOTIFICATION_HEIGHT - 20;\n \n // Create notification window, add layered support for transparency effects\n HWND hNotification = CreateWindowExW(\n WS_EX_TOPMOST | WS_EX_LAYERED | WS_EX_TOOLWINDOW, // Keep on top and hide from taskbar\n NOTIFICATION_CLASS_NAME,\n L\"Catime Notification\", // Window title (not visible)\n WS_POPUP, // Borderless popup window style\n x, y, // Bottom right screen position\n notificationWidth, NOTIFICATION_HEIGHT,\n NULL, NULL, hInstance, NULL\n );\n \n // Fall back to system tray notification if creation fails\n if (!hNotification) {\n free(wmessage);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Save message text and window width to window properties\n SetPropW(hNotification, L\"MessageText\", (HANDLE)wmessage);\n SetPropW(hNotification, L\"WindowWidth\", (HANDLE)(LONG_PTR)notificationWidth);\n \n // Set initial animation state to fade-in\n SetPropW(hNotification, L\"AnimState\", (HANDLE)ANIM_FADE_IN);\n SetPropW(hNotification, L\"Opacity\", (HANDLE)0); // Initial opacity is 0\n \n // Set initial window to completely transparent\n SetLayeredWindowAttributes(hNotification, 0, 0, LWA_ALPHA);\n \n // Show window but don't activate (don't steal focus)\n ShowWindow(hNotification, SW_SHOWNOACTIVATE);\n UpdateWindow(hNotification);\n \n // Start fade-in animation\n SetTimer(hNotification, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n \n // Set auto-close timer, using globally configured timeout\n SetTimer(hNotification, NOTIFICATION_TIMER_ID, NOTIFICATION_TIMEOUT_MS, NULL);\n}\n\n/**\n * @brief Register notification window class\n * @param hInstance Application instance handle\n * \n * Registers custom notification window class with Windows, defining basic behavior and appearance:\n * 1. Set window procedure function\n * 2. Define default cursor and background\n * 3. Specify unique window class name\n * \n * This function is only called the first time a notification is displayed, subsequent calls reuse the registered class.\n */\nvoid RegisterNotificationClass(HINSTANCE hInstance) {\n WNDCLASSEXW wc = {0};\n wc.cbSize = sizeof(WNDCLASSEXW);\n wc.lpfnWndProc = NotificationWndProc;\n wc.hInstance = hInstance;\n wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n wc.lpszClassName = NOTIFICATION_CLASS_NAME;\n \n RegisterClassExW(&wc);\n}\n\n/**\n * @brief Notification window message processing procedure\n * @param hwnd Window handle\n * @param msg Message ID\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return LRESULT Message processing result\n * \n * Handles all Windows messages for the notification window, including:\n * - WM_PAINT: Draw notification window content (title, message text)\n * - WM_TIMER: Handle auto-close and animation effects\n * - WM_LBUTTONDOWN: Handle user click to close\n * - WM_DESTROY: Release window resources\n * \n * Specifically handles animation state transition logic to ensure smooth fade-in/fade-out effects.\n */\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_PAINT: {\n PAINTSTRUCT ps;\n HDC hdc = BeginPaint(hwnd, &ps);\n \n // Get window client area size\n RECT clientRect;\n GetClientRect(hwnd, &clientRect);\n \n // Create compatible DC and bitmap for double-buffered drawing to avoid flickering\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, clientRect.right, clientRect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n \n // Fill white background\n HBRUSH whiteBrush = CreateSolidBrush(RGB(255, 255, 255));\n FillRect(memDC, &clientRect, whiteBrush);\n DeleteObject(whiteBrush);\n \n // Draw rectangle with border\n DrawRoundedRectangle(memDC, clientRect, 0);\n \n // Set text drawing mode to transparent background\n SetBkMode(memDC, TRANSPARENT);\n \n // Create title font - bold\n HFONT titleFont = CreateFontW(22, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Create message content font\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Draw title \"Catime\"\n SelectObject(memDC, titleFont);\n SetTextColor(memDC, RGB(0, 0, 0));\n RECT titleRect = {15, 10, clientRect.right - 15, 35};\n DrawTextW(memDC, L\"Catime\", -1, &titleRect, DT_SINGLELINE);\n \n // Draw message content - placed below title, using single line mode\n SelectObject(memDC, contentFont);\n SetTextColor(memDC, RGB(100, 100, 100));\n const wchar_t* message = (const wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n RECT textRect = {15, 35, clientRect.right - 15, clientRect.bottom - 10};\n // Use DT_SINGLELINE|DT_END_ELLIPSIS to ensure text is displayed in one line, with ellipsis for long text\n DrawTextW(memDC, message, -1, &textRect, DT_SINGLELINE|DT_END_ELLIPSIS);\n }\n \n // Copy content from memory DC to window DC\n BitBlt(hdc, 0, 0, clientRect.right, clientRect.bottom, memDC, 0, 0, SRCCOPY);\n \n // Clean up resources\n SelectObject(memDC, oldBitmap);\n DeleteObject(titleFont);\n DeleteObject(contentFont);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n \n EndPaint(hwnd, &ps);\n return 0;\n }\n \n case WM_TIMER:\n if (wParam == NOTIFICATION_TIMER_ID) {\n // Auto-close timer triggered, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // Check current state - only start fade-out when fully visible\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState == ANIM_VISIBLE) {\n // Set to fade-out state\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start animation timer\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n return 0;\n }\n else if (wParam == ANIMATION_TIMER_ID) {\n // Handle animation effect timer\n AnimationState state = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n DWORD opacityVal = (DWORD)(DWORD_PTR)GetPropW(hwnd, L\"Opacity\");\n BYTE opacity = (BYTE)opacityVal;\n \n // Calculate maximum opacity value (percentage converted to 0-255 range)\n BYTE maxOpacity = (BYTE)((NOTIFICATION_MAX_OPACITY * 255) / 100);\n \n switch (state) {\n case ANIM_FADE_IN:\n // Fade-in animation - gradually increase opacity\n if (opacity >= maxOpacity - ANIMATION_STEP) {\n // Reached maximum opacity, completed fade-in\n opacity = maxOpacity;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n \n // Switch to visible state and stop animation\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_VISIBLE);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n } else {\n // Normal fade-in - increase by one step each time\n opacity += ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_FADE_OUT:\n // Fade-out animation - gradually decrease opacity\n if (opacity <= ANIMATION_STEP) {\n // Completely transparent, destroy window\n KillTimer(hwnd, ANIMATION_TIMER_ID); // Make sure to stop timer first\n DestroyWindow(hwnd);\n } else {\n // Normal fade-out - decrease by one step each time\n opacity -= ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_VISIBLE:\n // Fully visible state doesn't need animation, stop timer\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n break;\n }\n return 0;\n }\n break;\n \n case WM_LBUTTONDOWN: {\n // Handle left mouse button click event (close notification early)\n \n // Get current state - only respond to clicks when fully visible or after fade-in completes\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState != ANIM_VISIBLE) {\n return 0; // Ignore click, avoid interference during animation\n }\n \n // Click anywhere, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID); // Stop auto-close timer\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n return 0;\n }\n \n case WM_DESTROY: {\n // Cleanup work when window is destroyed\n \n // Stop all timers\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n \n // Free message text memory\n wchar_t* message = (wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n free(message);\n }\n \n // Remove all window properties\n RemovePropW(hwnd, L\"MessageText\");\n RemovePropW(hwnd, L\"AnimState\");\n RemovePropW(hwnd, L\"Opacity\");\n return 0;\n }\n }\n \n return DefWindowProc(hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Draw rectangle with border\n * @param hdc Device context\n * @param rect Rectangle area\n * @param radius Corner radius (unused)\n * \n * Draws a rectangle with light gray border in the specified device context.\n * This function reserves the corner radius parameter, but current implementation uses standard rectangle.\n * Can be extended to support true rounded rectangles in future versions.\n */\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius) {\n // Create light gray border pen\n HPEN pen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n HPEN oldPen = (HPEN)SelectObject(hdc, pen);\n \n // Use normal rectangle instead of rounded rectangle\n Rectangle(hdc, rect.left, rect.top, rect.right, rect.bottom);\n \n // Clean up resources\n SelectObject(hdc, oldPen);\n DeleteObject(pen);\n}\n\n/**\n * @brief Close all currently displayed Catime notification windows\n * \n * Find and close all notification windows created by Catime, ignoring their current display time settings,\n * directly start fade-out animation. Usually called when switching timer modes to ensure notifications don't continue to display.\n */\nvoid CloseAllNotifications(void) {\n // Find all notification windows created by Catime\n HWND hwnd = NULL;\n HWND hwndPrev = NULL;\n \n // Use FindWindowExW to find each matching window one by one\n // First call with hwndPrev as NULL finds the first window\n // Subsequent calls pass the previously found window handle to find the next window\n while ((hwnd = FindWindowExW(NULL, hwndPrev, NOTIFICATION_CLASS_NAME, NULL)) != NULL) {\n // Check current state\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n \n // Stop current auto-close timer\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // If window hasn't started fading out yet, start fade-out animation\n if (currentState != ANIM_FADE_OUT) {\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start fade-out animation\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n \n // Save current window handle for next search\n hwndPrev = hwnd;\n }\n}\n"], ["/Catime/src/timer.c", "/**\n * @file timer.c\n * @brief Implementation of core timer functionality\n * \n * This file contains the implementation of the core timer logic, including time format conversion, \n * input parsing, configuration saving, and other functionalities,\n * while maintaining various timer states and configuration parameters.\n */\n\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n/** @name Timer status flags\n * @{ */\nBOOL CLOCK_IS_PAUSED = FALSE; ///< Timer pause status flag\nBOOL CLOCK_SHOW_CURRENT_TIME = FALSE; ///< Show current time mode flag\nBOOL CLOCK_USE_24HOUR = TRUE; ///< Use 24-hour format flag\nBOOL CLOCK_SHOW_SECONDS = TRUE; ///< Show seconds flag\nBOOL CLOCK_COUNT_UP = FALSE; ///< Countdown/count-up mode flag\nchar CLOCK_STARTUP_MODE[20] = \"COUNTDOWN\"; ///< Startup mode (countdown/count-up)\n/** @} */\n\n/** @name Timer time parameters \n * @{ */\nint CLOCK_TOTAL_TIME = 0; ///< Total timer time (seconds)\nint countdown_elapsed_time = 0; ///< Countdown elapsed time (seconds)\nint countup_elapsed_time = 0; ///< Count-up accumulated time (seconds)\ntime_t CLOCK_LAST_TIME_UPDATE = 0; ///< Last update timestamp\n\n// High-precision timer related variables\nLARGE_INTEGER timer_frequency; ///< High-precision timer frequency\nLARGE_INTEGER timer_last_count; ///< Last timing point\nBOOL high_precision_timer_initialized = FALSE; ///< High-precision timer initialization flag\n/** @} */\n\n/** @name Message status flags\n * @{ */\nBOOL countdown_message_shown = FALSE; ///< Countdown completion message display status\nBOOL countup_message_shown = FALSE; ///< Count-up completion message display status\nint pomodoro_work_cycles = 0; ///< Pomodoro work cycle count\n/** @} */\n\n/** @name Timeout action configuration\n * @{ */\nTimeoutActionType CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE; ///< Timeout action type\nchar CLOCK_TIMEOUT_TEXT[50] = \"\"; ///< Timeout display text\nchar CLOCK_TIMEOUT_FILE_PATH[MAX_PATH] = \"\"; ///< Timeout executable file path\n/** @} */\n\n/** @name Pomodoro time settings\n * @{ */\nint POMODORO_WORK_TIME = 25 * 60; ///< Pomodoro work time (25 minutes)\nint POMODORO_SHORT_BREAK = 5 * 60; ///< Pomodoro short break time (5 minutes)\nint POMODORO_LONG_BREAK = 15 * 60; ///< Pomodoro long break time (15 minutes)\nint POMODORO_LOOP_COUNT = 1; ///< Pomodoro loop count (default 1 time)\n/** @} */\n\n/** @name Preset time options\n * @{ */\nint time_options[MAX_TIME_OPTIONS]; ///< Preset time options array\nint time_options_count = 0; ///< Number of valid preset times\n/** @} */\n\n/** Last displayed time (seconds), used to prevent time display jumping phenomenon */\nint last_displayed_second = -1;\n\n/**\n * @brief Initialize high-precision timer\n * \n * Get system timer frequency and record initial timing point\n * @return BOOL Whether initialization was successful\n */\nBOOL InitializeHighPrecisionTimer(void) {\n if (!QueryPerformanceFrequency(&timer_frequency)) {\n return FALSE; // System does not support high-precision timer\n }\n \n if (!QueryPerformanceCounter(&timer_last_count)) {\n return FALSE; // Failed to get current count\n }\n \n high_precision_timer_initialized = TRUE;\n return TRUE;\n}\n\n/**\n * @brief Calculate milliseconds elapsed since last call\n * \n * Use high-precision timer to calculate exact time interval\n * @return double Elapsed milliseconds\n */\ndouble GetElapsedMilliseconds(void) {\n if (!high_precision_timer_initialized) {\n if (!InitializeHighPrecisionTimer()) {\n return 0.0; // Initialization failed, return 0\n }\n }\n \n LARGE_INTEGER current_count;\n if (!QueryPerformanceCounter(¤t_count)) {\n return 0.0; // Failed to get current count\n }\n \n // Calculate time difference (convert to milliseconds)\n double elapsed = (double)(current_count.QuadPart - timer_last_count.QuadPart) * 1000.0 / (double)timer_frequency.QuadPart;\n \n // Update last timing point\n timer_last_count = current_count;\n \n return elapsed;\n}\n\n/**\n * @brief Update elapsed time for countdown/count-up\n * \n * Use high-precision timer to calculate time elapsed since last call, and update\n * countup_elapsed_time (count-up mode) or countdown_elapsed_time (countdown mode) accordingly.\n * No updates are made in pause state.\n */\nvoid UpdateElapsedTime(void) {\n if (CLOCK_IS_PAUSED) {\n return; // Do not update in pause state\n }\n \n double elapsed_ms = GetElapsedMilliseconds();\n \n if (CLOCK_COUNT_UP) {\n // Count-up mode\n countup_elapsed_time += (int)(elapsed_ms / 1000.0);\n } else {\n // Countdown mode\n countdown_elapsed_time += (int)(elapsed_ms / 1000.0);\n \n // Ensure does not exceed total time\n if (countdown_elapsed_time > CLOCK_TOTAL_TIME) {\n countdown_elapsed_time = CLOCK_TOTAL_TIME;\n }\n }\n}\n\n/**\n * @brief Format display time\n * @param remaining_time Remaining time (seconds)\n * @param[out] time_text Formatted time string output buffer\n * \n * Format time as a string according to current configuration (12/24 hour format, whether to show seconds, countdown/count-up mode).\n * Supports three display modes: current system time, countdown remaining time, count-up accumulated time.\n */\nvoid FormatTime(int remaining_time, char* time_text) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // Get local time\n SYSTEMTIME st;\n GetLocalTime(&st);\n \n // Check time continuity, prevent second jumping display\n if (last_displayed_second != -1) {\n // If not consecutive seconds, and not a cross-minute situation\n if (st.wSecond != (last_displayed_second + 1) % 60 && \n !(last_displayed_second == 59 && st.wSecond == 0)) {\n // Relax conditions, allow larger differences to sync, ensure not lagging behind for long\n if (st.wSecond != last_displayed_second) {\n // Directly use system time seconds\n last_displayed_second = st.wSecond;\n }\n } else {\n // Time is consecutive, normal update\n last_displayed_second = st.wSecond;\n }\n } else {\n // First display, initialize record\n last_displayed_second = st.wSecond;\n }\n \n int hour = st.wHour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, st.wMinute, last_displayed_second);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, st.wMinute);\n }\n return;\n }\n\n if (CLOCK_COUNT_UP) {\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n return;\n }\n\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int remaining = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining <= 0) {\n // Do not return empty string, show 0:00 instead\n sprintf(time_text, \" 0:00\");\n return;\n }\n\n int hours = remaining / 3600;\n int minutes = (remaining % 3600) / 60;\n int seconds = remaining % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n if (minutes >= 10) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n }\n } else {\n if (seconds < 10) {\n sprintf(time_text, \" %d\", seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n }\n}\n\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n */\n\n// Detailed explanation of parsing logic and boundary handling\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n * \n * Parsing process:\n * 1. First check the validity of the input\n * 2. Detect if it's a target time format (ending with 't' or 'T')\n * - If so, calculate seconds from current to target time, if time has passed set to same time tomorrow\n * 3. Otherwise, check if it contains unit identifiers (h/m/s)\n * - If it does, process according to units\n * - If not, decide processing method based on number of space-separated numbers\n * \n * Boundary handling:\n * - Invalid input returns 0\n * - Negative or zero value returns 0\n * - Value exceeding INT_MAX returns 0\n */\nint ParseInput(const char* input, int* total_seconds) {\n if (!isValidInput(input)) return 0;\n\n int total = 0;\n char input_copy[256];\n strncpy(input_copy, input, sizeof(input_copy)-1);\n input_copy[sizeof(input_copy)-1] = '\\0';\n\n // Check if it's a target time format (ending with 't' or 'T')\n int len = strlen(input_copy);\n if (len > 0 && (input_copy[len-1] == 't' || input_copy[len-1] == 'T')) {\n // Remove 't' or 'T' suffix\n input_copy[len-1] = '\\0';\n \n // Get current time\n time_t now = time(NULL);\n struct tm *tm_now = localtime(&now);\n \n // Target time, initialize to current date\n struct tm tm_target = *tm_now;\n \n // Parse target time\n int hour = -1, minute = -1, second = -1;\n int count = 0;\n char *token = strtok(input_copy, \" \");\n \n while (token && count < 3) {\n int value = atoi(token);\n if (count == 0) hour = value;\n else if (count == 1) minute = value;\n else if (count == 2) second = value;\n count++;\n token = strtok(NULL, \" \");\n }\n \n // Set target time, set according to provided values, defaults to 0 if not provided\n if (hour >= 0) {\n tm_target.tm_hour = hour;\n \n // If only hour provided, set minute and second to 0\n if (minute < 0) {\n tm_target.tm_min = 0;\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_min = minute;\n \n // If second not provided, set to 0\n if (second < 0) {\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_sec = second;\n }\n }\n }\n \n // Calculate time difference (seconds)\n time_t target_time = mktime(&tm_target);\n \n // If target time has passed, set to same time tomorrow\n if (target_time <= now) {\n tm_target.tm_mday += 1;\n target_time = mktime(&tm_target);\n }\n \n total = (int)difftime(target_time, now);\n } else {\n // Check if it contains unit identifiers\n BOOL hasUnits = FALSE;\n for (int i = 0; input_copy[i]; i++) {\n char c = tolower((unsigned char)input_copy[i]);\n if (c == 'h' || c == 'm' || c == 's') {\n hasUnits = TRUE;\n break;\n }\n }\n \n if (hasUnits) {\n // For input with units, merge all parts with unit markings\n char* parts[10] = {0}; // Store up to 10 parts\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 10) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n // Process each part\n for (int i = 0; i < part_count; i++) {\n char* part = parts[i];\n int part_len = strlen(part);\n BOOL has_unit = FALSE;\n \n // Check if this part has a unit\n for (int j = 0; j < part_len; j++) {\n char c = tolower((unsigned char)part[j]);\n if (c == 'h' || c == 'm' || c == 's') {\n has_unit = TRUE;\n break;\n }\n }\n \n if (has_unit) {\n // If it has a unit, process according to unit\n char unit = tolower((unsigned char)part[part_len-1]);\n part[part_len-1] = '\\0'; // Remove unit\n int value = atoi(part);\n \n switch (unit) {\n case 'h': total += value * 3600; break;\n case 'm': total += value * 60; break;\n case 's': total += value; break;\n }\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'h') {\n // If next item has h unit, current item is hours\n total += atoi(part) * 3600;\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'm') {\n // If next item has m unit, current item is hours\n total += atoi(part) * 3600;\n } else {\n // Default process as two-segment or three-segment format\n if (part_count == 2) {\n // Two-segment format: first segment is minutes, second segment is seconds\n if (i == 0) total += atoi(part) * 60;\n else total += atoi(part);\n } else if (part_count == 3) {\n // Three-segment format: hour:minute:second\n if (i == 0) total += atoi(part) * 3600;\n else if (i == 1) total += atoi(part) * 60;\n else total += atoi(part);\n } else {\n // Other cases treated as minutes\n total += atoi(part) * 60;\n }\n }\n }\n } else {\n // Processing without units\n char* parts[3] = {0}; // Store up to 3 parts (hour, minute, second)\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 3) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n if (part_count == 1) {\n // Single number, calculate as minutes\n total = atoi(parts[0]) * 60;\n } else if (part_count == 2) {\n // Two numbers: minute:second\n total = atoi(parts[0]) * 60 + atoi(parts[1]);\n } else if (part_count == 3) {\n // Three numbers: hour:minute:second\n total = atoi(parts[0]) * 3600 + atoi(parts[1]) * 60 + atoi(parts[2]);\n }\n }\n }\n\n *total_seconds = total;\n if (*total_seconds <= 0) return 0;\n\n if (*total_seconds > INT_MAX) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Validate if input string is legal\n * @param input Input string to validate\n * @return int Returns 1 if legal, 0 if illegal\n * \n * Valid character check rules:\n * - Only allows digits, spaces, and h/m/s/t unit identifiers at the end (case insensitive)\n * - Must contain at least one digit\n * - Maximum of two space separators\n */\nint isValidInput(const char* input) {\n if (input == NULL || *input == '\\0') {\n return 0;\n }\n\n int len = strlen(input);\n int digitCount = 0;\n\n for (int i = 0; i < len; i++) {\n if (isdigit(input[i])) {\n digitCount++;\n } else if (input[i] == ' ') {\n // Allow any number of spaces\n } else if (i == len - 1 && (input[i] == 'h' || input[i] == 'm' || input[i] == 's' || \n input[i] == 't' || input[i] == 'T' || \n input[i] == 'H' || input[i] == 'M' || input[i] == 'S')) {\n // Allow last character to be h/m/s/t or their uppercase forms\n } else {\n return 0;\n }\n }\n\n if (digitCount == 0) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Reset timer\n * \n * Reset timer state, including pause flag, elapsed time, etc.\n */\nvoid ResetTimer(void) {\n // Reset timing state\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time = 0;\n } else {\n countdown_elapsed_time = 0;\n \n // Ensure countdown total time is not zero, zero would cause timer not to display\n if (CLOCK_TOTAL_TIME <= 0) {\n // If total time is invalid, use default value\n CLOCK_TOTAL_TIME = 60; // Default set to 1 minute\n }\n }\n \n // Cancel pause state\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset message display flags\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Reinitialize high-precision timer\n InitializeHighPrecisionTimer();\n}\n\n/**\n * @brief Toggle timer pause state\n * \n * Toggle timer between pause and continue states\n */\nvoid TogglePauseTimer(void) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n // If resuming from pause state, reinitialize high-precision timer\n if (!CLOCK_IS_PAUSED) {\n InitializeHighPrecisionTimer();\n }\n}\n\n/**\n * @brief Write default startup time to configuration file\n * @param seconds Default startup time (seconds)\n * \n * Use the general path retrieval method in the configuration management module to write to INI format configuration file\n */\nvoid WriteConfigDefaultStartTime(int seconds) {\n char config_path[MAX_PATH];\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Write using INI format\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", seconds, config_path);\n}\n"], ["/Catime/src/font.c", "/**\n * @file font.c\n * @brief Font management module implementation file\n * \n * This file implements the font management functionality of the application, including font loading, preview,\n * application and configuration file management. Supports loading multiple predefined fonts from resources.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/font.h\"\n#include \"../resource/resource.h\"\n\n/// @name Global font variables\n/// @{\nchar FONT_FILE_NAME[100] = \"Hack Nerd Font.ttf\"; ///< Currently used font file name\nchar FONT_INTERNAL_NAME[100]; ///< Font internal name (without extension)\nchar PREVIEW_FONT_NAME[100] = \"\"; ///< Preview font file name\nchar PREVIEW_INTERNAL_NAME[100] = \"\"; ///< Preview font internal name\nBOOL IS_PREVIEWING = FALSE; ///< Whether font preview is active\n/// @}\n\n/**\n * @brief Font resource array\n * \n * Stores information for all built-in font resources in the application\n */\nFontResource fontResources[] = {\n {CLOCK_IDC_FONT_RECMONO, IDR_FONT_RECMONO, \"RecMonoCasual Nerd Font Mono Essence.ttf\"},\n {CLOCK_IDC_FONT_DEPARTURE, IDR_FONT_DEPARTURE, \"DepartureMono Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_TERMINESS, IDR_FONT_TERMINESS, \"Terminess Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_ARBUTUS, IDR_FONT_ARBUTUS, \"Arbutus Essence.ttf\"},\n {CLOCK_IDC_FONT_BERKSHIRE, IDR_FONT_BERKSHIRE, \"Berkshire Swash Essence.ttf\"},\n {CLOCK_IDC_FONT_CAVEAT, IDR_FONT_CAVEAT, \"Caveat Brush Essence.ttf\"},\n {CLOCK_IDC_FONT_CREEPSTER, IDR_FONT_CREEPSTER, \"Creepster Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTGOTHIC, IDR_FONT_DOTGOTHIC, \"DotGothic16 Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTO, IDR_FONT_DOTO, \"Doto ExtraBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FOLDIT, IDR_FONT_FOLDIT, \"Foldit SemiBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FREDERICKA, IDR_FONT_FREDERICKA, \"Fredericka the Great Essence.ttf\"},\n {CLOCK_IDC_FONT_FRIJOLE, IDR_FONT_FRIJOLE, \"Frijole Essence.ttf\"},\n {CLOCK_IDC_FONT_GWENDOLYN, IDR_FONT_GWENDOLYN, \"Gwendolyn Essence.ttf\"},\n {CLOCK_IDC_FONT_HANDJET, IDR_FONT_HANDJET, \"Handjet Essence.ttf\"},\n {CLOCK_IDC_FONT_INKNUT, IDR_FONT_INKNUT, \"Inknut Antiqua Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARD, IDR_FONT_JACQUARD, \"Jacquard 12 Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARDA, IDR_FONT_JACQUARDA, \"Jacquarda Bastarda 9 Essence.ttf\"},\n {CLOCK_IDC_FONT_KAVOON, IDR_FONT_KAVOON, \"Kavoon Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE, IDR_FONT_KUMAR_ONE_OUTLINE, \"Kumar One Outline Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE, IDR_FONT_KUMAR_ONE, \"Kumar One Essence.ttf\"},\n {CLOCK_IDC_FONT_LAKKI_REDDY, IDR_FONT_LAKKI_REDDY, \"Lakki Reddy Essence.ttf\"},\n {CLOCK_IDC_FONT_LICORICE, IDR_FONT_LICORICE, \"Licorice Essence.ttf\"},\n {CLOCK_IDC_FONT_MA_SHAN_ZHENG, IDR_FONT_MA_SHAN_ZHENG, \"Ma Shan Zheng Essence.ttf\"},\n {CLOCK_IDC_FONT_MOIRAI_ONE, IDR_FONT_MOIRAI_ONE, \"Moirai One Essence.ttf\"},\n {CLOCK_IDC_FONT_MYSTERY_QUEST, IDR_FONT_MYSTERY_QUEST, \"Mystery Quest Essence.ttf\"},\n {CLOCK_IDC_FONT_NOTO_NASTALIQ, IDR_FONT_NOTO_NASTALIQ, \"Noto Nastaliq Urdu Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PIEDRA, IDR_FONT_PIEDRA, \"Piedra Essence.ttf\"},\n {CLOCK_IDC_FONT_PINYON_SCRIPT, IDR_FONT_PINYON_SCRIPT, \"Pinyon Script Essence.ttf\"},\n {CLOCK_IDC_FONT_PIXELIFY, IDR_FONT_PIXELIFY, \"Pixelify Sans Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PRESS_START, IDR_FONT_PRESS_START, \"Press Start 2P Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BUBBLES, IDR_FONT_RUBIK_BUBBLES, \"Rubik Bubbles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BURNED, IDR_FONT_RUBIK_BURNED, \"Rubik Burned Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_GLITCH, IDR_FONT_RUBIK_GLITCH, \"Rubik Glitch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_MARKER_HATCH, IDR_FONT_RUBIK_MARKER_HATCH, \"Rubik Marker Hatch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_PUDDLES, IDR_FONT_RUBIK_PUDDLES, \"Rubik Puddles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_VINYL, IDR_FONT_RUBIK_VINYL, \"Rubik Vinyl Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_WET_PAINT, IDR_FONT_RUBIK_WET_PAINT, \"Rubik Wet Paint Essence.ttf\"},\n {CLOCK_IDC_FONT_RUGE_BOOGIE, IDR_FONT_RUGE_BOOGIE, \"Ruge Boogie Essence.ttf\"},\n {CLOCK_IDC_FONT_SEVILLANA, IDR_FONT_SEVILLANA, \"Sevillana Essence.ttf\"},\n {CLOCK_IDC_FONT_SILKSCREEN, IDR_FONT_SILKSCREEN, \"Silkscreen Essence.ttf\"},\n {CLOCK_IDC_FONT_STICK, IDR_FONT_STICK, \"Stick Essence.ttf\"},\n {CLOCK_IDC_FONT_UNDERDOG, IDR_FONT_UNDERDOG, \"Underdog Essence.ttf\"},\n {CLOCK_IDC_FONT_WALLPOET, IDR_FONT_WALLPOET, \"Wallpoet Essence.ttf\"},\n {CLOCK_IDC_FONT_YESTERYEAR, IDR_FONT_YESTERYEAR, \"Yesteryear Essence.ttf\"},\n {CLOCK_IDC_FONT_ZCOOL_KUAILE, IDR_FONT_ZCOOL_KUAILE, \"ZCOOL KuaiLe Essence.ttf\"},\n {CLOCK_IDC_FONT_PROFONT, IDR_FONT_PROFONT, \"ProFont IIx Nerd Font Essence.ttf\"},\n {CLOCK_IDC_FONT_DADDYTIME, IDR_FONT_DADDYTIME, \"DaddyTimeMono Nerd Font Propo Essence.ttf\"},\n};\n\n/// Number of font resources\nconst int FONT_RESOURCES_COUNT = sizeof(fontResources) / sizeof(FontResource);\n\n/// @name External variable declarations\n/// @{\nextern char CLOCK_TEXT_COLOR[]; ///< Current clock text color\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t maxLen); ///< Get configuration file path\nextern void ReadConfig(void); ///< Read configuration file\nextern int CALLBACK EnumFontFamExProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam); ///< Font enumeration callback function\n/// @}\n\nBOOL LoadFontFromResource(HINSTANCE hInstance, int resourceId) {\n // Find font resource\n HRSRC hResource = FindResource(hInstance, MAKEINTRESOURCE(resourceId), RT_FONT);\n if (hResource == NULL) {\n return FALSE;\n }\n\n // Load resource into memory\n HGLOBAL hMemory = LoadResource(hInstance, hResource);\n if (hMemory == NULL) {\n return FALSE;\n }\n\n // Lock resource\n void* fontData = LockResource(hMemory);\n if (fontData == NULL) {\n return FALSE;\n }\n\n // Get resource size and add font\n DWORD fontLength = SizeofResource(hInstance, hResource);\n DWORD nFonts = 0;\n HANDLE handle = AddFontMemResourceEx(fontData, fontLength, NULL, &nFonts);\n \n if (handle == NULL) {\n return FALSE;\n }\n \n return TRUE;\n}\n\nBOOL LoadFontByName(HINSTANCE hInstance, const char* fontName) {\n // Iterate through the font resource array to find a matching font\n for (int i = 0; i < sizeof(fontResources) / sizeof(FontResource); i++) {\n if (strcmp(fontResources[i].fontName, fontName) == 0) {\n return LoadFontFromResource(hInstance, fontResources[i].resourceId);\n }\n }\n return FALSE;\n}\n\nvoid WriteConfigFont(const char* font_file_name) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Open configuration file for reading\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n // Read the entire configuration file content\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n // Create new configuration file content\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n // Process line by line and replace font settings\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"FONT_FILE_NAME=\", 15) == 0) {\n strcat(new_config, \"FONT_FILE_NAME=\");\n strcat(new_config, font_file_name);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n // Write new configuration content\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n // Re-read configuration\n ReadConfig();\n}\n\nvoid ListAvailableFonts(void) {\n HDC hdc = GetDC(NULL);\n LOGFONT lf;\n memset(&lf, 0, sizeof(LOGFONT));\n lf.lfCharSet = DEFAULT_CHARSET;\n\n // Create temporary font and enumerate fonts\n HFONT hFont = CreateFont(12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n lf.lfCharSet, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, NULL);\n SelectObject(hdc, hFont);\n\n EnumFontFamiliesEx(hdc, &lf, (FONTENUMPROC)EnumFontFamExProc, 0, 0);\n\n // Clean up resources\n DeleteObject(hFont);\n ReleaseDC(NULL, hdc);\n}\n\nint CALLBACK EnumFontFamExProc(\n ENUMLOGFONTEX *lpelfe,\n NEWTEXTMETRICEX *lpntme,\n DWORD FontType,\n LPARAM lParam\n) {\n return 1;\n}\n\nBOOL PreviewFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Save current font name\n strncpy(PREVIEW_FONT_NAME, fontName, sizeof(PREVIEW_FONT_NAME) - 1);\n PREVIEW_FONT_NAME[sizeof(PREVIEW_FONT_NAME) - 1] = '\\0';\n \n // Get internal font name (remove .ttf extension)\n size_t name_len = strlen(PREVIEW_FONT_NAME);\n if (name_len > 4 && strcmp(PREVIEW_FONT_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(PREVIEW_INTERNAL_NAME))\n copy_len = sizeof(PREVIEW_INTERNAL_NAME) - 1;\n \n memcpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, copy_len);\n PREVIEW_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, sizeof(PREVIEW_INTERNAL_NAME) - 1);\n PREVIEW_INTERNAL_NAME[sizeof(PREVIEW_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Load preview font\n if (!LoadFontByName(hInstance, PREVIEW_FONT_NAME)) {\n return FALSE;\n }\n \n IS_PREVIEWING = TRUE;\n return TRUE;\n}\n\nvoid CancelFontPreview(void) {\n IS_PREVIEWING = FALSE;\n PREVIEW_FONT_NAME[0] = '\\0';\n PREVIEW_INTERNAL_NAME[0] = '\\0';\n}\n\nvoid ApplyFontPreview(void) {\n // Check if there is a valid preview font\n if (!IS_PREVIEWING || strlen(PREVIEW_FONT_NAME) == 0) return;\n \n // Update current font\n strncpy(FONT_FILE_NAME, PREVIEW_FONT_NAME, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n strncpy(FONT_INTERNAL_NAME, PREVIEW_INTERNAL_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n \n // Save to configuration file and cancel preview state\n WriteConfigFont(FONT_FILE_NAME);\n CancelFontPreview();\n}\n\nBOOL SwitchFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Load new font\n if (!LoadFontByName(hInstance, fontName)) {\n return FALSE;\n }\n \n // Update font name\n strncpy(FONT_FILE_NAME, fontName, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n // Update internal font name (remove .ttf extension)\n size_t name_len = strlen(FONT_FILE_NAME);\n if (name_len > 4 && strcmp(FONT_FILE_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Write to configuration file\n WriteConfigFont(FONT_FILE_NAME);\n return TRUE;\n}"], ["/Catime/src/tray_events.c", "/**\n * @file tray_events.c\n * @brief Implementation of system tray event handling module\n * \n * This module implements the event handling functionality for the application's system tray,\n * including response to various mouse events on the tray icon, menu display and control,\n * as well as tray operations related to the timer such as pause/resume and restart.\n * It provides core functionality for users to quickly control the application through the tray icon.\n */\n\n#include \n#include \n#include \"../include/tray_events.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/window_events.h\"\n#include \"../resource/resource.h\"\n\n// Declaration of function to read timeout action from configuration file\nextern void ReadTimeoutActionFromConfig(void);\n\n/**\n * @brief Handle system tray messages\n * @param hwnd Window handle\n * @param uID Tray icon ID\n * @param uMouseMsg Mouse message type\n * \n * Process mouse events for the system tray, displaying different context menus based on the event type:\n * - Left click: Display main function context menu, including timer control functions\n * - Right click: Display color selection menu for quickly changing display color\n * \n * All menu item command processing is implemented in the corresponding menu display module.\n */\nvoid HandleTrayIconMessage(HWND hwnd, UINT uID, UINT uMouseMsg) {\n // Set default cursor to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n if (uMouseMsg == WM_RBUTTONUP) {\n ShowColorMenu(hwnd);\n }\n else if (uMouseMsg == WM_LBUTTONUP) {\n ShowContextMenu(hwnd);\n }\n}\n\n/**\n * @brief Pause or resume timer\n * @param hwnd Window handle\n * \n * Toggle timer pause/resume state based on current status:\n * 1. Check if there is an active timer (countdown or count-up)\n * 2. If timer is active, toggle pause/resume state\n * 3. When paused, record current time point and stop timer\n * 4. When resumed, restart timer\n * 5. Refresh window to reflect new state\n * \n * Note: Can only operate when displaying timer (not current time) and timer is active\n */\nvoid PauseResumeTimer(HWND hwnd) {\n // Check if there is an active timer\n if (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || CLOCK_TOTAL_TIME > 0)) {\n \n // Toggle pause/resume state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n if (CLOCK_IS_PAUSED) {\n // If paused, record current time point\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n // Stop timer\n KillTimer(hwnd, 1);\n \n // Pause playing notification audio (new addition)\n extern BOOL PauseNotificationSound(void);\n PauseNotificationSound();\n } else {\n // If resumed, restart timer\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Resume notification audio (new addition)\n extern BOOL ResumeNotificationSound(void);\n ResumeNotificationSound();\n }\n \n // Update window to reflect new state\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart timer\n * @param hwnd Window handle\n * \n * Reset timer to initial state and continue running, keeping current timer type unchanged:\n * 1. Read current timeout action settings\n * 2. Reset timer progress based on current mode (countdown/count-up)\n * 3. Reset all related timer state variables\n * 4. Cancel pause state, ensure timer is running\n * 5. Refresh window and ensure window is on top after reset\n * \n * This operation does not change the timer mode or total duration, it only resets progress to initial state.\n */\nvoid RestartTimer(HWND hwnd) {\n // Stop any notification audio that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Determine operation based on current mode\n if (!CLOCK_COUNT_UP) {\n // Countdown mode\n if (CLOCK_TOTAL_TIME > 0) {\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n } else {\n // Count-up mode\n countup_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Update window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure window is on top and visible\n HandleWindowReset(hwnd);\n}\n\n/**\n * @brief Set startup mode\n * @param hwnd Window handle\n * @param mode Startup mode (\"COUNTDOWN\"/\"COUNT_UP\"/\"SHOW_TIME\"/\"NO_DISPLAY\")\n * \n * Set the application's default startup mode and save it to the configuration file:\n * 1. Save the selected mode to the configuration file\n * 2. Update menu item checked state to reflect current setting\n * 3. Refresh window display\n * \n * The startup mode determines the default behavior of the application at startup, such as whether to display current time or start timing.\n * The setting will take effect the next time the program starts.\n */\nvoid SetStartupMode(HWND hwnd, const char* mode) {\n // Save startup mode to configuration file\n WriteConfigStartupMode(mode);\n \n // Update menu item checked state\n HMENU hMenu = GetMenu(hwnd);\n if (hMenu) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Open user guide webpage\n * \n * Use ShellExecute to open Catime's user guide webpage,\n * providing detailed software instructions and help documentation for users.\n * URL: https://vladelaina.github.io/Catime/guide\n */\nvoid OpenUserGuide(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/guide\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open support page\n * \n * Use ShellExecute to open Catime's support page,\n * providing channels for users to support the developer.\n * URL: https://vladelaina.github.io/Catime/support\n */\nvoid OpenSupportPage(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open feedback page\n * \n * Open different feedback channels based on current language setting:\n * - Simplified Chinese: Open bilibili private message page\n * - Other languages: Open GitHub Issues page\n */\nvoid OpenFeedbackPage(void) {\n extern AppLanguage CURRENT_LANGUAGE; // Declare external variable\n \n // Choose different feedback links based on language\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP) {\n // Simplified Chinese users open bilibili private message\n ShellExecuteW(NULL, L\"open\", URL_FEEDBACK, NULL, NULL, SW_SHOWNORMAL);\n } else {\n // Users of other languages open GitHub Issues\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime/issues\", NULL, NULL, SW_SHOWNORMAL);\n }\n}"], ["/Catime/src/color.c", "/**\n * @file color.c\n * @brief Color processing functionality implementation\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/color.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n\nPredefinedColor* COLOR_OPTIONS = NULL;\nsize_t COLOR_OPTIONS_COUNT = 0;\nchar PREVIEW_COLOR[10] = \"\";\nBOOL IS_COLOR_PREVIEWING = FALSE;\nchar CLOCK_TEXT_COLOR[10] = \"#FFFFFF\";\n\nvoid GetConfigPath(char* path, size_t size);\nvoid CreateDefaultConfig(const char* config_path);\nvoid ReadConfig(void);\nvoid WriteConfig(const char* config_path);\nvoid replaceBlackColor(const char* color, char* output, size_t output_size);\n\nstatic const CSSColor CSS_COLORS[] = {\n {\"white\", \"#FFFFFF\"},\n {\"black\", \"#000000\"},\n {\"red\", \"#FF0000\"},\n {\"lime\", \"#00FF00\"},\n {\"blue\", \"#0000FF\"},\n {\"yellow\", \"#FFFF00\"},\n {\"cyan\", \"#00FFFF\"},\n {\"magenta\", \"#FF00FF\"},\n {\"silver\", \"#C0C0C0\"},\n {\"gray\", \"#808080\"},\n {\"maroon\", \"#800000\"},\n {\"olive\", \"#808000\"},\n {\"green\", \"#008000\"},\n {\"purple\", \"#800080\"},\n {\"teal\", \"#008080\"},\n {\"navy\", \"#000080\"},\n {\"orange\", \"#FFA500\"},\n {\"pink\", \"#FFC0CB\"},\n {\"brown\", \"#A52A2A\"},\n {\"violet\", \"#EE82EE\"},\n {\"indigo\", \"#4B0082\"},\n {\"gold\", \"#FFD700\"},\n {\"coral\", \"#FF7F50\"},\n {\"salmon\", \"#FA8072\"},\n {\"khaki\", \"#F0E68C\"},\n {\"plum\", \"#DDA0DD\"},\n {\"azure\", \"#F0FFFF\"},\n {\"ivory\", \"#FFFFF0\"},\n {\"wheat\", \"#F5DEB3\"},\n {\"snow\", \"#FFFAFA\"}\n};\n\n#define CSS_COLORS_COUNT (sizeof(CSS_COLORS) / sizeof(CSS_COLORS[0]))\n\nstatic const char* DEFAULT_COLOR_OPTIONS[] = {\n \"#FFFFFF\",\n \"#F9DB91\",\n \"#F4CAE0\",\n \"#FFB6C1\",\n \"#A8E7DF\",\n \"#A3CFB3\",\n \"#92CBFC\",\n \"#BDA5E7\",\n \"#9370DB\",\n \"#8C92CF\",\n \"#72A9A5\",\n \"#EB99A7\",\n \"#EB96BD\",\n \"#FFAE8B\",\n \"#FF7F50\",\n \"#CA6174\"\n};\n\n#define DEFAULT_COLOR_OPTIONS_COUNT (sizeof(DEFAULT_COLOR_OPTIONS) / sizeof(DEFAULT_COLOR_OPTIONS[0]))\n\nWNDPROC g_OldEditProc;\n\n#include \n\nCOLORREF ShowColorDialog(HWND hwnd) {\n CHOOSECOLOR cc = {0};\n static COLORREF acrCustClr[16] = {0};\n static DWORD rgbCurrent;\n\n int r, g, b;\n if (CLOCK_TEXT_COLOR[0] == '#') {\n sscanf(CLOCK_TEXT_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n } else {\n sscanf(CLOCK_TEXT_COLOR, \"%d,%d,%d\", &r, &g, &b);\n }\n rgbCurrent = RGB(r, g, b);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT && i < 16; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n if (hexColor[0] == '#') {\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n acrCustClr[i] = RGB(r, g, b);\n }\n }\n\n cc.lStructSize = sizeof(CHOOSECOLOR);\n cc.hwndOwner = hwnd;\n cc.lpCustColors = acrCustClr;\n cc.rgbResult = rgbCurrent;\n cc.Flags = CC_FULLOPEN | CC_RGBINIT | CC_ENABLEHOOK;\n cc.lpfnHook = ColorDialogHookProc;\n\n if (ChooseColor(&cc)) {\n COLORREF finalColor;\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n int r, g, b;\n sscanf(PREVIEW_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n finalColor = RGB(r, g, b);\n } else {\n finalColor = cc.rgbResult;\n }\n\n char tempColor[10];\n snprintf(tempColor, sizeof(tempColor), \"#%02X%02X%02X\",\n GetRValue(finalColor),\n GetGValue(finalColor),\n GetBValue(finalColor));\n\n char finalColorStr[10];\n replaceBlackColor(tempColor, finalColorStr, sizeof(finalColorStr));\n\n strncpy(CLOCK_TEXT_COLOR, finalColorStr, sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n\n IS_COLOR_PREVIEWING = FALSE;\n\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return finalColor;\n }\n\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return (COLORREF)-1;\n}\n\nUINT_PTR CALLBACK ColorDialogHookProc(HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HWND hwndParent;\n static CHOOSECOLOR* pcc;\n static BOOL isColorLocked = FALSE;\n static DWORD rgbCurrent;\n static COLORREF lastCustomColors[16] = {0};\n\n switch (msg) {\n case WM_INITDIALOG:\n pcc = (CHOOSECOLOR*)lParam;\n hwndParent = pcc->hwndOwner;\n rgbCurrent = pcc->rgbResult;\n isColorLocked = FALSE;\n \n for (int i = 0; i < 16; i++) {\n lastCustomColors[i] = pcc->lpCustColors[i];\n }\n return TRUE;\n\n case WM_LBUTTONDOWN:\n case WM_RBUTTONDOWN:\n isColorLocked = !isColorLocked;\n \n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n \n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n \n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n \n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n\n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_MOUSEMOVE:\n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n\n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n\n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n\n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n \n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n \n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_COMMAND:\n if (HIWORD(wParam) == BN_CLICKED) {\n switch (LOWORD(wParam)) {\n case IDOK: {\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n } else {\n snprintf(PREVIEW_COLOR, sizeof(PREVIEW_COLOR), \"#%02X%02X%02X\",\n GetRValue(pcc->rgbResult),\n GetGValue(pcc->rgbResult),\n GetBValue(pcc->rgbResult));\n }\n break;\n }\n \n case IDCANCEL:\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n break;\n }\n }\n break;\n\n case WM_CTLCOLORBTN:\n case WM_CTLCOLOREDIT:\n case WM_CTLCOLORSTATIC:\n if (pcc) {\n BOOL colorsChanged = FALSE;\n for (int i = 0; i < 16; i++) {\n if (lastCustomColors[i] != pcc->lpCustColors[i]) {\n colorsChanged = TRUE;\n lastCustomColors[i] = pcc->lpCustColors[i];\n \n char colorStr[20];\n snprintf(colorStr, sizeof(colorStr), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n \n }\n }\n \n if (colorsChanged) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n ClearColorOptions();\n \n for (int i = 0; i < 16; i++) {\n if (pcc->lpCustColors[i] != 0) {\n char hexColor[10];\n snprintf(hexColor, sizeof(hexColor), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n AddColorOption(hexColor);\n }\n }\n \n WriteConfig(config_path);\n }\n }\n break;\n }\n return 0;\n}\n\nvoid InitializeDefaultLanguage(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n ClearColorOptions();\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n CreateDefaultConfig(config_path);\n file = fopen(config_path, \"r\");\n }\n\n if (file) {\n char line[1024];\n BOOL found_colors = FALSE;\n\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"COLOR_OPTIONS=\", 13) == 0) {\n ClearColorOptions();\n\n char* colors = line + 13;\n while (*colors == '=' || *colors == ' ') {\n colors++;\n }\n\n char* newline = strchr(colors, '\\n');\n if (newline) *newline = '\\0';\n\n char* token = strtok(colors, \",\");\n while (token) {\n while (*token == ' ') token++;\n char* end = token + strlen(token) - 1;\n while (end > token && *end == ' ') {\n *end = '\\0';\n end--;\n }\n\n if (*token) {\n if (token[0] != '#') {\n char colorWithHash[10];\n snprintf(colorWithHash, sizeof(colorWithHash), \"#%s\", token);\n AddColorOption(colorWithHash);\n } else {\n AddColorOption(token);\n }\n }\n token = strtok(NULL, \",\");\n }\n found_colors = TRUE;\n break;\n }\n }\n fclose(file);\n\n if (!found_colors || COLOR_OPTIONS_COUNT == 0) {\n for (size_t i = 0; i < DEFAULT_COLOR_OPTIONS_COUNT; i++) {\n AddColorOption(DEFAULT_COLOR_OPTIONS[i]);\n }\n }\n }\n}\n\n/**\n * @brief Add color option\n */\nvoid AddColorOption(const char* hexColor) {\n if (!hexColor || !*hexColor) {\n return;\n }\n\n char normalizedColor[10];\n const char* hex = (hexColor[0] == '#') ? hexColor + 1 : hexColor;\n\n size_t len = strlen(hex);\n if (len != 6) {\n return;\n }\n\n for (int i = 0; i < 6; i++) {\n if (!isxdigit((unsigned char)hex[i])) {\n return;\n }\n }\n\n unsigned int color;\n if (sscanf(hex, \"%x\", &color) != 1) {\n return;\n }\n\n snprintf(normalizedColor, sizeof(normalizedColor), \"#%06X\", color);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (strcasecmp(normalizedColor, COLOR_OPTIONS[i].hexColor) == 0) {\n return;\n }\n }\n\n PredefinedColor* newArray = realloc(COLOR_OPTIONS,\n (COLOR_OPTIONS_COUNT + 1) * sizeof(PredefinedColor));\n if (newArray) {\n COLOR_OPTIONS = newArray;\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = _strdup(normalizedColor);\n COLOR_OPTIONS_COUNT++;\n }\n}\n\n/**\n * @brief Clear all color options\n */\nvoid ClearColorOptions(void) {\n if (COLOR_OPTIONS) {\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n free((void*)COLOR_OPTIONS[i].hexColor);\n }\n free(COLOR_OPTIONS);\n COLOR_OPTIONS = NULL;\n COLOR_OPTIONS_COUNT = 0;\n }\n}\n\n/**\n * @brief Write color to configuration file\n */\nvoid WriteConfigColor(const char* color_input) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"CLOCK_TEXT_COLOR=\", 17) == 0) {\n strcat(new_config, \"CLOCK_TEXT_COLOR=\");\n strcat(new_config, color_input);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n ReadConfig();\n}\n\n/**\n * @brief Normalize color format\n */\nvoid normalizeColor(const char* input, char* output, size_t output_size) {\n while (isspace(*input)) input++;\n\n char color[32];\n strncpy(color, input, sizeof(color)-1);\n color[sizeof(color)-1] = '\\0';\n for (char* p = color; *p; p++) {\n *p = tolower(*p);\n }\n\n for (size_t i = 0; i < CSS_COLORS_COUNT; i++) {\n if (strcmp(color, CSS_COLORS[i].name) == 0) {\n strncpy(output, CSS_COLORS[i].hex, output_size);\n return;\n }\n }\n\n char cleaned[32] = {0};\n int j = 0;\n for (int i = 0; color[i]; i++) {\n if (!isspace(color[i]) && color[i] != ',' && color[i] != '(' && color[i] != ')') {\n cleaned[j++] = color[i];\n }\n }\n cleaned[j] = '\\0';\n\n if (cleaned[0] == '#') {\n memmove(cleaned, cleaned + 1, strlen(cleaned));\n }\n\n if (strlen(cleaned) == 3) {\n snprintf(output, output_size, \"#%c%c%c%c%c%c\",\n cleaned[0], cleaned[0], cleaned[1], cleaned[1], cleaned[2], cleaned[2]);\n return;\n }\n\n if (strlen(cleaned) == 6 && strspn(cleaned, \"0123456789abcdefABCDEF\") == 6) {\n snprintf(output, output_size, \"#%s\", cleaned);\n return;\n }\n\n int r = -1, g = -1, b = -1;\n char* rgb_str = color;\n\n if (strncmp(rgb_str, \"rgb\", 3) == 0) {\n rgb_str += 3;\n while (*rgb_str && (*rgb_str == '(' || isspace(*rgb_str))) rgb_str++;\n }\n\n if (sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d %d %d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d|%d|%d\", &r, &g, &b) == 3) {\n\n if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) {\n snprintf(output, output_size, \"#%02X%02X%02X\", r, g, b);\n return;\n }\n }\n\n strncpy(output, input, output_size);\n}\n\n/**\n * @brief Check if color is valid\n */\nBOOL isValidColor(const char* input) {\n if (!input || !*input) return FALSE;\n\n char normalized[32];\n normalizeColor(input, normalized, sizeof(normalized));\n\n if (normalized[0] != '#' || strlen(normalized) != 7) {\n return FALSE;\n }\n\n for (int i = 1; i < 7; i++) {\n if (!isxdigit((unsigned char)normalized[i])) {\n return FALSE;\n }\n }\n\n int r, g, b;\n if (sscanf(normalized + 1, \"%02x%02x%02x\", &r, &g, &b) == 3) {\n return (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255);\n }\n\n return FALSE;\n}\n\n/**\n * @brief Color edit box subclass procedure\n */\nLRESULT CALLBACK ColorEditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_KEYDOWN:\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n case WM_COMMAND:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n return 0;\n }\n }\n break;\n\n case WM_CHAR:\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n }\n\n return result;\n\n case WM_PASTE:\n case WM_CUT: {\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n }\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n\n return result;\n }\n }\n\n return CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Color settings dialog procedure\n */\nINT_PTR CALLBACK ColorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit) {\n g_OldEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC,\n (LONG_PTR)ColorEditSubclassProc);\n\n if (CLOCK_TEXT_COLOR[0] != '\\0') {\n SetWindowTextA(hwndEdit, CLOCK_TEXT_COLOR);\n }\n }\n return TRUE;\n }\n\n case WM_COMMAND: {\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n char color[32];\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, color, sizeof(color));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; color[i]; i++) {\n if (!isspace((unsigned char)color[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (color[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n\n if (isValidColor(color)) {\n char normalized_color[10];\n normalizeColor(color, normalized_color, sizeof(normalized_color));\n strncpy(CLOCK_TEXT_COLOR, normalized_color, sizeof(CLOCK_TEXT_COLOR)-1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR)-1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n }\n return FALSE;\n}\n\n/**\n * @brief Replace pure black color with near-black\n */\nvoid replaceBlackColor(const char* color, char* output, size_t output_size) {\n if (color && (strcasecmp(color, \"#000000\") == 0)) {\n strncpy(output, \"#000001\", output_size);\n output[output_size - 1] = '\\0';\n } else {\n strncpy(output, color, output_size);\n output[output_size - 1] = '\\0';\n }\n}"], ["/Catime/src/hotkey.c", "/**\n * @file hotkey.c\n * @brief Hotkey management implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#if defined _M_IX86\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_IA64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_X64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#else\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#endif\n#include \"../include/hotkey.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../resource/resource.h\"\n\n#ifndef HOTKEYF_SHIFT\n#define HOTKEYF_SHIFT 0x01\n#define HOTKEYF_CONTROL 0x02\n#define HOTKEYF_ALT 0x04\n#endif\n\nstatic WORD g_dlgShowTimeHotkey = 0;\nstatic WORD g_dlgCountUpHotkey = 0;\nstatic WORD g_dlgCountdownHotkey = 0;\nstatic WORD g_dlgCustomCountdownHotkey = 0;\nstatic WORD g_dlgQuickCountdown1Hotkey = 0;\nstatic WORD g_dlgQuickCountdown2Hotkey = 0;\nstatic WORD g_dlgQuickCountdown3Hotkey = 0;\nstatic WORD g_dlgPomodoroHotkey = 0;\nstatic WORD g_dlgToggleVisibilityHotkey = 0;\nstatic WORD g_dlgEditModeHotkey = 0;\nstatic WORD g_dlgPauseResumeHotkey = 0;\nstatic WORD g_dlgRestartTimerHotkey = 0;\n\nstatic WNDPROC g_OldHotkeyDlgProc = NULL;\n\n/**\n * @brief Dialog subclassing procedure\n */\nLRESULT CALLBACK HotkeyDialogSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n if (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN || msg == WM_KEYUP || msg == WM_SYSKEYUP) {\n BYTE vk = (BYTE)wParam;\n if (!(vk == VK_SHIFT || vk == VK_CONTROL || vk == VK_MENU || vk == VK_LWIN || vk == VK_RWIN)) {\n BYTE currentModifiers = 0;\n if (GetKeyState(VK_SHIFT) & 0x8000) currentModifiers |= HOTKEYF_SHIFT;\n if (GetKeyState(VK_CONTROL) & 0x8000) currentModifiers |= HOTKEYF_CONTROL;\n if (msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP || (GetKeyState(VK_MENU) & 0x8000)) {\n currentModifiers |= HOTKEYF_ALT;\n }\n\n WORD currentEventKeyCombination = MAKEWORD(vk, currentModifiers);\n\n const WORD originalHotkeys[] = {\n g_dlgShowTimeHotkey, g_dlgCountUpHotkey, g_dlgCountdownHotkey,\n g_dlgQuickCountdown1Hotkey, g_dlgQuickCountdown2Hotkey, g_dlgQuickCountdown3Hotkey,\n g_dlgPomodoroHotkey, g_dlgToggleVisibilityHotkey, g_dlgEditModeHotkey,\n g_dlgPauseResumeHotkey, g_dlgRestartTimerHotkey\n };\n BOOL isAnOriginalHotkeyEvent = FALSE;\n for (size_t i = 0; i < sizeof(originalHotkeys) / sizeof(originalHotkeys[0]); ++i) {\n if (originalHotkeys[i] != 0 && originalHotkeys[i] == currentEventKeyCombination) {\n isAnOriginalHotkeyEvent = TRUE;\n break;\n }\n }\n\n if (isAnOriginalHotkeyEvent) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n }\n\n switch (msg) {\n case WM_SYSKEYDOWN:\n case WM_SYSKEYUP:\n {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (isHotkeyEditControl) {\n break;\n }\n }\n return 0;\n }\n\n case WM_KEYDOWN:\n case WM_KEYUP:\n {\n BYTE vk_code = (BYTE)wParam;\n if (vk_code == VK_SHIFT || vk_code == VK_CONTROL || vk_code == VK_LWIN || vk_code == VK_RWIN) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n break;\n\n case WM_SYSCOMMAND:\n if ((wParam & 0xFFF0) == SC_KEYMENU) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(g_OldHotkeyDlgProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Show hotkey settings dialog\n */\nvoid ShowHotkeySettingsDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_HOTKEY_DIALOG),\n hwndParent,\n HotkeySettingsDlgProc);\n}\n\n/**\n * @brief Check if a hotkey is a single key\n */\nBOOL IsSingleKey(WORD hotkey) {\n BYTE modifiers = HIBYTE(hotkey);\n\n return modifiers == 0;\n}\n\n/**\n * @brief Check if a hotkey is a standalone letter, number, or symbol\n */\nBOOL IsRestrictedSingleKey(WORD hotkey) {\n if (hotkey == 0) {\n return FALSE;\n }\n\n BYTE vk = LOBYTE(hotkey);\n BYTE modifiers = HIBYTE(hotkey);\n\n if (modifiers != 0) {\n return FALSE;\n }\n\n if (vk >= 'A' && vk <= 'Z') {\n return TRUE;\n }\n\n if (vk >= '0' && vk <= '9') {\n return TRUE;\n }\n\n if (vk >= VK_NUMPAD0 && vk <= VK_NUMPAD9) {\n return TRUE;\n }\n\n switch (vk) {\n case VK_OEM_1:\n case VK_OEM_PLUS:\n case VK_OEM_COMMA:\n case VK_OEM_MINUS:\n case VK_OEM_PERIOD:\n case VK_OEM_2:\n case VK_OEM_3:\n case VK_OEM_4:\n case VK_OEM_5:\n case VK_OEM_6:\n case VK_OEM_7:\n case VK_SPACE:\n case VK_RETURN:\n case VK_ESCAPE:\n case VK_TAB:\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey settings dialog message processing procedure\n */\nINT_PTR CALLBACK HotkeySettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL1,\n GetLocalizedString(L\"显示当前时间:\", L\"Show Current Time:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL2,\n GetLocalizedString(L\"正计时:\", L\"Count Up:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL12,\n GetLocalizedString(L\"倒计时:\", L\"Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL3,\n GetLocalizedString(L\"默认倒计时:\", L\"Default Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL9,\n GetLocalizedString(L\"快捷倒计时1:\", L\"Quick Countdown 1:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL10,\n GetLocalizedString(L\"快捷倒计时2:\", L\"Quick Countdown 2:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL11,\n GetLocalizedString(L\"快捷倒计时3:\", L\"Quick Countdown 3:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL4,\n GetLocalizedString(L\"开始番茄钟:\", L\"Start Pomodoro:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL5,\n GetLocalizedString(L\"隐藏/显示窗口:\", L\"Hide/Show Window:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL6,\n GetLocalizedString(L\"进入编辑模式:\", L\"Enter Edit Mode:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL7,\n GetLocalizedString(L\"暂停/继续计时:\", L\"Pause/Resume Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL8,\n GetLocalizedString(L\"重新开始计时:\", L\"Restart Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_NOTE,\n GetLocalizedString(L\"* 热键将全局生效\", L\"* Hotkeys will work globally\"));\n\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"确定\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"取消\", L\"Cancel\"));\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n ReadConfigHotkeys(&g_dlgShowTimeHotkey, &g_dlgCountUpHotkey, &g_dlgCountdownHotkey,\n &g_dlgQuickCountdown1Hotkey, &g_dlgQuickCountdown2Hotkey, &g_dlgQuickCountdown3Hotkey,\n &g_dlgPomodoroHotkey, &g_dlgToggleVisibilityHotkey, &g_dlgEditModeHotkey,\n &g_dlgPauseResumeHotkey, &g_dlgRestartTimerHotkey);\n\n ReadCustomCountdownHotkey(&g_dlgCustomCountdownHotkey);\n\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_SETHOTKEY, g_dlgShowTimeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_SETHOTKEY, g_dlgCountUpHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_SETHOTKEY, g_dlgCustomCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_SETHOTKEY, g_dlgCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_SETHOTKEY, g_dlgQuickCountdown1Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_SETHOTKEY, g_dlgQuickCountdown2Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_SETHOTKEY, g_dlgQuickCountdown3Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_SETHOTKEY, g_dlgPomodoroHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_SETHOTKEY, g_dlgToggleVisibilityHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_SETHOTKEY, g_dlgEditModeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_SETHOTKEY, g_dlgPauseResumeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_SETHOTKEY, g_dlgRestartTimerHotkey, 0);\n\n UnregisterGlobalHotkeys(GetParent(hwndDlg));\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n SetWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i, 0);\n }\n }\n\n g_OldHotkeyDlgProc = (WNDPROC)SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)HotkeyDialogSubclassProc);\n\n SetFocus(GetDlgItem(hwndDlg, IDCANCEL));\n\n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n \n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n \n case WM_LBUTTONDOWN: {\n POINT pt = {LOWORD(lParam), HIWORD(lParam)};\n HWND hwndHit = ChildWindowFromPoint(hwndDlg, pt);\n\n if (hwndHit != NULL && hwndHit != hwndDlg) {\n int ctrlId = GetDlgCtrlID(hwndHit);\n\n BOOL isHotkeyEdit = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) {\n isHotkeyEdit = TRUE;\n break;\n }\n }\n\n if (!isHotkeyEdit) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n }\n }\n else if (hwndHit == hwndDlg) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND: {\n WORD ctrlId = LOWORD(wParam);\n WORD notifyCode = HIWORD(wParam);\n\n if (notifyCode == EN_CHANGE &&\n (ctrlId == IDC_HOTKEY_EDIT1 || ctrlId == IDC_HOTKEY_EDIT2 ||\n ctrlId == IDC_HOTKEY_EDIT3 || ctrlId == IDC_HOTKEY_EDIT4 ||\n ctrlId == IDC_HOTKEY_EDIT5 || ctrlId == IDC_HOTKEY_EDIT6 ||\n ctrlId == IDC_HOTKEY_EDIT7 || ctrlId == IDC_HOTKEY_EDIT8 ||\n ctrlId == IDC_HOTKEY_EDIT9 || ctrlId == IDC_HOTKEY_EDIT10 ||\n ctrlId == IDC_HOTKEY_EDIT11 || ctrlId == IDC_HOTKEY_EDIT12)) {\n\n WORD newHotkey = (WORD)SendDlgItemMessage(hwndDlg, ctrlId, HKM_GETHOTKEY, 0, 0);\n\n BYTE vk = LOBYTE(newHotkey);\n BYTE modifiers = HIBYTE(newHotkey);\n\n if (vk == 0xE5 && modifiers == HOTKEYF_SHIFT) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0 && IsRestrictedSingleKey(newHotkey)) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0) {\n static const int hotkeyCtrlIds[] = {\n IDC_HOTKEY_EDIT1, IDC_HOTKEY_EDIT2, IDC_HOTKEY_EDIT3,\n IDC_HOTKEY_EDIT9, IDC_HOTKEY_EDIT10, IDC_HOTKEY_EDIT11,\n IDC_HOTKEY_EDIT4, IDC_HOTKEY_EDIT5, IDC_HOTKEY_EDIT6,\n IDC_HOTKEY_EDIT7, IDC_HOTKEY_EDIT8, IDC_HOTKEY_EDIT12\n };\n\n for (int i = 0; i < sizeof(hotkeyCtrlIds) / sizeof(hotkeyCtrlIds[0]); i++) {\n if (hotkeyCtrlIds[i] == ctrlId) {\n continue;\n }\n\n WORD otherHotkey = (WORD)SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_GETHOTKEY, 0, 0);\n\n if (otherHotkey != 0 && otherHotkey == newHotkey) {\n SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_SETHOTKEY, 0, 0);\n }\n }\n }\n\n return TRUE;\n }\n \n switch (LOWORD(wParam)) {\n case IDOK: {\n WORD showTimeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_GETHOTKEY, 0, 0);\n WORD countUpHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_GETHOTKEY, 0, 0);\n WORD customCountdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_GETHOTKEY, 0, 0);\n WORD countdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown1Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown2Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown3Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_GETHOTKEY, 0, 0);\n WORD pomodoroHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_GETHOTKEY, 0, 0);\n WORD toggleVisibilityHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_GETHOTKEY, 0, 0);\n WORD editModeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_GETHOTKEY, 0, 0);\n WORD pauseResumeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_GETHOTKEY, 0, 0);\n WORD restartTimerHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_GETHOTKEY, 0, 0);\n\n WORD* hotkeys[] = {\n &showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey, &customCountdownHotkey\n };\n\n for (int i = 0; i < sizeof(hotkeys) / sizeof(hotkeys[0]); i++) {\n if (LOBYTE(*hotkeys[i]) == 0xE5 && HIBYTE(*hotkeys[i]) == HOTKEYF_SHIFT) {\n *hotkeys[i] = 0;\n continue;\n }\n\n if (*hotkeys[i] != 0 && IsRestrictedSingleKey(*hotkeys[i])) {\n *hotkeys[i] = 0;\n }\n }\n\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n g_dlgCustomCountdownHotkey = customCountdownHotkey;\n char customCountdownStr[64] = {0};\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr);\n\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n\n case IDCANCEL:\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n \n case WM_DESTROY:\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n if (g_OldHotkeyDlgProc) {\n SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)g_OldHotkeyDlgProc);\n g_OldHotkeyDlgProc = NULL;\n }\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n RemoveWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i);\n }\n }\n break;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey control subclass procedure\n */\nLRESULT CALLBACK HotkeyControlSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam,\n LPARAM lParam, UINT_PTR uIdSubclass,\n DWORD_PTR dwRefData) {\n switch (uMsg) {\n case WM_GETDLGCODE:\n return DLGC_WANTALLKEYS | DLGC_WANTCHARS;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(hwndDlg, IDOK));\n return 0;\n }\n }\n break;\n }\n\n return DefSubclassProc(hwnd, uMsg, wParam, lParam);\n}"], ["/Catime/src/drawing.c", "/**\n * @file drawing.c\n * @brief Window drawing functionality implementation\n * \n * This file implements the drawing-related functionality of the application window,\n * including text rendering, color settings, and window content drawing.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/drawing.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n\n// Variable imported from window_procedure.c\nextern int elapsed_time;\n\n// Using window drawing related constants defined in resource.h\n\nvoid HandleWindowPaint(HWND hwnd, PAINTSTRUCT *ps) {\n static char time_text[50];\n HDC hdc = ps->hdc;\n RECT rect;\n GetClientRect(hwnd, &rect);\n\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, rect.right, rect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n\n SetGraphicsMode(memDC, GM_ADVANCED);\n SetBkMode(memDC, TRANSPARENT);\n SetStretchBltMode(memDC, HALFTONE);\n SetBrushOrgEx(memDC, 0, 0, NULL);\n\n // Generate display text based on different modes\n if (CLOCK_SHOW_CURRENT_TIME) {\n time_t now = time(NULL);\n struct tm *tm_info = localtime(&now);\n int hour = tm_info->tm_hour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, tm_info->tm_min, tm_info->tm_sec);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, tm_info->tm_min);\n }\n } else if (CLOCK_COUNT_UP) {\n // Count-up mode\n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n } else {\n // Countdown mode\n int remaining_time = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining_time <= 0) {\n // Timeout reached, decide whether to display content based on conditions\n if (CLOCK_TOTAL_TIME == 0 && countdown_elapsed_time == 0) {\n // This is the case after sleep operation, don't display anything\n time_text[0] = '\\0';\n } else if (strcmp(CLOCK_TIMEOUT_TEXT, \"0\") == 0) {\n time_text[0] = '\\0';\n } else if (strlen(CLOCK_TIMEOUT_TEXT) > 0) {\n strncpy(time_text, CLOCK_TIMEOUT_TEXT, sizeof(time_text) - 1);\n time_text[sizeof(time_text) - 1] = '\\0';\n } else {\n time_text[0] = '\\0';\n }\n } else {\n int hours = remaining_time / 3600;\n int minutes = (remaining_time % 3600) / 60;\n int seconds = remaining_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n }\n }\n\n const char* fontToUse = IS_PREVIEWING ? PREVIEW_FONT_NAME : FONT_FILE_NAME;\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE * CLOCK_FONT_SCALE_FACTOR,\n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_TT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, \n VARIABLE_PITCH | FF_SWISS,\n IS_PREVIEWING ? PREVIEW_INTERNAL_NAME : FONT_INTERNAL_NAME\n );\n HFONT oldFont = (HFONT)SelectObject(memDC, hFont);\n\n SetTextAlign(memDC, TA_LEFT | TA_TOP);\n SetTextCharacterExtra(memDC, 0);\n SetMapMode(memDC, MM_TEXT);\n\n DWORD quality = SetICMMode(memDC, ICM_ON);\n SetLayout(memDC, 0);\n\n int r = 255, g = 255, b = 255;\n const char* colorToUse = IS_COLOR_PREVIEWING ? PREVIEW_COLOR : CLOCK_TEXT_COLOR;\n \n if (strlen(colorToUse) > 0) {\n if (colorToUse[0] == '#') {\n if (strlen(colorToUse) == 7) {\n sscanf(colorToUse + 1, \"%02x%02x%02x\", &r, &g, &b);\n }\n } else {\n sscanf(colorToUse, \"%d,%d,%d\", &r, &g, &b);\n }\n }\n SetTextColor(memDC, RGB(r, g, b));\n\n if (CLOCK_EDIT_MODE) {\n HBRUSH hBrush = CreateSolidBrush(RGB(20, 20, 20)); // Dark gray background\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n } else {\n HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0));\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n }\n\n if (strlen(time_text) > 0) {\n SIZE textSize;\n GetTextExtentPoint32(memDC, time_text, strlen(time_text), &textSize);\n\n if (textSize.cx != (rect.right - rect.left) || \n textSize.cy != (rect.bottom - rect.top)) {\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left, windowRect.top,\n textSize.cx + WINDOW_HORIZONTAL_PADDING, \n textSize.cy + WINDOW_VERTICAL_PADDING, \n SWP_NOZORDER | SWP_NOACTIVATE);\n GetClientRect(hwnd, &rect);\n }\n\n \n int x = (rect.right - textSize.cx) / 2;\n int y = (rect.bottom - textSize.cy) / 2;\n\n // If in edit mode, force white text and add outline effect\n if (CLOCK_EDIT_MODE) {\n SetTextColor(memDC, RGB(255, 255, 255));\n \n // Add black outline effect\n SetTextColor(memDC, RGB(0, 0, 0));\n TextOutA(memDC, x-1, y, time_text, strlen(time_text));\n TextOutA(memDC, x+1, y, time_text, strlen(time_text));\n TextOutA(memDC, x, y-1, time_text, strlen(time_text));\n TextOutA(memDC, x, y+1, time_text, strlen(time_text));\n \n // Set back to white for drawing text\n SetTextColor(memDC, RGB(255, 255, 255));\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n } else {\n SetTextColor(memDC, RGB(r, g, b));\n \n for (int i = 0; i < 8; i++) {\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n }\n }\n }\n\n BitBlt(hdc, 0, 0, rect.right, rect.bottom, memDC, 0, 0, SRCCOPY);\n\n SelectObject(memDC, oldFont);\n DeleteObject(hFont);\n SelectObject(memDC, oldBitmap);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n}"], ["/Catime/src/audio_player.c", "/**\n * @file audio_player.c\n * @brief Audio playback functionality handler\n */\n\n#include \n#include \n#include \n#include \"../libs/miniaudio/miniaudio.h\"\n\n#include \"config.h\"\n\nextern char NOTIFICATION_SOUND_FILE[MAX_PATH];\nextern int NOTIFICATION_SOUND_VOLUME;\n\ntypedef void (*AudioPlaybackCompleteCallback)(HWND hwnd);\n\nstatic ma_engine g_audioEngine;\nstatic ma_sound g_sound;\nstatic ma_bool32 g_engineInitialized = MA_FALSE;\nstatic ma_bool32 g_soundInitialized = MA_FALSE;\n\nstatic AudioPlaybackCompleteCallback g_audioCompleteCallback = NULL;\nstatic HWND g_audioCallbackHwnd = NULL;\nstatic UINT_PTR g_audioTimerId = 0;\n\nstatic ma_bool32 g_isPlaying = MA_FALSE;\nstatic ma_bool32 g_isPaused = MA_FALSE;\n\nstatic void CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime);\n\n/**\n * @brief Initialize audio engine\n */\nstatic BOOL InitializeAudioEngine() {\n if (g_engineInitialized) {\n return TRUE;\n }\n\n ma_result result = ma_engine_init(NULL, &g_audioEngine);\n if (result != MA_SUCCESS) {\n return FALSE;\n }\n\n g_engineInitialized = MA_TRUE;\n return TRUE;\n}\n\n/**\n * @brief Clean up audio engine resources\n */\nstatic void UninitializeAudioEngine() {\n if (g_engineInitialized) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n ma_engine_uninit(&g_audioEngine);\n g_engineInitialized = MA_FALSE;\n }\n}\n\n/**\n * @brief Check if a file exists\n */\nstatic BOOL FileExists(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2);\n\n DWORD dwAttrib = GetFileAttributesW(wFilePath);\n return (dwAttrib != INVALID_FILE_ATTRIBUTES &&\n !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));\n}\n\n/**\n * @brief Show error message dialog\n */\nstatic void ShowErrorMessage(HWND hwnd, const wchar_t* errorMsg) {\n MessageBoxW(hwnd, errorMsg, L\"Audio Playback Error\", MB_ICONERROR | MB_OK);\n}\n\n/**\n * @brief Timer callback to check if audio playback is complete\n */\nstatic void CALLBACK CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n if (g_engineInitialized && g_soundInitialized) {\n if (!ma_sound_is_playing(&g_sound) && !g_isPaused) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n } else {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n}\n\n/**\n * @brief System beep playback completion callback timer function\n */\nstatic void CALLBACK SystemBeepDoneCallback(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n}\n\n/**\n * @brief Set audio playback volume\n * @param volume Volume percentage (0-100)\n */\nvoid SetAudioVolume(int volume) {\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n\n if (g_engineInitialized) {\n float volFloat = (float)volume / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volFloat);\n\n if (g_soundInitialized && g_isPlaying) {\n ma_sound_set_volume(&g_sound, volFloat);\n }\n }\n}\n\n/**\n * @brief Play audio file using miniaudio\n */\nstatic BOOL PlayAudioWithMiniaudio(HWND hwnd, const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (!g_engineInitialized) {\n if (!InitializeAudioEngine()) {\n return FALSE;\n }\n }\n\n float volume = (float)NOTIFICATION_SOUND_VOLUME / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volume);\n\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n if (MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (UTF-8->Unicode): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n wchar_t shortPath[MAX_PATH] = {0};\n DWORD shortPathLen = GetShortPathNameW(wFilePath, shortPath, MAX_PATH);\n if (shortPathLen == 0 || shortPathLen >= MAX_PATH) {\n DWORD error = GetLastError();\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Failed to get short path: %ls\\nError code: %lu\", wFilePath, error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n char asciiPath[MAX_PATH] = {0};\n if (WideCharToMultiByte(CP_ACP, 0, shortPath, -1, asciiPath, MAX_PATH, NULL, NULL) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (Short Path->ASCII): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n return FALSE;\n }\n\n ma_result result = ma_sound_init_from_file(&g_audioEngine, asciiPath, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n char utf8Path[MAX_PATH * 4] = {0};\n WideCharToMultiByte(CP_UTF8, 0, wFilePath, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n\n result = ma_sound_init_from_file(&g_audioEngine, utf8Path, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Unable to load audio file: %ls\\nError code: %d\", wFilePath, result);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n }\n\n g_soundInitialized = MA_TRUE;\n\n if (ma_sound_start(&g_sound) != MA_SUCCESS) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n ShowErrorMessage(hwnd, L\"Cannot start audio playback\");\n return FALSE;\n }\n\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1001, 500, (TIMERPROC)CheckAudioPlaybackComplete);\n\n return TRUE;\n}\n\n/**\n * @brief Validate if file path is legal\n */\nstatic BOOL IsValidFilePath(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (strchr(filePath, '=') != NULL) return FALSE;\n\n if (strlen(filePath) >= MAX_PATH) return FALSE;\n\n return TRUE;\n}\n\n/**\n * @brief Clean up audio resources\n */\nvoid CleanupAudioResources(void) {\n PlaySound(NULL, NULL, SND_PURGE);\n\n if (g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n if (g_audioTimerId != 0 && g_audioCallbackHwnd != NULL) {\n KillTimer(g_audioCallbackHwnd, g_audioTimerId);\n g_audioTimerId = 0;\n }\n\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n}\n\n/**\n * @brief Set audio playback completion callback function\n */\nvoid SetAudioPlaybackCompleteCallback(HWND hwnd, AudioPlaybackCompleteCallback callback) {\n g_audioCallbackHwnd = hwnd;\n g_audioCompleteCallback = callback;\n}\n\n/**\n * @brief Play notification audio\n */\nBOOL PlayNotificationSound(HWND hwnd) {\n CleanupAudioResources();\n\n g_audioCallbackHwnd = hwnd;\n\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (!IsValidFilePath(NOTIFICATION_SOUND_FILE)) {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Invalid audio file path:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (FileExists(NOTIFICATION_SOUND_FILE)) {\n if (PlayAudioWithMiniaudio(hwnd, NOTIFICATION_SOUND_FILE)) {\n return TRUE;\n }\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n } else {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Cannot find the configured audio file:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Pause currently playing notification audio\n */\nBOOL PauseNotificationSound(void) {\n if (g_isPlaying && !g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n g_isPaused = MA_TRUE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Resume previously paused notification audio\n */\nBOOL ResumeNotificationSound(void) {\n if (g_isPlaying && g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_start(&g_sound);\n g_isPaused = MA_FALSE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Stop playing notification audio\n */\nvoid StopNotificationSound(void) {\n CleanupAudioResources();\n}"], ["/Catime/src/dialog_language.c", "/**\n * @file dialog_language.c\n * @brief Dialog multi-language support module implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \"../include/dialog_language.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\ntypedef struct {\n int dialogID;\n wchar_t* titleKey;\n} DialogTitleEntry;\n\ntypedef struct {\n int dialogID;\n int controlID;\n wchar_t* textKey;\n wchar_t* fallbackText;\n} SpecialControlEntry;\n\ntypedef struct {\n HWND hwndDlg;\n int dialogID;\n} EnumChildWindowsData;\n\nstatic DialogTitleEntry g_dialogTitles[] = {\n {IDD_ABOUT_DIALOG, L\"About\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, L\"Notification Settings\"},\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, L\"Set Pomodoro Loop Count\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, L\"Set Pomodoro Time Combination\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, L\"Set Pomodoro Time\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, L\"Countdown Presets\"},\n {CLOCK_IDD_WEBSITE_DIALOG, L\"Open Website\"},\n {CLOCK_IDD_DIALOG1, L\"Set Countdown\"},\n {IDD_NO_UPDATE_DIALOG, L\"Update Check\"},\n {IDD_UPDATE_DIALOG, L\"Update Available\"}\n};\n\nstatic SpecialControlEntry g_specialControls[] = {\n {IDD_ABOUT_DIALOG, IDC_ABOUT_TITLE, L\"关于\", L\"About\"},\n {IDD_ABOUT_DIALOG, IDC_VERSION_TEXT, L\"Version: %hs\", L\"Version: %hs\"},\n {IDD_ABOUT_DIALOG, IDC_BUILD_DATE, L\"构建日期:\", L\"Build Date:\"},\n {IDD_ABOUT_DIALOG, IDC_COPYRIGHT, L\"COPYRIGHT_TEXT\", L\"COPYRIGHT_TEXT\"},\n {IDD_ABOUT_DIALOG, IDC_CREDITS, L\"鸣谢\", L\"Credits\"},\n\n {IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT, L\"NoUpdateRequired\", L\"You are already using the latest version!\"},\n\n {IDD_UPDATE_DIALOG, IDC_UPDATE_TEXT, L\"CurrentVersion: %s\\nNewVersion: %s\", L\"Current Version: %s\\nNew Version: %s\"},\n {IDD_UPDATE_DIALOG, IDC_UPDATE_EXIT_TEXT, L\"The application will exit now\", L\"The application will exit now\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_CONTENT_GROUP, L\"Notification Content\", L\"Notification Content\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL1, L\"Countdown timeout message:\", L\"Countdown timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL2, L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL3, L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_DISPLAY_GROUP, L\"Notification Display\", L\"Notification Display\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TIME_LABEL, L\"Notification display time:\", L\"Notification display time:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_LABEL, L\"Maximum notification opacity (1-100%):\", L\"Maximum notification opacity (1-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_DISABLE_NOTIFICATION_CHECK, L\"Disable notifications\", L\"Disable notifications\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_METHOD_GROUP, L\"Notification Method\", L\"Notification Method\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_CATIME, L\"Catime notification window\", L\"Catime notification window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_OS, L\"System notification\", L\"System notification\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, L\"System modal window\", L\"System modal window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_SOUND_LABEL, L\"Sound (supports .mp3/.wav/.flac):\", L\"Sound (supports .mp3/.wav/.flac):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_LABEL, L\"Volume (0-100%):\", L\"Volume (0-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_TEXT, L\"100%\", L\"100%\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_TEXT, L\"100%\", L\"100%\"},\n\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_STATIC,\n L\"25=25 minutes\\\\n25h=25 hours\\\\n25s=25 seconds\\\\n25 30=25 minutes 30 seconds\\\\n25 30m=25 hours 30 minutes\\\\n1 30 20=1 hour 30 minutes 20 seconds\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\"},\n\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter pomodoro time sequence, separated by spaces:\\\\n\\\\n25m = 25 minutes\\\\n30s = 30 seconds\\\\n1h30m = 1 hour 30 minutes\\\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\",\n L\"Enter pomodoro time sequence, separated by spaces:\\n\\n25m = 25 minutes\\n30s = 30 seconds\\n1h30m = 1 hour 30 minutes\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\"},\n\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter the website URL to open when the countdown ends:\\\\nExample: https://github.com/vladelaina/Catime\",\n L\"Enter the website URL to open when the countdown ends:\\nExample: https://github.com/vladelaina/Catime\"},\n\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_STATIC,\n L\"CountdownPresetDialogStaticText\",\n L\"Enter numbers (minutes), separated by spaces\\n\\n25 10 5\\n\\nThis will create options for 25 minutes, 10 minutes, and 5 minutes\"},\n\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_STATIC,\n L\"CountdownDialogStaticText\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\\n17 20t=Countdown to 17:20\\n9 9 9t=Countdown to 09:09:09\"}\n};\n\nstatic SpecialControlEntry g_specialButtons[] = {\n {IDD_UPDATE_DIALOG, IDYES, L\"Yes\", L\"Yes\"},\n {IDD_UPDATE_DIALOG, IDNO, L\"No\", L\"No\"},\n {IDD_UPDATE_DIALOG, IDOK, L\"OK\", L\"OK\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_TEST_SOUND_BUTTON, L\"Test\", L\"Test\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_OPEN_SOUND_DIR_BUTTON, L\"Audio folder\", L\"Audio folder\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDOK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDCANCEL, L\"Cancel\", L\"Cancel\"},\n\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"}\n};\n\n#define DIALOG_TITLES_COUNT (sizeof(g_dialogTitles) / sizeof(g_dialogTitles[0]))\n#define SPECIAL_CONTROLS_COUNT (sizeof(g_specialControls) / sizeof(g_specialControls[0]))\n#define SPECIAL_BUTTONS_COUNT (sizeof(g_specialButtons) / sizeof(g_specialButtons[0]))\n\n/**\n * @brief Find localized text for special controls\n */\nstatic const wchar_t* FindSpecialControlText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_CONTROLS_COUNT; i++) {\n if (g_specialControls[i].dialogID == dialogID &&\n g_specialControls[i].controlID == controlID) {\n const wchar_t* localizedText = GetLocalizedString(NULL, g_specialControls[i].textKey);\n if (localizedText) {\n return localizedText;\n } else {\n return g_specialControls[i].fallbackText;\n }\n }\n }\n return NULL;\n}\n\n/**\n * @brief Find localized text for special buttons\n */\nstatic const wchar_t* FindSpecialButtonText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_BUTTONS_COUNT; i++) {\n if (g_specialButtons[i].dialogID == dialogID &&\n g_specialButtons[i].controlID == controlID) {\n return GetLocalizedString(NULL, g_specialButtons[i].textKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get localized text for dialog title\n */\nstatic const wchar_t* GetDialogTitleText(int dialogID) {\n for (int i = 0; i < DIALOG_TITLES_COUNT; i++) {\n if (g_dialogTitles[i].dialogID == dialogID) {\n return GetLocalizedString(NULL, g_dialogTitles[i].titleKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get original text of a control for translation lookup\n */\nstatic BOOL GetControlOriginalText(HWND hwndCtl, wchar_t* buffer, int bufferSize) {\n wchar_t className[256];\n GetClassNameW(hwndCtl, className, 256);\n\n if (wcscmp(className, L\"Button\") == 0 ||\n wcscmp(className, L\"Static\") == 0 ||\n wcscmp(className, L\"ComboBox\") == 0 ||\n wcscmp(className, L\"Edit\") == 0) {\n return GetWindowTextW(hwndCtl, buffer, bufferSize) > 0;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Process special control text settings, such as line breaks\n */\nstatic BOOL ProcessSpecialControlText(HWND hwndCtl, const wchar_t* localizedText, int dialogID, int controlID) {\n if ((dialogID == CLOCK_IDD_POMODORO_COMBO_DIALOG ||\n dialogID == CLOCK_IDD_POMODORO_TIME_DIALOG ||\n dialogID == CLOCK_IDD_WEBSITE_DIALOG ||\n dialogID == CLOCK_IDD_SHORTCUT_DIALOG ||\n dialogID == CLOCK_IDD_DIALOG1) &&\n controlID == CLOCK_IDC_STATIC) {\n wchar_t processedText[1024];\n const wchar_t* src = localizedText;\n wchar_t* dst = processedText;\n\n while (*src) {\n if (src[0] == L'\\\\' && src[1] == L'n') {\n *dst++ = L'\\n';\n src += 2;\n }\n else if (src[0] == L'\\n') {\n *dst++ = L'\\n';\n src++;\n }\n else {\n *dst++ = *src++;\n }\n }\n *dst = L'\\0';\n\n SetWindowTextW(hwndCtl, processedText);\n return TRUE;\n }\n\n if (controlID == IDC_VERSION_TEXT && dialogID == IDD_ABOUT_DIALOG) {\n wchar_t versionText[256];\n const wchar_t* localizedVersionFormat = GetLocalizedString(NULL, L\"Version: %hs\");\n if (localizedVersionFormat) {\n StringCbPrintfW(versionText, sizeof(versionText), localizedVersionFormat, CATIME_VERSION);\n } else {\n StringCbPrintfW(versionText, sizeof(versionText), localizedText, CATIME_VERSION);\n }\n SetWindowTextW(hwndCtl, versionText);\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Dialog child window enumeration callback function\n */\nstatic BOOL CALLBACK EnumChildProc(HWND hwndCtl, LPARAM lParam) {\n EnumChildWindowsData* data = (EnumChildWindowsData*)lParam;\n HWND hwndDlg = data->hwndDlg;\n int dialogID = data->dialogID;\n\n int controlID = GetDlgCtrlID(hwndCtl);\n if (controlID == 0) {\n return TRUE;\n }\n\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n if (ProcessSpecialControlText(hwndCtl, specialText, dialogID, controlID)) {\n return TRUE;\n }\n SetWindowTextW(hwndCtl, specialText);\n return TRUE;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n SetWindowTextW(hwndCtl, buttonText);\n return TRUE;\n }\n\n wchar_t originalText[512] = {0};\n if (GetControlOriginalText(hwndCtl, originalText, 512) && originalText[0] != L'\\0') {\n const wchar_t* localizedText = GetLocalizedString(NULL, originalText);\n if (localizedText && wcscmp(localizedText, originalText) != 0) {\n SetWindowTextW(hwndCtl, localizedText);\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Initialize dialog multi-language support\n */\nBOOL InitDialogLanguageSupport(void) {\n return TRUE;\n}\n\n/**\n * @brief Apply multi-language support to dialog\n */\nBOOL ApplyDialogLanguage(HWND hwndDlg, int dialogID) {\n if (!hwndDlg) return FALSE;\n\n const wchar_t* titleText = GetDialogTitleText(dialogID);\n if (titleText) {\n SetWindowTextW(hwndDlg, titleText);\n }\n\n EnumChildWindowsData data = {\n .hwndDlg = hwndDlg,\n .dialogID = dialogID\n };\n\n EnumChildWindows(hwndDlg, EnumChildProc, (LPARAM)&data);\n\n return TRUE;\n}\n\n/**\n * @brief Get localized text for dialog element\n */\nconst wchar_t* GetDialogLocalizedString(int dialogID, int controlID) {\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n return specialText;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n return buttonText;\n }\n\n if (controlID == -1) {\n return GetDialogTitleText(dialogID);\n }\n\n return NULL;\n}"], ["/Catime/src/tray.c", "/**\n * @file tray.c\n * @brief System tray functionality implementation\n */\n\n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/tray.h\"\n\nNOTIFYICONDATAW nid;\nUINT WM_TASKBARCREATED = 0;\n\n/**\n * @brief Register the TaskbarCreated message\n */\nvoid RegisterTaskbarCreatedMessage() {\n WM_TASKBARCREATED = RegisterWindowMessage(TEXT(\"TaskbarCreated\"));\n}\n\n/**\n * @brief Initialize the system tray icon\n * @param hwnd Window handle\n * @param hInstance Application instance handle\n */\nvoid InitTrayIcon(HWND hwnd, HINSTANCE hInstance) {\n memset(&nid, 0, sizeof(nid));\n nid.cbSize = sizeof(nid);\n nid.uID = CLOCK_ID_TRAY_APP_ICON;\n nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;\n nid.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CATIME));\n nid.hWnd = hwnd;\n nid.uCallbackMessage = CLOCK_WM_TRAYICON;\n \n wchar_t versionText[128] = {0};\n wchar_t versionWide[64] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CATIME_VERSION, -1, versionWide, _countof(versionWide));\n swprintf_s(versionText, _countof(versionText), L\"Catime %s\", versionWide);\n wcscpy_s(nid.szTip, _countof(nid.szTip), versionText);\n \n Shell_NotifyIconW(NIM_ADD, &nid);\n if (WM_TASKBARCREATED == 0) {\n RegisterTaskbarCreatedMessage();\n }\n}\n\n/**\n * @brief Remove the system tray icon\n */\nvoid RemoveTrayIcon(void) {\n Shell_NotifyIconW(NIM_DELETE, &nid);\n}\n\n/**\n * @brief Display a notification in the system tray\n * @param hwnd Window handle\n * @param message Text message to display\n */\nvoid ShowTrayNotification(HWND hwnd, const char* message) {\n NOTIFYICONDATAW nid_notify = {0};\n nid_notify.cbSize = sizeof(NOTIFYICONDATAW);\n nid_notify.hWnd = hwnd;\n nid_notify.uID = CLOCK_ID_TRAY_APP_ICON;\n nid_notify.uFlags = NIF_INFO;\n nid_notify.dwInfoFlags = NIIF_NONE;\n nid_notify.uTimeout = 3000;\n \n MultiByteToWideChar(CP_UTF8, 0, message, -1, nid_notify.szInfo, sizeof(nid_notify.szInfo)/sizeof(WCHAR));\n nid_notify.szInfoTitle[0] = L'\\0';\n \n Shell_NotifyIconW(NIM_MODIFY, &nid_notify);\n}\n\n/**\n * @brief Recreate the taskbar icon\n * @param hwnd Window handle\n * @param hInstance Instance handle\n */\nvoid RecreateTaskbarIcon(HWND hwnd, HINSTANCE hInstance) {\n RemoveTrayIcon();\n InitTrayIcon(hwnd, hInstance);\n}\n\n/**\n * @brief Update the tray icon and menu\n * @param hwnd Window handle\n */\nvoid UpdateTrayIcon(HWND hwnd) {\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n RecreateTaskbarIcon(hwnd, hInstance);\n}"], ["/Catime/src/language.c", "/**\n * @file language.c\n * @brief Multilingual support module implementation\n * \n * This file implements the multilingual support functionality for the application, \n * including language detection and localized string handling.\n * Translation content is embedded as resources in the executable file.\n */\n\n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\n/// Global language variable, stores the current application language setting\nAppLanguage CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default to English\n\n/// Global hash table for storing translations of the current language\n#define MAX_TRANSLATIONS 200\n#define MAX_STRING_LENGTH 1024\n\n// Language resource IDs (defined in languages.rc)\n#define LANG_EN_INI 1001 // Corresponds to languages/en.ini\n#define LANG_ZH_CN_INI 1002 // Corresponds to languages/zh_CN.ini\n#define LANG_ZH_TW_INI 1003 // Corresponds to languages/zh-Hant.ini\n#define LANG_ES_INI 1004 // Corresponds to languages/es.ini\n#define LANG_FR_INI 1005 // Corresponds to languages/fr.ini\n#define LANG_DE_INI 1006 // Corresponds to languages/de.ini\n#define LANG_RU_INI 1007 // Corresponds to languages/ru.ini\n#define LANG_PT_INI 1008 // Corresponds to languages/pt.ini\n#define LANG_JA_INI 1009 // Corresponds to languages/ja.ini\n#define LANG_KO_INI 1010 // Corresponds to languages/ko.ini\n\n/**\n * @brief Define language string key-value pair structure\n */\ntypedef struct {\n wchar_t english[MAX_STRING_LENGTH]; // English key\n wchar_t translation[MAX_STRING_LENGTH]; // Translated value\n} LocalizedString;\n\nstatic LocalizedString g_translations[MAX_TRANSLATIONS];\nstatic int g_translation_count = 0;\n\n/**\n * @brief Get the resource ID corresponding to a language\n * \n * @param language Language enumeration value\n * @return UINT Corresponding resource ID\n */\nstatic UINT GetLanguageResourceID(AppLanguage language) {\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n return LANG_ZH_CN_INI;\n case APP_LANG_CHINESE_TRAD:\n return LANG_ZH_TW_INI;\n case APP_LANG_SPANISH:\n return LANG_ES_INI;\n case APP_LANG_FRENCH:\n return LANG_FR_INI;\n case APP_LANG_GERMAN:\n return LANG_DE_INI;\n case APP_LANG_RUSSIAN:\n return LANG_RU_INI;\n case APP_LANG_PORTUGUESE:\n return LANG_PT_INI;\n case APP_LANG_JAPANESE:\n return LANG_JA_INI;\n case APP_LANG_KOREAN:\n return LANG_KO_INI;\n case APP_LANG_ENGLISH:\n default:\n return LANG_EN_INI;\n }\n}\n\n/**\n * @brief Convert UTF-8 string to wide character (UTF-16) string\n * \n * @param utf8 UTF-8 string\n * @param wstr Output wide character string buffer\n * @param wstr_size Buffer size (in characters)\n * @return int Number of characters after conversion, returns -1 if failed\n */\nstatic int UTF8ToWideChar(const char* utf8, wchar_t* wstr, int wstr_size) {\n return MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, wstr_size) - 1;\n}\n\n/**\n * @brief Parse a line in an ini file\n * \n * @param line A line from the ini file\n * @return int Whether parsing was successful (1 for success, 0 for failure)\n */\nstatic int ParseIniLine(const wchar_t* line) {\n // Skip empty lines and comment lines\n if (line[0] == L'\\0' || line[0] == L';' || line[0] == L'[') {\n return 0;\n }\n\n // Find content between the first and last quotes as the key\n const wchar_t* key_start = wcschr(line, L'\"');\n if (!key_start) return 0;\n key_start++; // Skip the first quote\n\n const wchar_t* key_end = wcschr(key_start, L'\"');\n if (!key_end) return 0;\n\n // Find content between the first and last quotes after the equal sign as the value\n const wchar_t* value_start = wcschr(key_end + 1, L'=');\n if (!value_start) return 0;\n \n value_start = wcschr(value_start, L'\"');\n if (!value_start) return 0;\n value_start++; // Skip the first quote\n\n const wchar_t* value_end = wcsrchr(value_start, L'\"');\n if (!value_end) return 0;\n\n // Copy key\n size_t key_len = key_end - key_start;\n if (key_len >= MAX_STRING_LENGTH) key_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].english, key_start, key_len);\n g_translations[g_translation_count].english[key_len] = L'\\0';\n\n // Copy value\n size_t value_len = value_end - value_start;\n if (value_len >= MAX_STRING_LENGTH) value_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].translation, value_start, value_len);\n g_translations[g_translation_count].translation[value_len] = L'\\0';\n\n g_translation_count++;\n return 1;\n}\n\n/**\n * @brief Load translations for a specified language from resources\n * \n * @param language Language enumeration value\n * @return int Whether loading was successful\n */\nstatic int LoadLanguageResource(AppLanguage language) {\n UINT resourceID = GetLanguageResourceID(language);\n \n // Reset translation count\n g_translation_count = 0;\n \n // Find resource\n HRSRC hResInfo = FindResource(NULL, MAKEINTRESOURCE(resourceID), RT_RCDATA);\n if (!hResInfo) {\n // If not found, check if it's Chinese and return\n if (language == APP_LANG_CHINESE_SIMP || language == APP_LANG_CHINESE_TRAD) {\n return 0;\n }\n \n // If not Chinese, load English as fallback\n if (language != APP_LANG_ENGLISH) {\n return LoadLanguageResource(APP_LANG_ENGLISH);\n }\n \n return 0;\n }\n \n // Get resource size\n DWORD dwSize = SizeofResource(NULL, hResInfo);\n if (dwSize == 0) {\n return 0;\n }\n \n // Load resource\n HGLOBAL hResData = LoadResource(NULL, hResInfo);\n if (!hResData) {\n return 0;\n }\n \n // Lock resource to get pointer\n const char* pData = (const char*)LockResource(hResData);\n if (!pData) {\n return 0;\n }\n \n // Create memory buffer copy\n char* buffer = (char*)malloc(dwSize + 1);\n if (!buffer) {\n return 0;\n }\n \n // Copy resource data to buffer\n memcpy(buffer, pData, dwSize);\n buffer[dwSize] = '\\0';\n \n // Split by lines and parse\n char* line = strtok(buffer, \"\\r\\n\");\n wchar_t wide_buffer[MAX_STRING_LENGTH];\n \n while (line && g_translation_count < MAX_TRANSLATIONS) {\n // Skip empty lines and BOM markers\n if (line[0] == '\\0' || (line[0] == (char)0xEF && line[1] == (char)0xBB && line[2] == (char)0xBF)) {\n line = strtok(NULL, \"\\r\\n\");\n continue;\n }\n \n // Convert to wide characters\n if (UTF8ToWideChar(line, wide_buffer, MAX_STRING_LENGTH) > 0) {\n ParseIniLine(wide_buffer);\n }\n \n line = strtok(NULL, \"\\r\\n\");\n }\n \n free(buffer);\n return 1;\n}\n\n/**\n * @brief Find corresponding translation in the global translation table\n * \n * @param english English original text\n * @return const wchar_t* Found translation, returns NULL if not found\n */\nstatic const wchar_t* FindTranslation(const wchar_t* english) {\n for (int i = 0; i < g_translation_count; i++) {\n if (wcscmp(english, g_translations[i].english) == 0) {\n return g_translations[i].translation;\n }\n }\n return NULL;\n}\n\n/**\n * @brief Initialize the application language environment\n * \n * Automatically detect and set the current language of the application based on system language.\n * Supports detection of Simplified Chinese, Traditional Chinese, and other preset languages.\n */\nstatic void DetectSystemLanguage() {\n LANGID langID = GetUserDefaultUILanguage();\n switch (PRIMARYLANGID(langID)) {\n case LANG_CHINESE:\n // Distinguish between Simplified and Traditional Chinese\n if (SUBLANGID(langID) == SUBLANG_CHINESE_SIMPLIFIED) {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_SIMP;\n } else {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_TRAD;\n }\n break;\n case LANG_SPANISH:\n CURRENT_LANGUAGE = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n CURRENT_LANGUAGE = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n CURRENT_LANGUAGE = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n CURRENT_LANGUAGE = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n CURRENT_LANGUAGE = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n CURRENT_LANGUAGE = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n CURRENT_LANGUAGE = APP_LANG_KOREAN;\n break;\n default:\n CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default fallback to English\n }\n}\n\n/**\n * @brief Get localized string\n * @param chinese Simplified Chinese version of the string\n * @param english English version of the string\n * @return const wchar_t* Pointer to the string corresponding to the current language\n * \n * Returns the string in the corresponding language based on the current language setting.\n */\nconst wchar_t* GetLocalizedString(const wchar_t* chinese, const wchar_t* english) {\n // Initialize translation resources on first call, but don't automatically detect system language\n static BOOL initialized = FALSE;\n if (!initialized) {\n // No longer call DetectSystemLanguage() to automatically detect system language\n // Instead, use the currently set CURRENT_LANGUAGE value (possibly from a configuration file)\n LoadLanguageResource(CURRENT_LANGUAGE);\n initialized = TRUE;\n }\n\n const wchar_t* translation = NULL;\n\n // If Simplified Chinese and Chinese string is provided, return directly\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP && chinese) {\n return chinese;\n }\n\n // Find translation\n translation = FindTranslation(english);\n if (translation) {\n return translation;\n }\n\n // For Traditional Chinese but no translation found, return Simplified Chinese as a fallback\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD && chinese) {\n return chinese;\n }\n\n // Default to English\n return english;\n}\n\n/**\n * @brief Set application language\n * \n * @param language The language to set\n * @return BOOL Whether the setting was successful\n */\nBOOL SetLanguage(AppLanguage language) {\n if (language < 0 || language >= APP_LANG_COUNT) {\n return FALSE;\n }\n \n CURRENT_LANGUAGE = language;\n g_translation_count = 0; // Clear existing translations\n return LoadLanguageResource(language);\n}\n\n/**\n * @brief Get current application language\n * \n * @return AppLanguage Current language\n */\nAppLanguage GetCurrentLanguage() {\n return CURRENT_LANGUAGE;\n}\n\n/**\n * @brief Get the name of the current language\n * @param buffer Buffer to store the language name\n * @param bufferSize Buffer size (in characters)\n * @return Whether the language name was successfully retrieved\n */\nBOOL GetCurrentLanguageName(wchar_t* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) {\n return FALSE;\n }\n \n // Get current language\n AppLanguage language = GetCurrentLanguage();\n \n // Return corresponding name based on language enumeration\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n wcscpy_s(buffer, bufferSize, L\"zh_CN\");\n break;\n case APP_LANG_CHINESE_TRAD:\n wcscpy_s(buffer, bufferSize, L\"zh-Hant\");\n break;\n case APP_LANG_SPANISH:\n wcscpy_s(buffer, bufferSize, L\"es\");\n break;\n case APP_LANG_FRENCH:\n wcscpy_s(buffer, bufferSize, L\"fr\");\n break;\n case APP_LANG_GERMAN:\n wcscpy_s(buffer, bufferSize, L\"de\");\n break;\n case APP_LANG_RUSSIAN:\n wcscpy_s(buffer, bufferSize, L\"ru\");\n break;\n case APP_LANG_PORTUGUESE:\n wcscpy_s(buffer, bufferSize, L\"pt\");\n break;\n case APP_LANG_JAPANESE:\n wcscpy_s(buffer, bufferSize, L\"ja\");\n break;\n case APP_LANG_KOREAN:\n wcscpy_s(buffer, bufferSize, L\"ko\");\n break;\n case APP_LANG_ENGLISH:\n default:\n wcscpy_s(buffer, bufferSize, L\"en\");\n break;\n }\n \n return TRUE;\n}\n"], ["/Catime/src/window_events.c", "/**\n * @file window_events.c\n * @brief Implementation of basic window event handling\n * \n * This file implements the basic event handling functionality for the application window,\n * including window creation, destruction, resizing, and position adjustment.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/tray.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/window_events.h\"\n\n/**\n * @brief Handle window creation event\n * @param hwnd Window handle\n * @return BOOL Processing result\n */\nBOOL HandleWindowCreate(HWND hwnd) {\n HWND hwndParent = GetParent(hwnd);\n if (hwndParent != NULL) {\n EnableWindow(hwndParent, TRUE);\n }\n \n // Load window settings\n LoadWindowSettings(hwnd);\n \n // Set click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // Ensure window is in topmost state\n SetWindowTopmost(hwnd, CLOCK_WINDOW_TOPMOST);\n \n return TRUE;\n}\n\n/**\n * @brief Handle window destruction event\n * @param hwnd Window handle\n */\nvoid HandleWindowDestroy(HWND hwnd) {\n SaveWindowSettings(hwnd); // Save window settings\n KillTimer(hwnd, 1);\n RemoveTrayIcon();\n \n // Clean up update check thread\n extern void CleanupUpdateThread(void);\n CleanupUpdateThread();\n \n PostQuitMessage(0);\n}\n\n/**\n * @brief Handle window reset event\n * @param hwnd Window handle\n */\nvoid HandleWindowReset(HWND hwnd) {\n // Unconditionally apply topmost setting from configuration\n // Regardless of the current CLOCK_WINDOW_TOPMOST value, force it to TRUE and apply\n CLOCK_WINDOW_TOPMOST = TRUE;\n SetWindowTopmost(hwnd, TRUE);\n WriteConfigTopmost(\"TRUE\");\n \n // Ensure window is always visible - solves the issue of timer not being visible after reset\n ShowWindow(hwnd, SW_SHOW);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowResize(HWND hwnd, int delta) {\n return HandleScaleWindow(hwnd, delta);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowMove(HWND hwnd) {\n return HandleDragWindow(hwnd);\n}\n"], ["/Catime/src/drag_scale.c", "/**\n * @file drag_scale.c\n * @brief Window dragging and scaling functionality implementation\n * \n * This file implements the dragging and scaling functionality of the application window,\n * including mouse dragging of the window and mouse wheel scaling of the window.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n\n// Add variable to record the topmost state before edit mode\nBOOL PREVIOUS_TOPMOST_STATE = FALSE;\n\nvoid StartDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_IS_DRAGGING = TRUE;\n SetCapture(hwnd);\n GetCursorPos(&CLOCK_LAST_MOUSE_POS);\n }\n}\n\nvoid StartEditMode(HWND hwnd) {\n // Record current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If currently not in topmost state, set to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Then enable edit mode\n CLOCK_EDIT_MODE = TRUE;\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure mouse cursor is default arrow\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n}\n\nvoid EndEditMode(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_EDIT_MODE = FALSE;\n \n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // If previously not in topmost state, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n }\n}\n\nvoid EndDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n CLOCK_IS_DRAGGING = FALSE;\n ReleaseCapture();\n // In edit mode, don't force window to stay on screen, allow dragging out\n AdjustWindowPosition(hwnd, FALSE);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\nBOOL HandleDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleScaleWindow(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings\n SaveWindowSettings(hwnd);\n return TRUE;\n }\n }\n return FALSE;\n}"], ["/Catime/src/media.c", "/**\n * @file media.c\n * @brief Media control functionality implementation\n * \n * This file implements the application's media control related functions,\n * including pause, play and other media control operations.\n */\n\n#include \n#include \"../include/media.h\"\n\n/**\n * @brief Pause media playback\n * \n * Pauses currently playing media by simulating media control key press events.\n * Includes a combination of stop and pause/play operations to ensure the media is properly paused.\n */\nvoid PauseMediaPlayback(void) {\n keybd_event(VK_MEDIA_STOP, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_STOP, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(100);\n}"], ["/Catime/libs/miniaudio/miniaudio.c", "#define MINIAUDIO_IMPLEMENTATION\n#include \"miniaudio.h\"\n"]], "task_instance_info": {"created_time": "2025-08-20 17:54:33", "created_task_model": "DeepSeek-R1", "function_skeleton": "static void HandleStartupMode(HWND hwnd) {}", "code_description": "This code segment functions to: Configure application initialization parameters based on specified operational modes by adjusting visibility states, timer controls, and tracking variables according to predefined configuration settings."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nstatic void HandleStartupMode(HWND hwnd) {\n // Handle minimized startup mode\n if (strcmp(CLOCK_STARTUP_MODE, \"minimized\") == 0) {\n ShowWindow(hwnd, SW_HIDE);\n TrayUpdateIcon(NIM_ADD);\n }\n // Handle autostart countdown mode\n else if (strcmp(CLOCK_STARTUP_MODE, \"autostart\") == 0) {\n elapsed_time = CLOCK_DEFAULT_START_TIME;\n SetWindowTextA(GetDlgItem(hwnd, IDC_BUTTON_START), GetTranslation(TR_ID_STOP_TIMER));\n UpdateTimeDisplay(hwnd);\n }\n // Default normal startup mode\n else {\n ShowWindow(hwnd, SW_SHOW);\n UpdateWindow(hwnd);\n }\n \n // Special handling for portable mode detected from path\n char exe_path[MAX_PATH];\n GetModuleFileNameA(NULL, exe_path, MAX_PATH);\n if (strstr(exe_path, \"Portable\") != NULL) {\n WritePrivateProfileStringA(\"Settings\", \"StartupMode\", \"normal\", CONFIG_FILE_PATH);\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 17-55-16"}, "editdistance_info": {"edit_distance": 26.1411, "calculate_time": "2025-08-20 17:55:16", "true_code_clean": "static void HandleStartupMode(HWND hwnd) {\n LOG_INFO(\"Setting startup mode: %s\", CLOCK_STARTUP_MODE);\n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n LOG_INFO(\"Setting to count-up mode\");\n CLOCK_COUNT_UP = TRUE;\n elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n LOG_INFO(\"Setting to hidden mode, window will be hidden\");\n ShowWindow(hwnd, SW_HIDE);\n KillTimer(hwnd, 1);\n elapsed_time = CLOCK_TOTAL_TIME;\n CLOCK_IS_PAUSED = TRUE;\n message_shown = TRUE;\n countdown_message_shown = TRUE;\n countup_message_shown = TRUE;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n LOG_INFO(\"Setting to show current time mode\");\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_LAST_TIME_UPDATE = 0;\n } else {\n LOG_INFO(\"Using default countdown mode\");\n }\n}", "predict_code_clean": "static void HandleStartupMode(HWND hwnd) {\n if (strcmp(CLOCK_STARTUP_MODE, \"minimized\") == 0) {\n ShowWindow(hwnd, SW_HIDE);\n TrayUpdateIcon(NIM_ADD);\n }\n else if (strcmp(CLOCK_STARTUP_MODE, \"autostart\") == 0) {\n elapsed_time = CLOCK_DEFAULT_START_TIME;\n SetWindowTextA(GetDlgItem(hwnd, IDC_BUTTON_START), GetTranslation(TR_ID_STOP_TIMER));\n UpdateTimeDisplay(hwnd);\n }\n else {\n ShowWindow(hwnd, SW_SHOW);\n UpdateWindow(hwnd);\n }\n char exe_path[MAX_PATH];\n GetModuleFileNameA(NULL, exe_path, MAX_PATH);\n if (strstr(exe_path, \"Portable\") != NULL) {\n WritePrivateProfileStringA(\"Settings\", \"StartupMode\", \"normal\", CONFIG_FILE_PATH);\n }\n}"}} {"repo_name": "Catime", "file_name": "/Catime/src/main.c", "inference_info": {"prefix_code": "/**\n * @file main.c\n * @brief Application main entry module implementation file\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\"\n#include \"../include/window.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/media.h\"\n#include \"../include/notification.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/dialog_language.h\"\n#include \"../include/shortcut_checker.h\"\n\n// Required for older Windows SDK\n#ifndef CSIDL_STARTUP\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n// Compiler directives\n#pragma comment(lib, \"dwmapi.lib\")\n#pragma comment(lib, \"user32.lib\")\n#pragma comment(lib, \"gdi32.lib\")\n#pragma comment(lib, \"comdlg32.lib\")\n#pragma comment(lib, \"dbghelp.lib\")\n#pragma comment(lib, \"comctl32.lib\")\n\nextern void CleanupLogSystem(void);\n\nint default_countdown_time = 0;\nint CLOCK_DEFAULT_START_TIME = 300;\nint elapsed_time = 0;\nchar inputText[256] = {0};\nint message_shown = 0;\ntime_t last_config_time = 0;\nRecentFile CLOCK_RECENT_FILES[MAX_RECENT_FILES];\nint CLOCK_RECENT_FILES_COUNT = 0;\nchar CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH] = \"\";\n\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char FONT_INTERNAL_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\n\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid ExitProgram(HWND hwnd);\n\n/**\n * @brief Handle application startup mode\n * @param hwnd Main window handle\n */\n", "suffix_code": "\n\n/**\n * @brief Application main entry point\n */\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n // Initialize Common Controls\n InitCommonControls();\n \n // Initialize log system\n if (!InitializeLogSystem()) {\n // If log system initialization fails, continue running but without logging\n MessageBox(NULL, \"Log system initialization failed, the program will continue running but will not log.\", \"Warning\", MB_ICONWARNING);\n }\n\n // Set up exception handler\n SetupExceptionHandler();\n\n LOG_INFO(\"Catime is starting...\");\n // Initialize COM\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM initialization failed, error code: 0x%08X\", hr);\n MessageBox(NULL, \"COM initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"COM initialization successful\");\n\n // Initialize application\n LOG_INFO(\"Starting application initialization...\");\n if (!InitializeApplication(hInstance)) {\n LOG_ERROR(\"Application initialization failed\");\n MessageBox(NULL, \"Application initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"Application initialization successful\");\n\n // Check and create desktop shortcut (if necessary)\n LOG_INFO(\"Checking desktop shortcut...\");\n char exe_path[MAX_PATH];\n GetModuleFileNameA(NULL, exe_path, MAX_PATH);\n LOG_INFO(\"Current program path: %s\", exe_path);\n \n // Set log level to DEBUG to show detailed information\n WriteLog(LOG_LEVEL_DEBUG, \"Starting shortcut detection, checking path: %s\", exe_path);\n \n // Check if path contains WinGet identifier\n if (strstr(exe_path, \"WinGet\") != NULL) {\n WriteLog(LOG_LEVEL_DEBUG, \"Path contains WinGet keyword\");\n }\n \n // Additional test: directly test if file exists\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path))) {\n sprintf(shortcut_path, \"%s\\\\Catime.lnk\", desktop_path);\n WriteLog(LOG_LEVEL_DEBUG, \"Checking if desktop shortcut exists: %s\", shortcut_path);\n if (GetFileAttributesA(shortcut_path) == INVALID_FILE_ATTRIBUTES) {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut does not exist, need to create\");\n } else {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut already exists\");\n }\n }\n \n int shortcut_result = CheckAndCreateShortcut();\n if (shortcut_result == 0) {\n LOG_INFO(\"Desktop shortcut check completed\");\n } else {\n LOG_WARNING(\"Desktop shortcut creation failed, error code: %d\", shortcut_result);\n }\n\n // Initialize dialog multi-language support\n LOG_INFO(\"Starting dialog multi-language support initialization...\");\n if (!InitDialogLanguageSupport()) {\n LOG_WARNING(\"Dialog multi-language support initialization failed, but program will continue running\");\n }\n LOG_INFO(\"Dialog multi-language support initialization successful\");\n\n // Handle single instance\n LOG_INFO(\"Checking if another instance is running...\");\n HANDLE hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n DWORD mutexError = GetLastError();\n \n if (mutexError == ERROR_ALREADY_EXISTS) {\n LOG_INFO(\"Detected another instance is running, trying to close that instance\");\n HWND hwndExisting = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwndExisting) {\n // Close existing window instance\n LOG_INFO(\"Sending close message to existing instance\");\n SendMessage(hwndExisting, WM_CLOSE, 0, 0);\n // Wait for old instance to close\n Sleep(200);\n } else {\n LOG_WARNING(\"Could not find window handle of existing instance, but mutex exists\");\n }\n // Release old mutex\n ReleaseMutex(hMutex);\n CloseHandle(hMutex);\n \n // Create new mutex\n LOG_INFO(\"Creating new mutex\");\n hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n if (GetLastError() == ERROR_ALREADY_EXISTS) {\n LOG_WARNING(\"Still have conflict after creating new mutex, possible race condition\");\n }\n }\n Sleep(50);\n\n // Create main window\n LOG_INFO(\"Starting main window creation...\");\n HWND hwnd = CreateMainWindow(hInstance, nCmdShow);\n if (!hwnd) {\n LOG_ERROR(\"Main window creation failed\");\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Main window creation successful, handle: 0x%p\", hwnd);\n\n // Set timer\n LOG_INFO(\"Setting main timer...\");\n if (SetTimer(hwnd, 1, 1000, NULL) == 0) {\n DWORD timerError = GetLastError();\n LOG_ERROR(\"Timer creation failed, error code: %lu\", timerError);\n MessageBox(NULL, \"Timer Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Timer set successfully\");\n\n // Handle startup mode\n LOG_INFO(\"Handling startup mode: %s\", CLOCK_STARTUP_MODE);\n HandleStartupMode(hwnd);\n \n // Automatic update check code has been removed\n\n // Message loop\n LOG_INFO(\"Entering main message loop\");\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0) > 0) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n // Clean up resources\n LOG_INFO(\"Program preparing to exit, starting resource cleanup\");\n \n // Clean up update check thread resources\n LOG_INFO(\"Preparing to clean up update check thread resources\");\n CleanupUpdateThread();\n \n CloseHandle(hMutex);\n CoUninitialize();\n \n // Close log system\n CleanupLogSystem();\n \n return (int)msg.wParam;\n // If execution reaches here, the program has exited normally\n}\n", "middle_code": "static void HandleStartupMode(HWND hwnd) {\n LOG_INFO(\"Setting startup mode: %s\", CLOCK_STARTUP_MODE);\n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n LOG_INFO(\"Setting to count-up mode\");\n CLOCK_COUNT_UP = TRUE;\n elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n LOG_INFO(\"Setting to hidden mode, window will be hidden\");\n ShowWindow(hwnd, SW_HIDE);\n KillTimer(hwnd, 1);\n elapsed_time = CLOCK_TOTAL_TIME;\n CLOCK_IS_PAUSED = TRUE;\n message_shown = TRUE;\n countdown_message_shown = TRUE;\n countup_message_shown = TRUE;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n LOG_INFO(\"Setting to show current time mode\");\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_LAST_TIME_UPDATE = 0;\n } else {\n LOG_INFO(\"Using default countdown mode\");\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/Catime/src/shortcut_checker.c", "/**\n * @file shortcut_checker.c\n * @brief Implementation of desktop shortcut detection and creation\n *\n * Detects if the program is installed from the App Store or WinGet,\n * and creates a desktop shortcut when necessary.\n */\n\n#include \"../include/shortcut_checker.h\"\n#include \"../include/config.h\"\n#include \"../include/log.h\" // Include log header\n#include // For printf debug output\n#include \n#include \n#include \n#include \n#include \n#include \n\n// Import required COM interfaces\n#include \n\n// We don't need to manually define IID_IShellLinkA, it's already defined in system headers\n\n/**\n * @brief Check if a string starts with a specified prefix\n * \n * @param str The string to check\n * @param prefix The prefix string\n * @return bool true if the string starts with the specified prefix, false otherwise\n */\nstatic bool StartsWith(const char* str, const char* prefix) {\n size_t prefix_len = strlen(prefix);\n size_t str_len = strlen(str);\n \n if (str_len < prefix_len) {\n return false;\n }\n \n return strncmp(str, prefix, prefix_len) == 0;\n}\n\n/**\n * @brief Check if a string contains a specified substring\n * \n * @param str The string to check\n * @param substring The substring\n * @return bool true if the string contains the specified substring, false otherwise\n */\nstatic bool Contains(const char* str, const char* substring) {\n return strstr(str, substring) != NULL;\n}\n\n/**\n * @brief Check if the program is installed from the App Store or WinGet\n * \n * @param exe_path Buffer to output the program path\n * @param path_size Buffer size\n * @return bool true if installed from the App Store or WinGet, false otherwise\n */\nstatic bool IsStoreOrWingetInstall(char* exe_path, size_t path_size) {\n // Get program path\n if (GetModuleFileNameA(NULL, exe_path, path_size) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n return false;\n }\n \n LOG_DEBUG(\"Checking program path: %s\", exe_path);\n \n // Check if it's an App Store installation path (starts with C:\\Program Files\\WindowsApps)\n if (StartsWith(exe_path, \"C:\\\\Program Files\\\\WindowsApps\")) {\n LOG_DEBUG(\"Detected App Store installation path\");\n return true;\n }\n \n // Check if it's a WinGet installation path\n // 1. Regular path containing \\AppData\\Local\\Microsoft\\WinGet\\Packages\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\WinGet\\\\Packages\")) {\n LOG_DEBUG(\"Detected WinGet installation path (regular)\");\n return true;\n }\n \n // 2. Possible custom WinGet installation path (if in C:\\Users\\username\\AppData\\Local\\Microsoft\\*)\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\\") && Contains(exe_path, \"WinGet\")) {\n LOG_DEBUG(\"Detected possible WinGet installation path (custom)\");\n return true;\n }\n \n // Force test: When the path contains specific strings, consider it a path that needs to create shortcuts\n // This test path matches the installation path seen in user logs\n if (Contains(exe_path, \"\\\\WinGet\\\\catime.exe\")) {\n LOG_DEBUG(\"Detected specific WinGet installation path\");\n return true;\n }\n \n LOG_DEBUG(\"Not a Store or WinGet installation path\");\n return false;\n}\n\n/**\n * @brief Check if the desktop already has a shortcut and if the shortcut points to the current program\n * \n * @param exe_path Program path\n * @param shortcut_path_out If a shortcut is found, output the shortcut path\n * @param shortcut_path_size Shortcut path buffer size\n * @param target_path_out If a shortcut is found, output the shortcut target path\n * @param target_path_size Target path buffer size\n * @return int 0=shortcut not found, 1=shortcut found and points to current program, 2=shortcut found but points to another path\n */\nstatic int CheckShortcutTarget(const char* exe_path, char* shortcut_path_out, size_t shortcut_path_size, \n char* target_path_out, size_t target_path_size) {\n char desktop_path[MAX_PATH];\n char public_desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char link_target[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n WIN32_FIND_DATAA find_data;\n int result = 0;\n \n // Get user desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n LOG_DEBUG(\"User desktop path: %s\", desktop_path);\n \n // Get public desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_COMMON_DESKTOPDIRECTORY, NULL, 0, public_desktop_path);\n if (FAILED(hr)) {\n LOG_WARNING(\"Failed to get public desktop path, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_DEBUG(\"Public desktop path: %s\", public_desktop_path);\n }\n \n // First check user desktop - build complete shortcut path (Catime.lnk)\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n LOG_DEBUG(\"Checking user desktop shortcut: %s\", shortcut_path);\n \n // Check if the user desktop shortcut file exists\n bool file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n \n // If not found on user desktop, check public desktop\n if (!file_exists && SUCCEEDED(hr)) {\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", public_desktop_path);\n LOG_DEBUG(\"Checking public desktop shortcut: %s\", shortcut_path);\n \n file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n }\n \n // If no shortcut file is found, return 0 directly\n if (!file_exists) {\n LOG_DEBUG(\"No shortcut files found\");\n return 0;\n }\n \n // Save the found shortcut path to the output parameter\n if (shortcut_path_out && shortcut_path_size > 0) {\n strncpy(shortcut_path_out, shortcut_path, shortcut_path_size);\n shortcut_path_out[shortcut_path_size - 1] = '\\0';\n }\n \n // Found shortcut file, get its target\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Convert to wide character\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_ACP, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Load shortcut\n hr = ppf->lpVtbl->Load(ppf, wide_path, STGM_READ);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to load shortcut, hr=0x%08X\", (unsigned int)hr);\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Get shortcut target path\n hr = psl->lpVtbl->GetPath(psl, link_target, MAX_PATH, &find_data, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get shortcut target path, hr=0x%08X\", (unsigned int)hr);\n result = 0;\n } else {\n LOG_DEBUG(\"Shortcut target path: %s\", link_target);\n LOG_DEBUG(\"Current program path: %s\", exe_path);\n \n // Save target path to output parameter\n if (target_path_out && target_path_size > 0) {\n strncpy(target_path_out, link_target, target_path_size);\n target_path_out[target_path_size - 1] = '\\0';\n }\n \n // Check if the shortcut points to the current program\n if (_stricmp(link_target, exe_path) == 0) {\n LOG_DEBUG(\"Shortcut points to current program\");\n result = 1;\n } else {\n LOG_DEBUG(\"Shortcut points to another path\");\n result = 2;\n }\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return result;\n}\n\n/**\n * @brief Create or update desktop shortcut\n * \n * @param exe_path Program path\n * @param existing_shortcut_path Existing shortcut path, create new one if NULL\n * @return bool true for successful creation/update, false for failure\n */\nstatic bool CreateOrUpdateDesktopShortcut(const char* exe_path, const char* existing_shortcut_path) {\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char icon_path[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n bool success = false;\n \n // If an existing shortcut path is provided, use it; otherwise create a new shortcut on the user's desktop\n if (existing_shortcut_path && *existing_shortcut_path) {\n LOG_INFO(\"Starting to update desktop shortcut: %s pointing to: %s\", existing_shortcut_path, exe_path);\n strcpy(shortcut_path, existing_shortcut_path);\n } else {\n LOG_INFO(\"Starting to create desktop shortcut, program path: %s\", exe_path);\n \n // Get desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n LOG_DEBUG(\"Desktop path: %s\", desktop_path);\n \n // Build complete shortcut path\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n }\n \n LOG_DEBUG(\"Shortcut path: %s\", shortcut_path);\n \n // Use program path as icon path\n strcpy(icon_path, exe_path);\n \n // Create IShellLink interface\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n \n // Set target path\n hr = psl->lpVtbl->SetPath(psl, exe_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set shortcut target path, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Set working directory (use the directory where the executable is located)\n char work_dir[MAX_PATH];\n strcpy(work_dir, exe_path);\n char* last_slash = strrchr(work_dir, '\\\\');\n if (last_slash) {\n *last_slash = '\\0';\n }\n LOG_DEBUG(\"Working directory: %s\", work_dir);\n \n hr = psl->lpVtbl->SetWorkingDirectory(psl, work_dir);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set working directory, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set icon\n hr = psl->lpVtbl->SetIconLocation(psl, icon_path, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set icon, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set description\n hr = psl->lpVtbl->SetDescription(psl, \"A very useful timer (Pomodoro Clock)\");\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set description, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set window style (normal window)\n psl->lpVtbl->SetShowCmd(psl, SW_SHOWNORMAL);\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Convert to wide characters\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Save shortcut\n hr = ppf->lpVtbl->Save(ppf, wide_path, TRUE);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to save shortcut, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_INFO(\"Desktop shortcut %s successful: %s\", existing_shortcut_path ? \"update\" : \"creation\", shortcut_path);\n success = true;\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return success;\n}\n\n/**\n * @brief Check and create desktop shortcut\n * \n * All installation types will check if the desktop shortcut exists and points to the current program.\n * If the shortcut already exists but points to another program, it will be updated to the current path.\n * But only versions installed from the Windows App Store or WinGet will create a new shortcut.\n * If SHORTCUT_CHECK_DONE=TRUE is marked in the configuration file, no new shortcut will be created even if the shortcut is deleted.\n * \n * @return int 0 means no need to create/update or create/update successful, 1 means failure\n */\nint CheckAndCreateShortcut(void) {\n char exe_path[MAX_PATH];\n char config_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char target_path[MAX_PATH];\n bool shortcut_check_done = false;\n bool isStoreInstall = false;\n \n // Initialize COM library, needed for creating shortcuts later\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM library initialization failed, hr=0x%08X\", (unsigned int)hr);\n return 1;\n }\n \n LOG_DEBUG(\"Starting shortcut check\");\n \n // Read the flag from the configuration file to determine if it has been checked\n GetConfigPath(config_path, MAX_PATH);\n shortcut_check_done = IsShortcutCheckDone();\n \n LOG_DEBUG(\"Configuration path: %s, already checked: %d\", config_path, shortcut_check_done);\n \n // Get current program path\n if (GetModuleFileNameA(NULL, exe_path, MAX_PATH) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n CoUninitialize();\n return 1;\n }\n LOG_DEBUG(\"Program path: %s\", exe_path);\n \n // Check if it's an App Store or WinGet installation (only affects the behavior of creating new shortcuts)\n isStoreInstall = IsStoreOrWingetInstall(exe_path, MAX_PATH);\n LOG_DEBUG(\"Is Store/WinGet installation: %d\", isStoreInstall);\n \n // Check if the shortcut exists and points to the current program\n // Return value: 0=does not exist, 1=exists and points to the current program, 2=exists but points to another path\n int shortcut_status = CheckShortcutTarget(exe_path, shortcut_path, MAX_PATH, target_path, MAX_PATH);\n \n if (shortcut_status == 0) {\n // Shortcut does not exist\n if (shortcut_check_done) {\n // If the configuration has already been marked as checked, don't create it even if there's no shortcut\n LOG_INFO(\"No shortcut found on desktop, but configuration marked as checked, not creating\");\n CoUninitialize();\n return 0;\n } else if (isStoreInstall) {\n // Only first-run Store or WinGet installations create shortcuts\n LOG_INFO(\"No shortcut found on desktop, first run of Store/WinGet installation, starting to create\");\n bool success = CreateOrUpdateDesktopShortcut(exe_path, NULL);\n \n // Mark as checked, regardless of whether creation was successful\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return success ? 0 : 1;\n } else {\n LOG_INFO(\"No shortcut found on desktop, not a Store/WinGet installation, not creating shortcut\");\n \n // Mark as checked\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return 0;\n }\n } else if (shortcut_status == 1) {\n // Shortcut exists and points to the current program, no action needed\n LOG_INFO(\"Desktop shortcut already exists and points to the current program\");\n \n // Mark as checked\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return 0;\n } else if (shortcut_status == 2) {\n // Shortcut exists but points to another program, any installation method will update it\n LOG_INFO(\"Desktop shortcut points to another path: %s, will update to: %s\", target_path, exe_path);\n bool success = CreateOrUpdateDesktopShortcut(exe_path, shortcut_path);\n \n // Mark as checked, regardless of whether the update was successful\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return success ? 0 : 1;\n }\n \n // Should not reach here\n LOG_ERROR(\"Unknown shortcut check status\");\n CoUninitialize();\n return 1;\n} "], ["/Catime/src/window_procedure.c", "/**\n * @file window_procedure.c\n * @brief Window message processing implementation\n * \n * This file implements the message processing callback function for the application's main window,\n * handling all message events for the window.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\" \n#include \"../include/window.h\" \n#include \"../include/startup.h\" \n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/window_events.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/drawing.h\"\n#include \"../include/timer_events.h\"\n#include \"../include/tray_events.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/notification.h\" // Add notification header\n\n// Variables imported from main.c\nextern char inputText[256];\nextern int elapsed_time;\nextern int message_shown;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void PauseMediaPlayback(void);\n\n// Add these external variable declarations at the beginning of the file\nextern int POMODORO_TIMES[10]; // Pomodoro time array\nextern int POMODORO_TIMES_COUNT; // Number of pomodoro time options\nextern int current_pomodoro_time_index; // Current pomodoro time index\nextern int complete_pomodoro_cycles; // Completed pomodoro cycles\n\n// If ShowInputDialog function needs to be declared, add at the beginning\nextern BOOL ShowInputDialog(HWND hwnd, char* text);\n\n// Modify to match the correct function declaration in config.h\nextern void WriteConfigPomodoroTimeOptions(int* times, int count);\n\n// If the function doesn't exist, use an existing similar function\n// For example, modify calls to WriteConfigPomodoroTimeOptions to WriteConfigPomodoroTimes\n\n// Add at the beginning of the file\ntypedef struct {\n const wchar_t* title;\n const wchar_t* prompt;\n const wchar_t* defaultText;\n wchar_t* result;\n size_t maxLen;\n} INPUTBOX_PARAMS;\n\n// Add declaration for ShowPomodoroLoopDialog function at the beginning of the file\nextern void ShowPomodoroLoopDialog(HWND hwndParent);\n\n// Add declaration for OpenUserGuide function\nextern void OpenUserGuide(void);\n\n// Add declaration for OpenSupportPage function\nextern void OpenSupportPage(void);\n\n// Add declaration for OpenFeedbackPage function\nextern void OpenFeedbackPage(void);\n\n// Helper function: Check if a string contains only spaces\nstatic BOOL isAllSpacesOnly(const char* str) {\n for (int i = 0; str[i]; i++) {\n if (!isspace((unsigned char)str[i])) {\n return FALSE;\n }\n }\n return TRUE;\n}\n\n/**\n * @brief Input dialog callback function\n * @param hwndDlg Dialog handle\n * @param uMsg Message\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return Processing result\n */\nINT_PTR CALLBACK InputBoxProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {\n static wchar_t* result;\n static size_t maxLen;\n \n switch (uMsg) {\n case WM_INITDIALOG: {\n // Get passed parameters\n INPUTBOX_PARAMS* params = (INPUTBOX_PARAMS*)lParam;\n result = params->result;\n maxLen = params->maxLen;\n \n // Set dialog title\n SetWindowTextW(hwndDlg, params->title);\n \n // Set prompt message\n SetDlgItemTextW(hwndDlg, IDC_STATIC_PROMPT, params->prompt);\n \n // Set default text\n SetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, params->defaultText);\n \n // Select text\n SendDlgItemMessageW(hwndDlg, IDC_EDIT_INPUT, EM_SETSEL, 0, -1);\n \n // Set focus\n SetFocus(GetDlgItem(hwndDlg, IDC_EDIT_INPUT));\n return FALSE;\n }\n \n case WM_COMMAND:\n switch (LOWORD(wParam)) {\n case IDOK: {\n // Get input text\n GetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, result, (int)maxLen);\n EndDialog(hwndDlg, TRUE);\n return TRUE;\n }\n \n case IDCANCEL:\n // Cancel operation\n EndDialog(hwndDlg, FALSE);\n return TRUE;\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display input dialog\n * @param hwndParent Parent window handle\n * @param title Dialog title\n * @param prompt Prompt message\n * @param defaultText Default text\n * @param result Result buffer\n * @param maxLen Maximum buffer length\n * @return TRUE if successful, FALSE if canceled\n */\nBOOL InputBox(HWND hwndParent, const wchar_t* title, const wchar_t* prompt, \n const wchar_t* defaultText, wchar_t* result, size_t maxLen) {\n // Prepare parameters to pass to dialog\n INPUTBOX_PARAMS params;\n params.title = title;\n params.prompt = prompt;\n params.defaultText = defaultText;\n params.result = result;\n params.maxLen = maxLen;\n \n // Display modal dialog\n return DialogBoxParamW(GetModuleHandle(NULL), \n MAKEINTRESOURCEW(IDD_INPUTBOX), \n hwndParent, \n InputBoxProc, \n (LPARAM)¶ms) == TRUE;\n}\n\nvoid ExitProgram(HWND hwnd) {\n RemoveTrayIcon();\n\n PostQuitMessage(0);\n}\n\n#define HOTKEY_ID_SHOW_TIME 100 // Hotkey ID to show current time\n#define HOTKEY_ID_COUNT_UP 101 // Hotkey ID for count up timer\n#define HOTKEY_ID_COUNTDOWN 102 // Hotkey ID for countdown timer\n#define HOTKEY_ID_QUICK_COUNTDOWN1 103 // Hotkey ID for quick countdown 1\n#define HOTKEY_ID_QUICK_COUNTDOWN2 104 // Hotkey ID for quick countdown 2\n#define HOTKEY_ID_QUICK_COUNTDOWN3 105 // Hotkey ID for quick countdown 3\n#define HOTKEY_ID_POMODORO 106 // Hotkey ID for pomodoro timer\n#define HOTKEY_ID_TOGGLE_VISIBILITY 107 // Hotkey ID for hide/show\n#define HOTKEY_ID_EDIT_MODE 108 // Hotkey ID for edit mode\n#define HOTKEY_ID_PAUSE_RESUME 109 // Hotkey ID for pause/resume\n#define HOTKEY_ID_RESTART_TIMER 110 // Hotkey ID for restart timer\n#define HOTKEY_ID_CUSTOM_COUNTDOWN 111 // Hotkey ID for custom countdown\n\n/**\n * @brief Register global hotkeys\n * @param hwnd Window handle\n * \n * Reads and registers global hotkey settings from the configuration file for quickly switching between\n * displaying current time, count up timer, and default countdown.\n * If a hotkey is already registered, it will be unregistered before re-registering.\n * If a hotkey cannot be registered (possibly because it's being used by another program),\n * that hotkey setting will be set to none and the configuration file will be updated.\n * \n * @return BOOL Whether at least one hotkey was successfully registered\n */\nBOOL RegisterGlobalHotkeys(HWND hwnd) {\n // First unregister all previously registered hotkeys\n UnregisterGlobalHotkeys(hwnd);\n \n // Use new function to read hotkey configuration\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n BOOL success = FALSE;\n BOOL configChanged = FALSE;\n \n // Register show current time hotkey\n if (showTimeHotkey != 0) {\n BYTE vk = LOBYTE(showTimeHotkey); // Virtual key code\n BYTE mod = HIBYTE(showTimeHotkey); // Modifier keys\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n showTimeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register count up hotkey\n if (countUpHotkey != 0) {\n BYTE vk = LOBYTE(countUpHotkey);\n BYTE mod = HIBYTE(countUpHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNT_UP, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countUpHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register countdown hotkey\n if (countdownHotkey != 0) {\n BYTE vk = LOBYTE(countdownHotkey);\n BYTE mod = HIBYTE(countdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 1 hotkey\n if (quickCountdown1Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown1Hotkey);\n BYTE mod = HIBYTE(quickCountdown1Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown1Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 2 hotkey\n if (quickCountdown2Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown2Hotkey);\n BYTE mod = HIBYTE(quickCountdown2Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown2Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 3 hotkey\n if (quickCountdown3Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown3Hotkey);\n BYTE mod = HIBYTE(quickCountdown3Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown3Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pomodoro hotkey\n if (pomodoroHotkey != 0) {\n BYTE vk = LOBYTE(pomodoroHotkey);\n BYTE mod = HIBYTE(pomodoroHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_POMODORO, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pomodoroHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register hide/show window hotkey\n if (toggleVisibilityHotkey != 0) {\n BYTE vk = LOBYTE(toggleVisibilityHotkey);\n BYTE mod = HIBYTE(toggleVisibilityHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n toggleVisibilityHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register edit mode hotkey\n if (editModeHotkey != 0) {\n BYTE vk = LOBYTE(editModeHotkey);\n BYTE mod = HIBYTE(editModeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n editModeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pause/resume hotkey\n if (pauseResumeHotkey != 0) {\n BYTE vk = LOBYTE(pauseResumeHotkey);\n BYTE mod = HIBYTE(pauseResumeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pauseResumeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register restart timer hotkey\n if (restartTimerHotkey != 0) {\n BYTE vk = LOBYTE(restartTimerHotkey);\n BYTE mod = HIBYTE(restartTimerHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n restartTimerHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // If any hotkey registration failed, update config file\n if (configChanged) {\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n \n // Check if custom countdown hotkey was cleared, if so, update config\n if (customCountdownHotkey == 0) {\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", \"None\");\n }\n }\n \n // Added after reading hotkey configuration\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Added after registering countdown hotkey\n // Register custom countdown hotkey\n if (customCountdownHotkey != 0) {\n BYTE vk = LOBYTE(customCountdownHotkey);\n BYTE mod = HIBYTE(customCountdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n customCountdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n return success;\n}\n\n/**\n * @brief Unregister global hotkeys\n * @param hwnd Window handle\n * \n * Unregister all previously registered global hotkeys.\n */\nvoid UnregisterGlobalHotkeys(HWND hwnd) {\n // Unregister all previously registered hotkeys\n UnregisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNT_UP);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3);\n UnregisterHotKey(hwnd, HOTKEY_ID_POMODORO);\n UnregisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY);\n UnregisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE);\n UnregisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME);\n UnregisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER);\n UnregisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN);\n}\n\n/**\n * @brief Main window message processing callback function\n * @param hwnd Window handle\n * @param msg Message type\n * @param wp Message parameter (specific meaning depends on message type)\n * @param lp Message parameter (specific meaning depends on message type)\n * @return LRESULT Message processing result\n * \n * Handles all message events for the main window, including:\n * - Window creation/destruction\n * - Mouse events (dragging, wheel scaling)\n * - Timer events\n * - System tray interaction\n * - Drawing events\n * - Menu command processing\n */\nLRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)\n{\n static char time_text[50];\n UINT uID;\n UINT uMouseMsg;\n\n // Check if this is a TaskbarCreated message\n // TaskbarCreated is a system message broadcasted when Windows Explorer restarts\n // At this time all tray icons are destroyed and need to be recreated by applications\n // Handling this message solves the issue of the tray icon disappearing while the program is still running\n if (msg == WM_TASKBARCREATED) {\n // Explorer has restarted, need to recreate the tray icon\n RecreateTaskbarIcon(hwnd, GetModuleHandle(NULL));\n return 0;\n }\n\n switch(msg)\n {\n case WM_CREATE: {\n // Register global hotkeys when window is created\n RegisterGlobalHotkeys(hwnd);\n HandleWindowCreate(hwnd);\n break;\n }\n\n case WM_SETCURSOR: {\n // When in edit mode, always use default arrow cursor\n if (CLOCK_EDIT_MODE && LOWORD(lp) == HTCLIENT) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE; // Indicates we've handled this message\n }\n \n // Also use default arrow cursor when handling tray icon operations\n if (LOWORD(lp) == HTCLIENT || msg == CLOCK_WM_TRAYICON) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE;\n }\n break;\n }\n\n case WM_LBUTTONDOWN: {\n StartDragWindow(hwnd);\n break;\n }\n\n case WM_LBUTTONUP: {\n EndDragWindow(hwnd);\n break;\n }\n\n case WM_MOUSEWHEEL: {\n int delta = GET_WHEEL_DELTA_WPARAM(wp);\n HandleScaleWindow(hwnd, delta);\n break;\n }\n\n case WM_MOUSEMOVE: {\n if (HandleDragWindow(hwnd)) {\n return 0;\n }\n break;\n }\n\n case WM_PAINT: {\n PAINTSTRUCT ps;\n BeginPaint(hwnd, &ps);\n HandleWindowPaint(hwnd, &ps);\n EndPaint(hwnd, &ps);\n break;\n }\n case WM_TIMER: {\n if (HandleTimerEvent(hwnd, wp)) {\n break;\n }\n break;\n }\n case WM_DESTROY: {\n // Unregister global hotkeys when window is destroyed\n UnregisterGlobalHotkeys(hwnd);\n HandleWindowDestroy(hwnd);\n return 0;\n }\n case CLOCK_WM_TRAYICON: {\n HandleTrayIconMessage(hwnd, (UINT)wp, (UINT)lp);\n break;\n }\n case WM_COMMAND: {\n // Handle preset color options (ID: 201 ~ 201+COLOR_OPTIONS_COUNT-1)\n if (LOWORD(wp) >= 201 && LOWORD(wp) < 201 + COLOR_OPTIONS_COUNT) {\n int colorIndex = LOWORD(wp) - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n // Update current color\n strncpy(CLOCK_TEXT_COLOR, COLOR_OPTIONS[colorIndex].hexColor, \n sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n \n // Write to config file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n \n // Redraw window to show new color\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n WORD cmd = LOWORD(wp);\n switch (cmd) {\n case 101: { \n if (CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_LAST_TIME_UPDATE = 0;\n KillTimer(hwnd, 1);\n }\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n // Handle quick time options (102-102+MAX_TIME_OPTIONS)\n case 102: case 103: case 104: case 105: case 106:\n case 107: case 108: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n int index = cmd - 102;\n if (index >= 0 && index < time_options_count) {\n int minutes = time_options[index];\n if (minutes > 0) {\n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = minutes * 60; // Convert to seconds\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n break;\n }\n // Handle exit option\n case 109: {\n ExitProgram(hwnd);\n break;\n }\n case CLOCK_IDC_MODIFY_TIME_OPTIONS: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_SHORTCUT_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_SHORTCUT_DIALOG);\n\n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n // If input is empty or contains only spaces, exit the loop\n if (inputText[0] == '\\0' || isAllSpaces) {\n break;\n }\n\n char* token = strtok(inputText, \" \");\n char options[256] = {0};\n int valid = 1;\n int count = 0;\n \n while (token && count < MAX_TIME_OPTIONS) {\n int num = atoi(token);\n if (num <= 0) {\n valid = 0;\n break;\n }\n \n if (count > 0) {\n strcat(options, \",\");\n }\n strcat(options, token);\n count++;\n token = strtok(NULL, \" \");\n }\n\n if (valid && count > 0) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigTimeOptions(options);\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd,\n GetLocalizedString(\n L\"请输入用空格分隔的数字\\n\"\n L\"例如: 25 10 5\",\n L\"Enter numbers separated by spaces\\n\"\n L\"Example: 25 10 5\"),\n GetLocalizedString(L\"无效输入\", L\"Invalid Input\"), \n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_MODIFY_DEFAULT_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_STARTUP_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_STARTUP_DIALOG);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case 200: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // First, stop all timers to ensure no timer events will be processed\n KillTimer(hwnd, 1);\n \n // Unregister all global hotkeys to ensure they don't remain active after reset\n UnregisterGlobalHotkeys(hwnd);\n \n // Fully reset timer state - critical part\n // Import all timer state variables that need to be reset\n extern int elapsed_time; // from main.c\n extern int countdown_elapsed_time; // from timer.c\n extern int countup_elapsed_time; // from timer.c\n extern BOOL message_shown; // from main.c \n extern BOOL countdown_message_shown;// from timer.c\n extern BOOL countup_message_shown; // from timer.c\n \n // Import high-precision timer initialization function from timer.c\n extern BOOL InitializeHighPrecisionTimer(void);\n extern void ResetTimer(void); // Use a dedicated reset function\n extern void ReadNotificationMessagesConfig(void); // Read notification message configuration\n \n // Reset all timer state variables - order matters!\n CLOCK_TOTAL_TIME = 25 * 60; // 1. First set total time to 25 minutes\n elapsed_time = 0; // 2. Reset elapsed_time in main.c\n countdown_elapsed_time = 0; // 3. Reset countdown_elapsed_time in timer.c\n countup_elapsed_time = 0; // 4. Reset countup_elapsed_time in timer.c\n message_shown = FALSE; // 5. Reset message status\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set timer state to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Call the dedicated timer reset function - this is crucial!\n // This function reinitializes the high-precision timer and resets all timing states\n ResetTimer();\n \n // Reset UI state\n CLOCK_EDIT_MODE = FALSE;\n SetClickThrough(hwnd, TRUE);\n SendMessage(hwnd, WM_SETREDRAW, FALSE, 0);\n \n // Reset file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n \n // Default language initialization\n AppLanguage defaultLanguage;\n LANGID langId = GetUserDefaultUILanguage();\n WORD primaryLangId = PRIMARYLANGID(langId);\n WORD subLangId = SUBLANGID(langId);\n \n switch (primaryLangId) {\n case LANG_CHINESE:\n defaultLanguage = (subLangId == SUBLANG_CHINESE_SIMPLIFIED) ? \n APP_LANG_CHINESE_SIMP : APP_LANG_CHINESE_TRAD;\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n break;\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n break;\n }\n \n if (CURRENT_LANGUAGE != defaultLanguage) {\n CURRENT_LANGUAGE = defaultLanguage;\n }\n \n // Delete and recreate the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure the file is closed and deleted\n FILE* test = fopen(config_path, \"r\");\n if (test) {\n fclose(test);\n remove(config_path);\n }\n \n // Recreate default configuration\n CreateDefaultConfig(config_path);\n \n // Reread the configuration\n ReadConfig();\n \n // Ensure notification messages are reread\n ReadNotificationMessagesConfig();\n \n // Restore default font\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0) { \n LoadFontFromResource(hInstance, fontResources[i].resourceId);\n break;\n }\n }\n \n // Reset window scale\n CLOCK_WINDOW_SCALE = 1.0f;\n CLOCK_FONT_SCALE_FACTOR = 1.0f;\n \n // Recalculate window size\n HDC hdc = GetDC(hwnd);\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE, \n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, FONT_INTERNAL_NAME\n );\n HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);\n \n char time_text[50];\n FormatTime(CLOCK_TOTAL_TIME, time_text);\n SIZE textSize;\n GetTextExtentPoint32(hdc, time_text, strlen(time_text), &textSize);\n \n SelectObject(hdc, hOldFont);\n DeleteObject(hFont);\n ReleaseDC(hwnd, hdc);\n \n // Set default scale based on screen height\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n float defaultScale = (screenHeight * 0.03f) / 20.0f;\n CLOCK_WINDOW_SCALE = defaultScale;\n CLOCK_FONT_SCALE_FACTOR = defaultScale;\n \n // Reset window position\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n textSize.cx * defaultScale, textSize.cy * defaultScale,\n SWP_NOZORDER | SWP_NOACTIVATE\n );\n \n // Ensure window is visible\n ShowWindow(hwnd, SW_SHOW);\n \n // Restart the timer - ensure it's started after all states are reset\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n SendMessage(hwnd, WM_SETREDRAW, TRUE, 0);\n RedrawWindow(hwnd, NULL, NULL, \n RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);\n \n // Reregister default hotkeys\n RegisterGlobalHotkeys(hwnd);\n \n break;\n }\n case CLOCK_IDM_TIMER_PAUSE_RESUME: {\n PauseResumeTimer(hwnd);\n break;\n }\n case CLOCK_IDM_TIMER_RESTART: {\n // Close all notification windows\n CloseAllNotifications();\n RestartTimer(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE: {\n SetLanguage(APP_LANG_CHINESE_SIMP);\n WriteConfigLanguage(APP_LANG_CHINESE_SIMP);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE_TRAD: {\n SetLanguage(APP_LANG_CHINESE_TRAD);\n WriteConfigLanguage(APP_LANG_CHINESE_TRAD);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_ENGLISH: {\n SetLanguage(APP_LANG_ENGLISH);\n WriteConfigLanguage(APP_LANG_ENGLISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_SPANISH: {\n SetLanguage(APP_LANG_SPANISH);\n WriteConfigLanguage(APP_LANG_SPANISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_FRENCH: {\n SetLanguage(APP_LANG_FRENCH);\n WriteConfigLanguage(APP_LANG_FRENCH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_GERMAN: {\n SetLanguage(APP_LANG_GERMAN);\n WriteConfigLanguage(APP_LANG_GERMAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_RUSSIAN: {\n SetLanguage(APP_LANG_RUSSIAN);\n WriteConfigLanguage(APP_LANG_RUSSIAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_PORTUGUESE: {\n SetLanguage(APP_LANG_PORTUGUESE);\n WriteConfigLanguage(APP_LANG_PORTUGUESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_JAPANESE: {\n SetLanguage(APP_LANG_JAPANESE);\n WriteConfigLanguage(APP_LANG_JAPANESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_KOREAN: {\n SetLanguage(APP_LANG_KOREAN);\n WriteConfigLanguage(APP_LANG_KOREAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_ABOUT:\n ShowAboutDialog(hwnd);\n return 0;\n case CLOCK_IDM_TOPMOST: {\n // Toggle the topmost state in configuration\n BOOL newTopmost = !CLOCK_WINDOW_TOPMOST;\n \n // If in edit mode, just update the stored state but don't apply it yet\n if (CLOCK_EDIT_MODE) {\n // Update the configuration and saved state only\n PREVIOUS_TOPMOST_STATE = newTopmost;\n CLOCK_WINDOW_TOPMOST = newTopmost;\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n } else {\n // Not in edit mode, apply it immediately\n SetWindowTopmost(hwnd, newTopmost);\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n }\n break;\n }\n case CLOCK_IDM_COUNTDOWN_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = FALSE; // Switch to countdown mode\n }\n \n // Reset the countdown timer\n extern void ResetTimer(void);\n ResetTimer();\n \n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDC_EDIT_MODE: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n } else {\n StartEditMode(hwnd);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n case CLOCK_IDC_CUSTOMIZE_LEFT: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n char hex_color[10];\n snprintf(hex_color, sizeof(hex_color), \"#%02X%02X%02X\", \n GetRValue(color), GetGValue(color), GetBValue(color));\n WriteConfigColor(hex_color);\n ReadConfig();\n }\n break;\n }\n case CLOCK_IDC_FONT_RECMONO: {\n WriteConfigFont(\"RecMonoCasual Nerd Font Mono Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DEPARTURE: {\n WriteConfigFont(\"DepartureMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_TERMINESS: {\n WriteConfigFont(\"Terminess Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PINYON_SCRIPT: {\n WriteConfigFont(\"Pinyon Script Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ARBUTUS: {\n WriteConfigFont(\"Arbutus Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_BERKSHIRE: {\n WriteConfigFont(\"Berkshire Swash Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CAVEAT: {\n WriteConfigFont(\"Caveat Brush Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CREEPSTER: {\n WriteConfigFont(\"Creepster Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DOTO: { \n WriteConfigFont(\"Doto ExtraBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FOLDIT: {\n WriteConfigFont(\"Foldit SemiBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FREDERICKA: {\n WriteConfigFont(\"Fredericka the Great Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FRIJOLE: {\n WriteConfigFont(\"Frijole Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_GWENDOLYN: {\n WriteConfigFont(\"Gwendolyn Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_HANDJET: {\n WriteConfigFont(\"Handjet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_INKNUT: {\n WriteConfigFont(\"Inknut Antiqua Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARD: {\n WriteConfigFont(\"Jacquard 12 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARDA: {\n WriteConfigFont(\"Jacquarda Bastarda 9 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KAVOON: {\n WriteConfigFont(\"Kavoon Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE: {\n WriteConfigFont(\"Kumar One Outline Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE: {\n WriteConfigFont(\"Kumar One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LAKKI_REDDY: {\n WriteConfigFont(\"Lakki Reddy Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LICORICE: {\n WriteConfigFont(\"Licorice Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MA_SHAN_ZHENG: {\n WriteConfigFont(\"Ma Shan Zheng Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MOIRAI_ONE: {\n WriteConfigFont(\"Moirai One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MYSTERY_QUEST: {\n WriteConfigFont(\"Mystery Quest Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_NOTO_NASTALIQ: {\n WriteConfigFont(\"Noto Nastaliq Urdu Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIEDRA: {\n WriteConfigFont(\"Piedra Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIXELIFY: {\n WriteConfigFont(\"Pixelify Sans Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PRESS_START: {\n WriteConfigFont(\"Press Start 2P Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BUBBLES: {\n WriteConfigFont(\"Rubik Bubbles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BURNED: {\n WriteConfigFont(\"Rubik Burned Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_GLITCH: {\n WriteConfigFont(\"Rubik Glitch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_MARKER_HATCH: {\n WriteConfigFont(\"Rubik Marker Hatch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_PUDDLES: {\n WriteConfigFont(\"Rubik Puddles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_VINYL: {\n WriteConfigFont(\"Rubik Vinyl Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_WET_PAINT: {\n WriteConfigFont(\"Rubik Wet Paint Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUGE_BOOGIE: {\n WriteConfigFont(\"Ruge Boogie Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SEVILLANA: {\n WriteConfigFont(\"Sevillana Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SILKSCREEN: {\n WriteConfigFont(\"Silkscreen Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_STICK: {\n WriteConfigFont(\"Stick Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_UNDERDOG: {\n WriteConfigFont(\"Underdog Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_WALLPOET: {\n WriteConfigFont(\"Wallpoet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_YESTERYEAR: {\n WriteConfigFont(\"Yesteryear Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ZCOOL_KUAILE: {\n WriteConfigFont(\"ZCOOL KuaiLe Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PROFONT: {\n WriteConfigFont(\"ProFont IIx Nerd Font Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DADDYTIME: {\n WriteConfigFont(\"DaddyTimeMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDM_SHOW_CURRENT_TIME: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_SHOW_CURRENT_TIME = !CLOCK_SHOW_CURRENT_TIME;\n if (CLOCK_SHOW_CURRENT_TIME) {\n ShowWindow(hwnd, SW_SHOW); \n \n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1); \n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0; // Ensure total time is reset\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n SetTimer(hwnd, 1, 100, NULL); // Reduce interval to 100ms for higher refresh rate\n } else {\n KillTimer(hwnd, 1); \n // When canceling showing current time, fully reset state instead of restoring previous state\n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0;\n message_shown = 0; // Reset message shown state\n // Set timer with longer interval because second-level updates are no longer needed\n SetTimer(hwnd, 1, 1000, NULL); \n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_24HOUR_FORMAT: { \n CLOCK_USE_24HOUR = !CLOCK_USE_24HOUR;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_SHOW_SECONDS: { \n CLOCK_SHOW_SECONDS = !CLOCK_SHOW_SECONDS;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_RECENT_FILE_1:\n case CLOCK_IDM_RECENT_FILE_2:\n case CLOCK_IDM_RECENT_FILE_3:\n case CLOCK_IDM_RECENT_FILE_4:\n case CLOCK_IDM_RECENT_FILE_5: {\n int index = cmd - CLOCK_IDM_RECENT_FILE_1;\n if (index < CLOCK_RECENT_FILES_COUNT) {\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[index].path, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(CLOCK_RECENT_FILES[index].path);\n \n // Step 2: Update the recent files list (move this file to the top)\n SaveRecentFile(CLOCK_RECENT_FILES[index].path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n \n // Clear invalid file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n \n // Remove this file from the recent files list\n for (int i = index; i < CLOCK_RECENT_FILES_COUNT - 1; i++) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i + 1];\n }\n CLOCK_RECENT_FILES_COUNT--;\n \n // Update recent files list in the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n }\n }\n break;\n }\n case CLOCK_IDM_BROWSE_FILE: {\n wchar_t szFile[MAX_PATH] = {0};\n \n OPENFILENAMEW ofn = {0};\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile) / sizeof(wchar_t);\n ofn.lpstrFilter = L\"所有文件\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n \n if (GetOpenFileNameW(&ofn)) {\n // Convert wide character path to UTF-8 to save in the configuration file\n char utf8Path[MAX_PATH * 3] = {0}; // Larger buffer to accommodate UTF-8 encoding\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n \n if (GetFileAttributesW(szFile) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case CLOCK_IDC_TIMEOUT_BROWSE: {\n OPENFILENAMEW ofn;\n wchar_t szFile[MAX_PATH] = L\"\";\n \n ZeroMemory(&ofn, sizeof(ofn));\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile);\n ofn.lpstrFilter = L\"All Files (*.*)\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n\n if (GetOpenFileNameW(&ofn)) {\n char utf8Path[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, \n utf8Path, \n sizeof(utf8Path), \n NULL, NULL);\n \n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n }\n break;\n }\n case CLOCK_IDM_COUNT_UP: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_COUNT_UP = !CLOCK_COUNT_UP;\n if (CLOCK_COUNT_UP) {\n ShowWindow(hwnd, SW_SHOW);\n \n elapsed_time = 0;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (!CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = TRUE;\n \n // Ensure the timer starts from 0 every time it switches to count-up mode\n countup_elapsed_time = 0;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n } else {\n // Already in count-up mode, so toggle pause/run state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n // Reset the count-up counter\n extern void ResetTimer(void);\n ResetTimer();\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDC_SET_COUNTDOWN_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n \n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n \n CLOCK_DEFAULT_START_TIME = total_seconds;\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_START_SHOW_TIME: {\n WriteConfigStartupMode(\"SHOW_TIME\");\n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_CHECKED);\n break;\n }\n case CLOCK_IDC_START_COUNT_UP: {\n WriteConfigStartupMode(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDC_START_NO_DISPLAY: {\n WriteConfigStartupMode(\"NO_DISPLAY\");\n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n case CLOCK_IDC_AUTO_START: {\n BOOL isEnabled = IsAutoStartEnabled();\n if (isEnabled) {\n if (RemoveShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_UNCHECKED);\n }\n } else {\n if (CreateShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_CHECKED);\n }\n }\n break;\n }\n case CLOCK_IDC_COLOR_VALUE: {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_COLOR_DIALOG), \n hwnd, \n (DLGPROC)ColorDlgProc);\n break;\n }\n case CLOCK_IDC_COLOR_PANEL: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case CLOCK_IDM_POMODORO_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n if (!IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_SHOW);\n }\n \n // Reset timer state\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // Set work time\n CLOCK_TOTAL_TIME = POMODORO_WORK_TIME;\n \n // Initialize Pomodoro phase\n extern void InitializePomodoro(void);\n InitializePomodoro();\n \n // Save original timeout action\n TimeoutActionType originalAction = CLOCK_TIMEOUT_ACTION;\n \n // Force set to show message\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n \n // Start the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Reset message state\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_POMODORO_WORK:\n case CLOCK_IDM_POMODORO_BREAK:\n case CLOCK_IDM_POMODORO_LBREAK:\n // Keep original menu item ID handling\n {\n int selectedIndex = 0;\n if (LOWORD(wp) == CLOCK_IDM_POMODORO_WORK) {\n selectedIndex = 0;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_BREAK) {\n selectedIndex = 1;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_LBREAK) {\n selectedIndex = 2;\n }\n \n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n break;\n\n // Also handle new dynamic ID range\n case 600: case 601: case 602: case 603: case 604:\n case 605: case 606: case 607: case 608: case 609:\n // Handle Pomodoro time setting options (dynamic ID range)\n {\n // Calculate the selected option index\n int selectedIndex = LOWORD(wp) - CLOCK_IDM_POMODORO_TIME_BASE;\n \n if (selectedIndex >= 0 && selectedIndex < POMODORO_TIMES_COUNT) {\n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n }\n break;\n case CLOCK_IDM_POMODORO_LOOP_COUNT:\n ShowPomodoroLoopDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Call ResetTimer to reset the timer state\n extern void ResetTimer(void);\n ResetTimer();\n \n // If currently in Pomodoro mode, reset related states\n if (CLOCK_TOTAL_TIME == POMODORO_WORK_TIME || \n CLOCK_TOTAL_TIME == POMODORO_SHORT_BREAK || \n CLOCK_TOTAL_TIME == POMODORO_LONG_BREAK) {\n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDM_TIMEOUT_SHOW_TIME: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n WriteConfigTimeoutAction(\"SHOW_TIME\");\n break;\n }\n case CLOCK_IDM_TIMEOUT_COUNT_UP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n WriteConfigTimeoutAction(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDM_SHOW_MESSAGE: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n break;\n }\n case CLOCK_IDM_LOCK_SCREEN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n WriteConfigTimeoutAction(\"LOCK\");\n break;\n }\n case CLOCK_IDM_SHUTDOWN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHUTDOWN;\n WriteConfigTimeoutAction(\"SHUTDOWN\");\n break;\n }\n case CLOCK_IDM_RESTART: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RESTART;\n WriteConfigTimeoutAction(\"RESTART\");\n break;\n }\n case CLOCK_IDM_SLEEP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n WriteConfigTimeoutAction(\"SLEEP\");\n break;\n }\n case CLOCK_IDM_RUN_COMMAND: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n WriteConfigTimeoutAction(\"RUN_COMMAND\");\n break;\n }\n case CLOCK_IDM_HTTP_REQUEST: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n WriteConfigTimeoutAction(\"HTTP_REQUEST\");\n break;\n }\n case CLOCK_IDM_CHECK_UPDATE: {\n // Call async update check function - non-silent mode\n CheckForUpdateAsync(hwnd, FALSE);\n break;\n }\n case CLOCK_IDM_OPEN_WEBSITE:\n // Don't set action type immediately, wait for dialog result\n ShowWebsiteDialog(hwnd);\n break;\n \n case CLOCK_IDM_CURRENT_WEBSITE:\n ShowWebsiteDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_COMBINATION:\n ShowPomodoroComboDialog(hwnd);\n break;\n case CLOCK_IDM_NOTIFICATION_CONTENT: {\n ShowNotificationMessagesDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_DISPLAY: {\n ShowNotificationDisplayDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_SETTINGS: {\n ShowNotificationSettingsDialog(hwnd);\n break;\n }\n case CLOCK_IDM_HOTKEY_SETTINGS: {\n ShowHotkeySettingsDialog(hwnd);\n // Register/reregister global hotkeys\n RegisterGlobalHotkeys(hwnd);\n break;\n }\n case CLOCK_IDM_HELP: {\n OpenUserGuide();\n break;\n }\n case CLOCK_IDM_SUPPORT: {\n OpenSupportPage();\n break;\n }\n case CLOCK_IDM_FEEDBACK: {\n OpenFeedbackPage();\n break;\n }\n }\n break;\n\nrefresh_window:\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case WM_WINDOWPOSCHANGED: {\n if (CLOCK_EDIT_MODE) {\n SaveWindowSettings(hwnd);\n }\n break;\n }\n case WM_RBUTTONUP: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_MEASUREITEM:\n {\n LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT)lp;\n if (lpmis->CtlType == ODT_MENU) {\n lpmis->itemHeight = 25;\n lpmis->itemWidth = 100;\n return TRUE;\n }\n return FALSE;\n }\n case WM_DRAWITEM:\n {\n LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT)lp;\n if (lpdis->CtlType == ODT_MENU) {\n int colorIndex = lpdis->itemID - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n const char* hexColor = COLOR_OPTIONS[colorIndex].hexColor;\n int r, g, b;\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n \n HBRUSH hBrush = CreateSolidBrush(RGB(r, g, b));\n HPEN hPen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n \n HGDIOBJ oldBrush = SelectObject(lpdis->hDC, hBrush);\n HGDIOBJ oldPen = SelectObject(lpdis->hDC, hPen);\n \n Rectangle(lpdis->hDC, lpdis->rcItem.left, lpdis->rcItem.top,\n lpdis->rcItem.right, lpdis->rcItem.bottom);\n \n SelectObject(lpdis->hDC, oldPen);\n SelectObject(lpdis->hDC, oldBrush);\n DeleteObject(hPen);\n DeleteObject(hBrush);\n \n if (lpdis->itemState & ODS_SELECTED) {\n DrawFocusRect(lpdis->hDC, &lpdis->rcItem);\n }\n \n return TRUE;\n }\n }\n return FALSE;\n }\n case WM_MENUSELECT: {\n UINT menuItem = LOWORD(wp);\n UINT flags = HIWORD(wp);\n HMENU hMenu = (HMENU)lp;\n\n if (!(flags & MF_POPUP) && hMenu != NULL) {\n int colorIndex = menuItem - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n strncpy(PREVIEW_COLOR, COLOR_OPTIONS[colorIndex].hexColor, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (fontResources[i].menuId == menuItem) {\n strncpy(PREVIEW_FONT_NAME, fontResources[i].fontName, 99);\n PREVIEW_FONT_NAME[99] = '\\0';\n \n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, 99);\n PREVIEW_INTERNAL_NAME[99] = '\\0';\n char* dot = strrchr(PREVIEW_INTERNAL_NAME, '.');\n if (dot) *dot = '\\0';\n \n LoadFontByName((HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), \n fontResources[i].fontName);\n \n IS_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n \n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n } else if (flags & MF_POPUP) {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n break;\n }\n case WM_EXITMENULOOP: {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case WM_RBUTTONDOWN: {\n if (GetKeyState(VK_CONTROL) & 0x8000) {\n // Toggle edit mode\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Entering edit mode\n SetClickThrough(hwnd, FALSE);\n } else {\n // Exiting edit mode\n SetClickThrough(hwnd, TRUE);\n SaveWindowSettings(hwnd); // Save settings when exiting edit mode\n WriteConfigColor(CLOCK_TEXT_COLOR); // Save the current color to config\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n break;\n }\n case WM_CLOSE: {\n SaveWindowSettings(hwnd); // Save window settings before closing\n DestroyWindow(hwnd); // Close the window\n break;\n }\n case WM_LBUTTONDBLCLK: {\n if (!CLOCK_EDIT_MODE) {\n // Enter edit mode\n StartEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_HOTKEY: {\n // WM_HOTKEY message's lp contains key information\n if (wp == HOTKEY_ID_SHOW_TIME) {\n ToggleShowTimeMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNT_UP) {\n StartCountUp(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNTDOWN) {\n StartDefaultCountDown(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_CUSTOM_COUNTDOWN) {\n // Check if the input dialog already exists\n if (g_hwndInputDialog != NULL && IsWindow(g_hwndInputDialog)) {\n // The dialog already exists, close it\n SendMessage(g_hwndInputDialog, WM_CLOSE, 0, 0);\n return 0;\n }\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Show input dialog to set countdown\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Clear input text\n memset(inputText, 0, sizeof(inputText));\n \n // Show input dialog\n INT_PTR result = DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), \n hwnd, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n \n // If the dialog has input and was confirmed\n if (inputText[0] != '\\0') {\n // Check if input is valid\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Set countdown state\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n \n // Switch to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Stop and restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN1) {\n // Start quick countdown 1\n StartQuickCountdown1(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN2) {\n // Start quick countdown 2\n StartQuickCountdown2(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN3) {\n // Start quick countdown 3\n StartQuickCountdown3(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_POMODORO) {\n // Start Pomodoro timer\n StartPomodoroTimer(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_TOGGLE_VISIBILITY) {\n // Hide/show window\n if (IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_HIDE);\n } else {\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n }\n return 0;\n } else if (wp == HOTKEY_ID_EDIT_MODE) {\n // Enter edit mode\n ToggleEditMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_PAUSE_RESUME) {\n // Pause/resume timer\n TogglePauseResume(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_RESTART_TIMER) {\n // Close all notification windows\n CloseAllNotifications();\n // Restart current timer\n RestartCurrentTimer(hwnd);\n return 0;\n }\n break;\n }\n // Handle reregistration message after hotkey settings change\n case WM_APP+1: {\n // Only reregister hotkeys, do not open dialog\n RegisterGlobalHotkeys(hwnd);\n return 0;\n }\n default:\n return DefWindowProc(hwnd, msg, wp, lp);\n }\n return 0;\n}\n\n// External variable declarations\nextern int CLOCK_DEFAULT_START_TIME;\nextern int countdown_elapsed_time;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern int CLOCK_TOTAL_TIME;\n\n// Remove menu items\nvoid RemoveMenuItems(HMENU hMenu, int count);\n\n// Add menu item\nvoid AddMenuItem(HMENU hMenu, UINT id, const char* text, BOOL isEnabled);\n\n// Modify menu item text\nvoid ModifyMenuItemText(HMENU hMenu, UINT id, const char* text);\n\n/**\n * @brief Toggle show current time mode\n * @param hwnd Window handle\n */\nvoid ToggleShowTimeMode(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // If not currently in show current time mode, then enable it\n // If already in show current time mode, do nothing (don't turn it off)\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Switch to show current time mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n \n // Reset the timer to ensure the update frequency is correct\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 100, NULL); // Use 100ms update frequency to keep the time display smooth\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n }\n // Already in show current time mode, do nothing\n}\n\n/**\n * @brief Start count up timer\n * @param hwnd Window handle\n */\nvoid StartCountUp(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Declare external variables\n extern int countup_elapsed_time;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Reset count up counter\n countup_elapsed_time = 0;\n \n // Set to count up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start default countdown\n * @param hwnd Window handle\n */\nvoid StartDefaultCountDown(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Set mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n if (CLOCK_DEFAULT_START_TIME > 0) {\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n } else {\n // If no default countdown is set, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, 101, 0);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start Pomodoro timer\n * @param hwnd Window handle\n */\nvoid StartPomodoroTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // If it was previously in show current time mode, stop the old timer\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n }\n \n // Use the Pomodoro menu item command to start the Pomodoro timer\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDM_POMODORO_START, 0);\n}\n\n/**\n * @brief Toggle edit mode\n * @param hwnd Window handle\n */\nvoid ToggleEditMode(HWND hwnd) {\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Record the current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If not currently topmost, set it to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure the window is visible and in the foreground\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n } else {\n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, TRUE);\n \n // If it was not topmost before, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Save window settings and color settings\n SaveWindowSettings(hwnd);\n WriteConfigColor(CLOCK_TEXT_COLOR);\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Pause/resume timer\n * @param hwnd Window handle\n */\nvoid TogglePauseResume(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart the current timer\n * @param hwnd Window handle\n */\nvoid RestartCurrentTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Variables imported from main.c\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Reset message shown state to allow notification and sound to be played again when timer ends\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n if (CLOCK_COUNT_UP) {\n // Reset count up timer\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else {\n // Reset countdown timer\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n }\n CLOCK_IS_PAUSED = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Start quick countdown 1\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown1(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there is at least one preset time option\n if (time_options_count > 0) {\n CLOCK_TOTAL_TIME = time_options[0] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are no preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 2\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown2(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least two preset time options\n if (time_options_count > 1) {\n CLOCK_TOTAL_TIME = time_options[1] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 3\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown3(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least three preset time options\n if (time_options_count > 2) {\n CLOCK_TOTAL_TIME = time_options[2] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n"], ["/Catime/src/log.c", "/**\n * @file log.c\n * @brief Log recording functionality implementation\n * \n * Implements logging functionality, including file writing, error code retrieval, etc.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/log.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n\n// Add check for ARM64 macro\n#ifndef PROCESSOR_ARCHITECTURE_ARM64\n#define PROCESSOR_ARCHITECTURE_ARM64 12\n#endif\n\n// Log file path\nstatic char LOG_FILE_PATH[MAX_PATH] = {0};\nstatic FILE* logFile = NULL;\nstatic CRITICAL_SECTION logCS;\n\n// Log level string representations\nstatic const char* LOG_LEVEL_STRINGS[] = {\n \"DEBUG\",\n \"INFO\",\n \"WARNING\",\n \"ERROR\",\n \"FATAL\"\n};\n\n/**\n * @brief Get operating system version information\n * \n * Use Windows API to get operating system version, version number, build and other information\n */\nstatic void LogSystemInformation(void) {\n // Get system information\n SYSTEM_INFO si;\n GetNativeSystemInfo(&si);\n \n // Use RtlGetVersion to get system version more accurately, because GetVersionEx was changed in newer Windows versions\n typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);\n HMODULE hNtdll = GetModuleHandleW(L\"ntdll.dll\");\n \n DWORD major = 0, minor = 0, build = 0;\n BOOL isWorkstation = TRUE;\n BOOL isServer = FALSE;\n \n if (hNtdll) {\n RtlGetVersionPtr pRtlGetVersion = (RtlGetVersionPtr)GetProcAddress(hNtdll, \"RtlGetVersion\");\n if (pRtlGetVersion) {\n RTL_OSVERSIONINFOW rovi = { 0 };\n rovi.dwOSVersionInfoSize = sizeof(rovi);\n if (pRtlGetVersion(&rovi) == 0) { // STATUS_SUCCESS = 0\n major = rovi.dwMajorVersion;\n minor = rovi.dwMinorVersion;\n build = rovi.dwBuildNumber;\n }\n }\n }\n \n // If the above method fails, try the method below\n if (major == 0) {\n OSVERSIONINFOEXA osvi;\n ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA));\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA);\n \n typedef LONG (WINAPI* PRTLGETVERSION)(OSVERSIONINFOEXW*);\n PRTLGETVERSION pRtlGetVersion;\n pRtlGetVersion = (PRTLGETVERSION)GetProcAddress(GetModuleHandle(TEXT(\"ntdll.dll\")), \"RtlGetVersion\");\n \n if (pRtlGetVersion) {\n pRtlGetVersion((OSVERSIONINFOEXW*)&osvi);\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n // Finally try using GetVersionExA, although it may not be accurate\n if (GetVersionExA((OSVERSIONINFOA*)&osvi)) {\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n WriteLog(LOG_LEVEL_WARNING, \"Unable to get operating system version information\");\n }\n }\n }\n \n // Detect specific Windows version\n const char* windowsVersion = \"Unknown version\";\n \n // Determine specific version based on version number\n if (major == 10) {\n if (build >= 22000) {\n windowsVersion = \"Windows 11\";\n } else {\n windowsVersion = \"Windows 10\";\n }\n } else if (major == 6) {\n if (minor == 3) {\n windowsVersion = \"Windows 8.1\";\n } else if (minor == 2) {\n windowsVersion = \"Windows 8\";\n } else if (minor == 1) {\n windowsVersion = \"Windows 7\";\n } else if (minor == 0) {\n windowsVersion = \"Windows Vista\";\n }\n } else if (major == 5) {\n if (minor == 2) {\n windowsVersion = \"Windows Server 2003\";\n if (isWorkstation && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {\n windowsVersion = \"Windows XP Professional x64\";\n }\n } else if (minor == 1) {\n windowsVersion = \"Windows XP\";\n } else if (minor == 0) {\n windowsVersion = \"Windows 2000\";\n }\n }\n \n WriteLog(LOG_LEVEL_INFO, \"Operating System: %s (%d.%d) Build %d %s\", \n windowsVersion,\n major, minor, \n build, \n isWorkstation ? \"Workstation\" : \"Server\");\n \n // CPU architecture\n const char* arch;\n switch (si.wProcessorArchitecture) {\n case PROCESSOR_ARCHITECTURE_AMD64:\n arch = \"x64 (AMD64)\";\n break;\n case PROCESSOR_ARCHITECTURE_INTEL:\n arch = \"x86 (Intel)\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM:\n arch = \"ARM\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM64:\n arch = \"ARM64\";\n break;\n default:\n arch = \"Unknown\";\n break;\n }\n WriteLog(LOG_LEVEL_INFO, \"CPU Architecture: %s\", arch);\n \n // System memory information\n MEMORYSTATUSEX memInfo;\n memInfo.dwLength = sizeof(MEMORYSTATUSEX);\n if (GlobalMemoryStatusEx(&memInfo)) {\n WriteLog(LOG_LEVEL_INFO, \"Physical Memory: %.2f GB / %.2f GB (%d%% used)\", \n (memInfo.ullTotalPhys - memInfo.ullAvailPhys) / (1024.0 * 1024 * 1024), \n memInfo.ullTotalPhys / (1024.0 * 1024 * 1024),\n memInfo.dwMemoryLoad);\n }\n \n // Don't get screen resolution information as it's not accurate and not necessary for debugging\n \n // Check if UAC is enabled\n BOOL uacEnabled = FALSE;\n HANDLE hToken;\n if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {\n TOKEN_ELEVATION_TYPE elevationType;\n DWORD dwSize;\n if (GetTokenInformation(hToken, TokenElevationType, &elevationType, sizeof(elevationType), &dwSize)) {\n uacEnabled = (elevationType != TokenElevationTypeDefault);\n }\n CloseHandle(hToken);\n }\n WriteLog(LOG_LEVEL_INFO, \"UAC Status: %s\", uacEnabled ? \"Enabled\" : \"Disabled\");\n \n // Check if running as administrator\n BOOL isAdmin = FALSE;\n SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;\n PSID AdministratorsGroup;\n if (AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup)) {\n if (CheckTokenMembership(NULL, AdministratorsGroup, &isAdmin)) {\n WriteLog(LOG_LEVEL_INFO, \"Administrator Privileges: %s\", isAdmin ? \"Yes\" : \"No\");\n }\n FreeSid(AdministratorsGroup);\n }\n}\n\n/**\n * @brief Get log file path\n * \n * Build log filename based on config file path\n * \n * @param logPath Log path buffer\n * @param size Buffer size\n */\nstatic void GetLogFilePath(char* logPath, size_t size) {\n char configPath[MAX_PATH] = {0};\n \n // Get directory containing config file\n GetConfigPath(configPath, MAX_PATH);\n \n // Determine config file directory\n char* lastSeparator = strrchr(configPath, '\\\\');\n if (lastSeparator) {\n size_t dirLen = lastSeparator - configPath + 1;\n \n // Copy directory part\n strncpy(logPath, configPath, dirLen);\n \n // Use simple log filename\n _snprintf_s(logPath + dirLen, size - dirLen, _TRUNCATE, \"Catime_Logs.log\");\n } else {\n // If config directory can't be determined, use current directory\n _snprintf_s(logPath, size, _TRUNCATE, \"Catime_Logs.log\");\n }\n}\n\nBOOL InitializeLogSystem(void) {\n InitializeCriticalSection(&logCS);\n \n GetLogFilePath(LOG_FILE_PATH, MAX_PATH);\n \n // Open file in write mode each startup, which clears existing content\n logFile = fopen(LOG_FILE_PATH, \"w\");\n if (!logFile) {\n // Failed to create log file\n return FALSE;\n }\n \n // Record log system initialization information\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n // First record software version\n WriteLog(LOG_LEVEL_INFO, \"Catime Version: %s\", CATIME_VERSION);\n // Then record system environment information (before any possible errors)\n WriteLog(LOG_LEVEL_INFO, \"-----------------System Information-----------------\");\n LogSystemInformation();\n WriteLog(LOG_LEVEL_INFO, \"-----------------Application Information-----------------\");\n WriteLog(LOG_LEVEL_INFO, \"Log system initialization complete, Catime started\");\n \n return TRUE;\n}\n\nvoid WriteLog(LogLevel level, const char* format, ...) {\n if (!logFile) {\n return;\n }\n \n EnterCriticalSection(&logCS);\n \n // Get current time\n time_t now;\n struct tm local_time;\n char timeStr[32] = {0};\n \n time(&now);\n localtime_s(&local_time, &now);\n strftime(timeStr, sizeof(timeStr), \"%Y-%m-%d %H:%M:%S\", &local_time);\n \n // Write log header\n fprintf(logFile, \"[%s] [%s] \", timeStr, LOG_LEVEL_STRINGS[level]);\n \n // Format and write log content\n va_list args;\n va_start(args, format);\n vfprintf(logFile, format, args);\n va_end(args);\n \n // New line\n fprintf(logFile, \"\\n\");\n \n // Flush buffer immediately to ensure logs are saved even if program crashes\n fflush(logFile);\n \n LeaveCriticalSection(&logCS);\n}\n\nvoid GetLastErrorDescription(DWORD errorCode, char* buffer, int bufferSize) {\n if (!buffer || bufferSize <= 0) {\n return;\n }\n \n LPSTR messageBuffer = NULL;\n DWORD size = FormatMessageA(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | \n FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL,\n errorCode,\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n (LPSTR)&messageBuffer,\n 0, NULL);\n \n if (size > 0) {\n // Remove trailing newlines\n if (size >= 2 && messageBuffer[size-2] == '\\r' && messageBuffer[size-1] == '\\n') {\n messageBuffer[size-2] = '\\0';\n }\n \n strncpy_s(buffer, bufferSize, messageBuffer, _TRUNCATE);\n LocalFree(messageBuffer);\n } else {\n _snprintf_s(buffer, bufferSize, _TRUNCATE, \"Unknown error (code: %lu)\", errorCode);\n }\n}\n\n// Signal handler function - used to handle various C standard signals\nvoid SignalHandler(int signal) {\n char errorMsg[256] = {0};\n \n switch (signal) {\n case SIGFPE:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Floating point exception\");\n break;\n case SIGILL:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Illegal instruction\");\n break;\n case SIGSEGV:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Segmentation fault/memory access error\");\n break;\n case SIGTERM:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Termination signal\");\n break;\n case SIGABRT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Abnormal termination/abort\");\n break;\n case SIGINT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"User interrupt\");\n break;\n default:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Unknown signal\");\n break;\n }\n \n // Record exception information\n if (logFile) {\n fprintf(logFile, \"[FATAL] Fatal signal occurred: %s (signal number: %d)\\n\", \n errorMsg, signal);\n fflush(logFile);\n \n // Close log file\n fclose(logFile);\n logFile = NULL;\n }\n \n // Display error message box\n MessageBox(NULL, \"The program encountered a serious error. Please check the log file for detailed information.\", \"Fatal Error\", MB_ICONERROR | MB_OK);\n \n // Terminate program\n exit(signal);\n}\n\nvoid SetupExceptionHandler(void) {\n // Set up standard C signal handlers\n signal(SIGFPE, SignalHandler); // Floating point exception\n signal(SIGILL, SignalHandler); // Illegal instruction\n signal(SIGSEGV, SignalHandler); // Segmentation fault\n signal(SIGTERM, SignalHandler); // Termination signal\n signal(SIGABRT, SignalHandler); // Abnormal termination\n signal(SIGINT, SignalHandler); // User interrupt\n}\n\n// Call this function when program exits to clean up log resources\nvoid CleanupLogSystem(void) {\n if (logFile) {\n WriteLog(LOG_LEVEL_INFO, \"Catime exited normally\");\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n fclose(logFile);\n logFile = NULL;\n }\n \n DeleteCriticalSection(&logCS);\n}\n"], ["/Catime/src/update_checker.c", "/**\n * @file update_checker.c\n * @brief Minimalist application update check functionality implementation\n * \n * This file implements functions for checking versions, opening browser for downloads, and deleting configuration files.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/language.h\"\n#include \"../include/dialog_language.h\"\n#include \"../resource/resource.h\"\n\n#pragma comment(lib, \"wininet.lib\")\n\n// Update source URL\n#define GITHUB_API_URL \"https://api.github.com/repos/vladelaina/Catime/releases/latest\"\n#define USER_AGENT \"Catime Update Checker\"\n\n// Version information structure definition\ntypedef struct {\n const char* currentVersion;\n const char* latestVersion;\n const char* downloadUrl;\n} UpdateVersionInfo;\n\n// Function declarations\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\n/**\n * @brief Compare version numbers\n * @param version1 First version string\n * @param version2 Second version string\n * @return Returns 1 if version1 > version2, 0 if equal, -1 if version1 < version2\n */\nint CompareVersions(const char* version1, const char* version2) {\n LOG_DEBUG(\"Comparing versions: '%s' vs '%s'\", version1, version2);\n \n int major1, minor1, patch1;\n int major2, minor2, patch2;\n \n // Parse version numbers\n sscanf(version1, \"%d.%d.%d\", &major1, &minor1, &patch1);\n sscanf(version2, \"%d.%d.%d\", &major2, &minor2, &patch2);\n \n LOG_DEBUG(\"Parsed version1: %d.%d.%d, version2: %d.%d.%d\", major1, minor1, patch1, major2, minor2, patch2);\n \n // Compare major version\n if (major1 > major2) return 1;\n if (major1 < major2) return -1;\n \n // Compare minor version\n if (minor1 > minor2) return 1;\n if (minor1 < minor2) return -1;\n \n // Compare patch version\n if (patch1 > patch2) return 1;\n if (patch1 < patch2) return -1;\n \n return 0;\n}\n\n/**\n * @brief Parse JSON response to get latest version and download URL\n */\nBOOL ParseLatestVersionFromJson(const char* jsonResponse, char* latestVersion, size_t maxLen, \n char* downloadUrl, size_t urlMaxLen) {\n LOG_DEBUG(\"Starting to parse JSON response, extracting version information\");\n \n // Find version number\n const char* tagNamePos = strstr(jsonResponse, \"\\\"tag_name\\\":\");\n if (!tagNamePos) {\n LOG_ERROR(\"JSON parsing failed: tag_name field not found\");\n return FALSE;\n }\n \n const char* firstQuote = strchr(tagNamePos + 11, '\\\"');\n if (!firstQuote) return FALSE;\n \n const char* secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy version number\n size_t versionLen = secondQuote - (firstQuote + 1);\n if (versionLen >= maxLen) versionLen = maxLen - 1;\n \n strncpy(latestVersion, firstQuote + 1, versionLen);\n latestVersion[versionLen] = '\\0';\n \n // If version starts with 'v', remove it\n if (latestVersion[0] == 'v' || latestVersion[0] == 'V') {\n memmove(latestVersion, latestVersion + 1, versionLen);\n }\n \n // Find download URL\n const char* downloadUrlPos = strstr(jsonResponse, \"\\\"browser_download_url\\\":\");\n if (!downloadUrlPos) {\n LOG_ERROR(\"JSON parsing failed: browser_download_url field not found\");\n return FALSE;\n }\n \n firstQuote = strchr(downloadUrlPos + 22, '\\\"');\n if (!firstQuote) return FALSE;\n \n secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy download URL\n size_t urlLen = secondQuote - (firstQuote + 1);\n if (urlLen >= urlMaxLen) urlLen = urlMaxLen - 1;\n \n strncpy(downloadUrl, firstQuote + 1, urlLen);\n downloadUrl[urlLen] = '\\0';\n \n return TRUE;\n}\n\n/**\n * @brief Exit message dialog procedure\n */\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Get localized exit text\n const wchar_t* exitText = GetLocalizedString(L\"程序即将退出\", L\"The application will exit now\");\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, exitText);\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, L\"\"); // Clear version text\n \n // Set OK button text\n const wchar_t* okText = GetLocalizedString(L\"确定\", L\"OK\");\n SetDlgItemTextW(hwndDlg, IDOK, okText);\n \n // Hide Yes/No buttons, only show OK button\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_SHOW);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"Catime - 更新提示\", L\"Catime - Update Notice\");\n SetWindowTextW(hwndDlg, titleText);\n \n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display custom exit message dialog\n */\nvoid ShowExitMessageDialog(HWND hwnd) {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n ExitMsgDlgProc);\n}\n\n/**\n * @brief Update dialog procedure\n */\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static UpdateVersionInfo* versionInfo = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Save version information\n versionInfo = (UpdateVersionInfo*)lParam;\n \n // Format display text\n if (versionInfo) {\n // Convert ASCII version numbers to Unicode\n wchar_t currentVersionW[64] = {0};\n wchar_t newVersionW[64] = {0};\n \n // Convert version numbers to wide characters\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->currentVersion, -1, \n currentVersionW, sizeof(currentVersionW)/sizeof(wchar_t));\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->latestVersion, -1, \n newVersionW, sizeof(newVersionW)/sizeof(wchar_t));\n \n // Use pre-formatted strings instead of trying to format ourselves\n wchar_t displayText[256];\n \n // Get localized version text (pre-formatted)\n const wchar_t* currentVersionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n const wchar_t* newVersionText = GetLocalizedString(L\"新版本:\", L\"New version:\");\n\n // Manually build formatted string\n StringCbPrintfW(displayText, sizeof(displayText),\n L\"%s %s\\n%s %s\",\n currentVersionText, currentVersionW,\n newVersionText, newVersionW);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, displayText);\n \n // Set button text\n const wchar_t* yesText = GetLocalizedString(L\"是\", L\"Yes\");\n const wchar_t* noText = GetLocalizedString(L\"否\", L\"No\");\n \n // Explicitly set button text, not relying on dialog resource\n SetDlgItemTextW(hwndDlg, IDYES, yesText);\n SetDlgItemTextW(hwndDlg, IDNO, noText);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"发现新版本\", L\"Update Available\");\n SetWindowTextW(hwndDlg, titleText);\n \n // Hide exit text and OK button, show Yes/No buttons\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, L\"\");\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_HIDE);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDNO);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update notification dialog\n */\nint ShowUpdateNotification(HWND hwnd, const char* currentVersion, const char* latestVersion, const char* downloadUrl) {\n // Create version info structure\n UpdateVersionInfo versionInfo;\n versionInfo.currentVersion = currentVersion;\n versionInfo.latestVersion = latestVersion;\n versionInfo.downloadUrl = downloadUrl;\n \n // Display custom dialog\n return DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n UpdateDlgProc, \n (LPARAM)&versionInfo);\n}\n\n/**\n * @brief Update error dialog procedure\n */\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Get error message text\n const wchar_t* errorMsg = (const wchar_t*)lParam;\n if (errorMsg) {\n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_ERROR_TEXT, errorMsg);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update error dialog\n */\nvoid ShowUpdateErrorDialog(HWND hwnd, const wchar_t* errorMsg) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_ERROR_DIALOG), \n hwnd, \n UpdateErrorDlgProc, \n (LPARAM)errorMsg);\n}\n\n/**\n * @brief No update required dialog procedure\n */\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_NO_UPDATE_DIALOG);\n \n // Get current version information\n const char* currentVersion = (const char*)lParam;\n if (currentVersion) {\n // Get localized basic text\n const wchar_t* baseText = GetDialogLocalizedString(IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT);\n if (!baseText) {\n // If localized text not found, use default text\n baseText = L\"You are already using the latest version!\";\n }\n \n // Get localized \"Current version\" text\n const wchar_t* versionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n \n // Create complete message including version number\n wchar_t fullMessage[256];\n StringCbPrintfW(fullMessage, sizeof(fullMessage),\n L\"%s\\n%s %hs\", baseText, versionText, currentVersion);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_NO_UPDATE_TEXT, fullMessage);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display no update required dialog\n * @param hwnd Parent window handle\n * @param currentVersion Current version number\n */\nvoid ShowNoUpdateDialog(HWND hwnd, const char* currentVersion) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_NO_UPDATE_DIALOG), \n hwnd, \n NoUpdateDlgProc, \n (LPARAM)currentVersion);\n}\n\n/**\n * @brief Open browser to download update and exit program\n */\nBOOL OpenBrowserForUpdateAndExit(const char* url, HWND hwnd) {\n // Open browser\n HINSTANCE hInstance = ShellExecuteA(hwnd, \"open\", url, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)hInstance <= 32) {\n // Failed to open browser\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法打开浏览器下载更新\", L\"Could not open browser to download update\"));\n return FALSE;\n }\n \n LOG_INFO(\"Successfully opened browser, preparing to exit program\");\n \n // Prompt user\n wchar_t message[512];\n StringCbPrintfW(message, sizeof(message),\n L\"即将退出程序\");\n \n LOG_INFO(\"Sending exit message to main window\");\n // Use custom dialog to display exit message\n ShowExitMessageDialog(hwnd);\n \n // Exit program\n PostMessage(hwnd, WM_CLOSE, 0, 0);\n return TRUE;\n}\n\n/**\n * @brief General update check function\n */\nvoid CheckForUpdateInternal(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Starting update check process, silent mode: %s\", silentCheck ? \"yes\" : \"no\");\n \n // Create Internet session\n LOG_INFO(\"Attempting to create Internet session\");\n HINTERNET hInternet = InternetOpenA(USER_AGENT, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);\n if (!hInternet) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to create Internet session, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法创建Internet连接\", L\"Could not create Internet connection\"));\n }\n return;\n }\n LOG_INFO(\"Internet session created successfully\");\n \n // Connect to update API\n LOG_INFO(\"Attempting to connect to GitHub API: %s\", GITHUB_API_URL);\n HINTERNET hConnect = InternetOpenUrlA(hInternet, GITHUB_API_URL, NULL, 0, \n INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, 0);\n if (!hConnect) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to connect to GitHub API, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n InternetCloseHandle(hInternet);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法连接到更新服务器\", L\"Could not connect to update server\"));\n }\n return;\n }\n LOG_INFO(\"Successfully connected to GitHub API\");\n \n // Allocate buffer\n LOG_INFO(\"Allocating memory buffer for API response\");\n char* buffer = (char*)malloc(8192);\n if (!buffer) {\n LOG_ERROR(\"Memory allocation failed, could not allocate buffer for API response\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n \n // Read response\n LOG_INFO(\"Starting to read response data from API\");\n DWORD bytesRead = 0;\n DWORD totalBytes = 0;\n size_t bufferSize = 8192;\n \n while (InternetReadFile(hConnect, buffer + totalBytes, \n bufferSize - totalBytes - 1, &bytesRead) && bytesRead > 0) {\n LOG_DEBUG(\"Read %lu bytes of data, accumulated %lu bytes\", bytesRead, totalBytes + bytesRead);\n totalBytes += bytesRead;\n if (totalBytes >= bufferSize - 256) {\n size_t newSize = bufferSize * 2;\n char* newBuffer = (char*)realloc(buffer, newSize);\n if (!newBuffer) {\n // Fix: If realloc fails, free the original buffer and abort\n LOG_ERROR(\"Failed to reallocate buffer, current size: %zu bytes\", bufferSize);\n free(buffer);\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n LOG_DEBUG(\"Buffer expanded, new size: %zu bytes\", newSize);\n buffer = newBuffer;\n bufferSize = newSize;\n }\n }\n \n buffer[totalBytes] = '\\0';\n LOG_INFO(\"Successfully read API response, total %lu bytes of data\", totalBytes);\n \n // Close connection\n LOG_INFO(\"Closing Internet connection\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n \n // Parse version and download URL\n LOG_INFO(\"Starting to parse API response, extracting version info and download URL\");\n char latestVersion[32] = {0};\n char downloadUrl[256] = {0};\n if (!ParseLatestVersionFromJson(buffer, latestVersion, sizeof(latestVersion), \n downloadUrl, sizeof(downloadUrl))) {\n LOG_ERROR(\"Failed to parse version information, response may not be valid JSON format\");\n free(buffer);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法解析版本信息\", L\"Could not parse version information\"));\n }\n return;\n }\n LOG_INFO(\"Successfully parsed version information, GitHub latest version: %s, download URL: %s\", latestVersion, downloadUrl);\n \n free(buffer);\n \n // Get current version\n const char* currentVersion = CATIME_VERSION;\n LOG_INFO(\"Current application version: %s\", currentVersion);\n \n // Compare versions\n LOG_INFO(\"Comparing version numbers: current version %s vs. latest version %s\", currentVersion, latestVersion);\n int versionCompare = CompareVersions(latestVersion, currentVersion);\n if (versionCompare > 0) {\n // New version available\n LOG_INFO(\"New version found! Current: %s, Available update: %s\", currentVersion, latestVersion);\n int response = ShowUpdateNotification(hwnd, currentVersion, latestVersion, downloadUrl);\n LOG_INFO(\"Update prompt dialog result: %s\", response == IDYES ? \"User agreed to update\" : \"User declined update\");\n \n if (response == IDYES) {\n LOG_INFO(\"User chose to update now, preparing to open browser and exit program\");\n OpenBrowserForUpdateAndExit(downloadUrl, hwnd);\n }\n } else if (!silentCheck) {\n // Already using latest version\n LOG_INFO(\"Current version %s is already the latest, no update needed\", currentVersion);\n \n // Use localized strings instead of building complete message\n ShowNoUpdateDialog(hwnd, currentVersion);\n } else {\n LOG_INFO(\"Silent check mode: Current version %s is already the latest, no prompt shown\", currentVersion);\n }\n \n LOG_INFO(\"Update check process complete\");\n}\n\n/**\n * @brief Check for application updates\n */\nvoid CheckForUpdate(HWND hwnd) {\n CheckForUpdateInternal(hwnd, FALSE);\n}\n\n/**\n * @brief Silently check for application updates\n */\nvoid CheckForUpdateSilent(HWND hwnd, BOOL silentCheck) {\n CheckForUpdateInternal(hwnd, silentCheck);\n} \n"], ["/Catime/src/window.c", "/**\n * @file window.c\n * @brief Window management functionality implementation\n * \n * This file implements the functionality related to application window management,\n * including window creation, position adjustment, transparency, click-through, and drag functionality.\n */\n\n#include \"../include/window.h\"\n#include \"../include/timer.h\"\n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n\n// Forward declaration of WindowProcedure (defined in main.c)\nextern LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\n\n// Add declaration for SetProcessDPIAware function\n#ifndef _INC_WINUSER\n// If not included by windows.h, add SetProcessDPIAware function declaration\nWINUSERAPI BOOL WINAPI SetProcessDPIAware(VOID);\n#endif\n\n// Window size and position variables\nint CLOCK_BASE_WINDOW_WIDTH = 200;\nint CLOCK_BASE_WINDOW_HEIGHT = 100;\nfloat CLOCK_WINDOW_SCALE = 1.0f;\nint CLOCK_WINDOW_POS_X = 100;\nint CLOCK_WINDOW_POS_Y = 100;\n\n// Window state variables\nBOOL CLOCK_EDIT_MODE = FALSE;\nBOOL CLOCK_IS_DRAGGING = FALSE;\nPOINT CLOCK_LAST_MOUSE_POS = {0, 0};\nBOOL CLOCK_WINDOW_TOPMOST = TRUE; // Default topmost\n\n// Text area variables\nRECT CLOCK_TEXT_RECT = {0, 0, 0, 0};\nBOOL CLOCK_TEXT_RECT_VALID = FALSE;\n\n// DWM function pointer type definition\ntypedef HRESULT (WINAPI *pfnDwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);\nstatic pfnDwmEnableBlurBehindWindow _DwmEnableBlurBehindWindow = NULL;\n\n// Window composition attribute type definition\ntypedef enum _WINDOWCOMPOSITIONATTRIB {\n WCA_UNDEFINED = 0,\n WCA_NCRENDERING_ENABLED = 1,\n WCA_NCRENDERING_POLICY = 2,\n WCA_TRANSITIONS_FORCEDISABLED = 3,\n WCA_ALLOW_NCPAINT = 4,\n WCA_CAPTION_BUTTON_BOUNDS = 5,\n WCA_NONCLIENT_RTL_LAYOUT = 6,\n WCA_FORCE_ICONIC_REPRESENTATION = 7,\n WCA_EXTENDED_FRAME_BOUNDS = 8,\n WCA_HAS_ICONIC_BITMAP = 9,\n WCA_THEME_ATTRIBUTES = 10,\n WCA_NCRENDERING_EXILED = 11,\n WCA_NCADORNMENTINFO = 12,\n WCA_EXCLUDED_FROM_LIVEPREVIEW = 13,\n WCA_VIDEO_OVERLAY_ACTIVE = 14,\n WCA_FORCE_ACTIVEWINDOW_APPEARANCE = 15,\n WCA_DISALLOW_PEEK = 16,\n WCA_CLOAK = 17,\n WCA_CLOAKED = 18,\n WCA_ACCENT_POLICY = 19,\n WCA_FREEZE_REPRESENTATION = 20,\n WCA_EVER_UNCLOAKED = 21,\n WCA_VISUAL_OWNER = 22,\n WCA_HOLOGRAPHIC = 23,\n WCA_EXCLUDED_FROM_DDA = 24,\n WCA_PASSIVEUPDATEMODE = 25,\n WCA_USEDARKMODECOLORS = 26,\n WCA_LAST = 27\n} WINDOWCOMPOSITIONATTRIB;\n\ntypedef struct _WINDOWCOMPOSITIONATTRIBDATA {\n WINDOWCOMPOSITIONATTRIB Attrib;\n PVOID pvData;\n SIZE_T cbData;\n} WINDOWCOMPOSITIONATTRIBDATA;\n\nWINUSERAPI BOOL WINAPI SetWindowCompositionAttribute(HWND hwnd, WINDOWCOMPOSITIONATTRIBDATA* pData);\n\ntypedef enum _ACCENT_STATE {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5\n} ACCENT_STATE;\n\ntypedef struct _ACCENT_POLICY {\n ACCENT_STATE AccentState;\n DWORD AccentFlags;\n DWORD GradientColor;\n DWORD AnimationId;\n} ACCENT_POLICY;\n\nvoid SetClickThrough(HWND hwnd, BOOL enable) {\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n // Clear previously set related styles\n exStyle &= ~WS_EX_TRANSPARENT;\n \n if (enable) {\n // Set click-through\n exStyle |= WS_EX_TRANSPARENT;\n \n // If the window is a layered window, ensure it properly handles mouse input\n if (exStyle & WS_EX_LAYERED) {\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n }\n } else {\n // Ensure window receives all mouse input\n if (exStyle & WS_EX_LAYERED) {\n // Maintain transparency but allow receiving mouse input\n SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);\n }\n }\n \n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Update window to apply new style\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n}\n\nBOOL InitDWMFunctions() {\n HMODULE hDwmapi = LoadLibraryA(\"dwmapi.dll\");\n if (hDwmapi) {\n _DwmEnableBlurBehindWindow = (pfnDwmEnableBlurBehindWindow)GetProcAddress(hDwmapi, \"DwmEnableBlurBehindWindow\");\n return _DwmEnableBlurBehindWindow != NULL;\n }\n return FALSE;\n}\n\nvoid SetBlurBehind(HWND hwnd, BOOL enable) {\n if (enable) {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_ENABLE_BLURBEHIND;\n policy.AccentFlags = 0;\n policy.GradientColor = (180 << 24) | 0x00202020; // Changed to dark gray background with 180 transparency\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = TRUE;\n bb.hRgnBlur = NULL;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n } else {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_DISABLED;\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = FALSE;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n }\n}\n\nvoid AdjustWindowPosition(HWND hwnd, BOOL forceOnScreen) {\n if (!forceOnScreen) {\n // Do not force window to be on screen, return directly\n return;\n }\n \n // Original code to ensure window is on screen\n RECT rect;\n GetWindowRect(hwnd, &rect);\n \n int screenWidth = GetSystemMetrics(SM_CXSCREEN);\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n \n int width = rect.right - rect.left;\n int height = rect.bottom - rect.top;\n \n int x = rect.left;\n int y = rect.top;\n \n // Ensure window right edge doesn't exceed screen\n if (x + width > screenWidth) {\n x = screenWidth - width;\n }\n \n // Ensure window bottom edge doesn't exceed screen\n if (y + height > screenHeight) {\n y = screenHeight - height;\n }\n \n // Ensure window left edge doesn't exceed screen\n if (x < 0) {\n x = 0;\n }\n \n // Ensure window top edge doesn't exceed screen\n if (y < 0) {\n y = 0;\n }\n \n // If window position needs adjustment, move the window\n if (x != rect.left || y != rect.top) {\n SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n }\n}\n\nextern void GetConfigPath(char* path, size_t size);\nextern void WriteConfigEditMode(const char* mode);\n\nvoid SaveWindowSettings(HWND hwnd) {\n if (!hwnd) return;\n\n RECT rect;\n if (!GetWindowRect(hwnd, &rect)) return;\n \n CLOCK_WINDOW_POS_X = rect.left;\n CLOCK_WINDOW_POS_Y = rect.top;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n size_t buffer_size = 8192; \n char *config = malloc(buffer_size);\n char *new_config = malloc(buffer_size);\n if (!config || !new_config) {\n if (config) free(config);\n if (new_config) free(new_config);\n fclose(fp);\n return;\n }\n \n config[0] = new_config[0] = '\\0';\n char line[256];\n size_t total_len = 0;\n \n while (fgets(line, sizeof(line), fp)) {\n size_t line_len = strlen(line);\n if (total_len + line_len >= buffer_size - 1) {\n size_t new_size = buffer_size * 2;\n char *temp_config = realloc(config, new_size);\n char *temp_new_config = realloc(new_config, new_size);\n \n if (!temp_config || !temp_new_config) {\n free(config);\n free(new_config);\n fclose(fp);\n return;\n }\n \n config = temp_config;\n new_config = temp_new_config;\n buffer_size = new_size;\n }\n strcat(config, line);\n total_len += line_len;\n }\n fclose(fp);\n \n char *start = config;\n char *end = config + strlen(config);\n BOOL has_window_scale = FALSE;\n size_t new_config_len = 0;\n \n while (start < end) {\n char *newline = strchr(start, '\\n');\n if (!newline) newline = end;\n \n char temp[256] = {0};\n size_t line_len = newline - start;\n if (line_len >= sizeof(temp)) line_len = sizeof(temp) - 1;\n strncpy(temp, start, line_len);\n \n if (strncmp(temp, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len, \n buffer_size - new_config_len, \n \"CLOCK_WINDOW_POS_X=%d\\n\", CLOCK_WINDOW_POS_X);\n } else if (strncmp(temp, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"CLOCK_WINDOW_POS_Y=%d\\n\", CLOCK_WINDOW_POS_Y);\n } else if (strncmp(temp, \"WINDOW_SCALE=\", 13) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n has_window_scale = TRUE;\n } else {\n size_t remaining = buffer_size - new_config_len;\n if (remaining > line_len + 1) {\n strncpy(new_config + new_config_len, start, line_len);\n new_config_len += line_len;\n new_config[new_config_len++] = '\\n';\n }\n }\n \n start = newline + 1;\n if (start > end) break;\n }\n \n if (!has_window_scale && buffer_size - new_config_len > 50) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n }\n \n if (new_config_len < buffer_size) {\n new_config[new_config_len] = '\\0';\n } else {\n new_config[buffer_size - 1] = '\\0';\n }\n \n fp = fopen(config_path, \"w\");\n if (fp) {\n fputs(new_config, fp);\n fclose(fp);\n }\n \n free(config);\n free(new_config);\n}\n\nvoid LoadWindowSettings(HWND hwnd) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n line[strcspn(line, \"\\n\")] = 0;\n \n if (strncmp(line, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n CLOCK_WINDOW_POS_X = atoi(line + 19);\n } else if (strncmp(line, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n CLOCK_WINDOW_POS_Y = atoi(line + 19);\n } else if (strncmp(line, \"WINDOW_SCALE=\", 13) == 0) {\n CLOCK_WINDOW_SCALE = atof(line + 13);\n CLOCK_FONT_SCALE_FACTOR = CLOCK_WINDOW_SCALE;\n }\n }\n fclose(fp);\n \n // Apply position from config file directly, without additional adjustments\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, \n CLOCK_WINDOW_POS_Y,\n (int)(CLOCK_BASE_WINDOW_WIDTH * CLOCK_WINDOW_SCALE),\n (int)(CLOCK_BASE_WINDOW_HEIGHT * CLOCK_WINDOW_SCALE),\n SWP_NOZORDER\n );\n \n // Don't call AdjustWindowPosition to avoid overriding user settings\n}\n\nBOOL HandleMouseWheel(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n // Remove original position calculation logic, directly use window center as scaling reference point\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n // Use window center as scaling reference\n float relativeX = 0.5f;\n float relativeY = 0.5f;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings after resizing\n SaveWindowSettings(hwnd);\n }\n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleMouseMove(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update the position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nHWND CreateMainWindow(HINSTANCE hInstance, int nCmdShow) {\n // Window class registration\n WNDCLASS wc = {0};\n wc.lpfnWndProc = WindowProcedure;\n wc.hInstance = hInstance;\n wc.lpszClassName = \"CatimeWindow\";\n \n if (!RegisterClass(&wc)) {\n MessageBox(NULL, \"Window Registration Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n // Set extended style\n DWORD exStyle = WS_EX_LAYERED | WS_EX_TOOLWINDOW;\n \n // If not in topmost mode, add WS_EX_NOACTIVATE extended style\n if (!CLOCK_WINDOW_TOPMOST) {\n exStyle |= WS_EX_NOACTIVATE;\n }\n \n // Create window\n HWND hwnd = CreateWindowEx(\n exStyle,\n \"CatimeWindow\",\n \"Catime\",\n WS_POPUP,\n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n CLOCK_BASE_WINDOW_WIDTH, CLOCK_BASE_WINDOW_HEIGHT,\n NULL,\n NULL,\n hInstance,\n NULL\n );\n\n if (!hwnd) {\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n EnableWindow(hwnd, TRUE);\n SetFocus(hwnd);\n\n // Set window transparency\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n\n // Set blur effect\n SetBlurBehind(hwnd, FALSE);\n\n // Initialize tray icon\n InitTrayIcon(hwnd, hInstance);\n\n // Show window\n ShowWindow(hwnd, nCmdShow);\n UpdateWindow(hwnd);\n\n // Set window position and parent based on topmost status\n if (CLOCK_WINDOW_TOPMOST) {\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n } else {\n // Find desktop window and set as parent\n HWND hProgman = FindWindow(\"Progman\", NULL);\n if (hProgman != NULL) {\n // Try to find the real desktop window\n HWND hDesktop = hProgman;\n \n // Look for WorkerW window (common in Win10+)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n \n // Set as child window of desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, set to bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n\n return hwnd;\n}\n\nfloat CLOCK_FONT_SCALE_FACTOR = 1.0f;\nint CLOCK_BASE_FONT_SIZE = 24;\n\nBOOL InitializeApplication(HINSTANCE hInstance) {\n // Set DPI awareness mode to Per-Monitor DPI Aware to properly handle scaling when moving window between displays with different DPIs\n // Use newer API SetProcessDpiAwarenessContext if available, otherwise fallback to older APIs\n \n // Define DPI awareness related constants and types\n #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);\n #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n #endif\n \n // Define PROCESS_DPI_AWARENESS enum\n typedef enum {\n PROCESS_DPI_UNAWARE = 0,\n PROCESS_SYSTEM_DPI_AWARE = 1,\n PROCESS_PER_MONITOR_DPI_AWARE = 2\n } PROCESS_DPI_AWARENESS;\n \n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n typedef BOOL(WINAPI* SetProcessDpiAwarenessContextFunc)(DPI_AWARENESS_CONTEXT);\n SetProcessDpiAwarenessContextFunc setProcessDpiAwarenessContextFunc =\n (SetProcessDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetProcessDpiAwarenessContext\");\n \n if (setProcessDpiAwarenessContextFunc) {\n // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 is the latest DPI awareness mode\n // It provides better multi-monitor DPI support\n setProcessDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n } else {\n // Try using older API\n HMODULE hShcore = LoadLibraryA(\"shcore.dll\");\n if (hShcore) {\n typedef HRESULT(WINAPI* SetProcessDpiAwarenessFunc)(PROCESS_DPI_AWARENESS);\n SetProcessDpiAwarenessFunc setProcessDpiAwarenessFunc =\n (SetProcessDpiAwarenessFunc)GetProcAddress(hShcore, \"SetProcessDpiAwareness\");\n \n if (setProcessDpiAwarenessFunc) {\n // PROCESS_PER_MONITOR_DPI_AWARE corresponds to per-monitor DPI awareness\n setProcessDpiAwarenessFunc(PROCESS_PER_MONITOR_DPI_AWARE);\n } else {\n // Finally try the oldest API\n SetProcessDPIAware();\n }\n \n FreeLibrary(hShcore);\n } else {\n // If shcore.dll is not available, use the most basic DPI awareness API\n SetProcessDPIAware();\n }\n }\n }\n \n SetConsoleOutputCP(936);\n SetConsoleCP(936);\n\n // Modified initialization order: read config file first, then initialize other features\n ReadConfig();\n UpdateStartupShortcut();\n InitializeDefaultLanguage();\n\n int defaultFontIndex = -1;\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, FONT_FILE_NAME) == 0) {\n defaultFontIndex = i;\n break;\n }\n }\n\n if (defaultFontIndex != -1) {\n LoadFontFromResource(hInstance, fontResources[defaultFontIndex].resourceId);\n }\n\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n \n return TRUE;\n}\n\nBOOL OpenFileDialog(HWND hwnd, char* filePath, DWORD maxPath) {\n OPENFILENAME ofn = { 0 };\n ofn.lStructSize = sizeof(OPENFILENAME);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFilter = \"All Files\\0*.*\\0\";\n ofn.lpstrFile = filePath;\n ofn.nMaxFile = maxPath;\n ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;\n ofn.lpstrDefExt = \"\";\n \n return GetOpenFileName(&ofn);\n}\n\n// Add function to set window topmost state\nvoid SetWindowTopmost(HWND hwnd, BOOL topmost) {\n CLOCK_WINDOW_TOPMOST = topmost;\n \n // Get current window style\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n if (topmost) {\n // Topmost mode: remove no-activate style (if exists), add topmost style\n exStyle &= ~WS_EX_NOACTIVATE;\n \n // If window was previously set as desktop child window, need to restore\n // First set window as top-level window, clear parent window relationship\n SetParent(hwnd, NULL);\n \n // Reset window owner, ensure Z-order is correct\n SetWindowLongPtr(hwnd, GWLP_HWNDPARENT, 0);\n \n // Set window position to top layer, and force window update\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_FRAMECHANGED);\n } else {\n // Non-topmost mode: add no-activate style to prevent window from gaining focus\n exStyle |= WS_EX_NOACTIVATE;\n \n // Set as child window of desktop\n HWND hProgman = FindWindow(\"Progman\", NULL);\n HWND hDesktop = NULL;\n \n // Try to find the real desktop window\n if (hProgman != NULL) {\n // First try using Progman\n hDesktop = hProgman;\n \n // Look for WorkerW window (more common on Win10)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n // Found the real desktop container\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n }\n \n if (hDesktop != NULL) {\n // Set window as child of desktop, this keeps it on the desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, at least place at bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n \n // Apply new window style\n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Force window update\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n \n // Save window topmost setting\n WriteConfigTopmost(topmost ? \"TRUE\" : \"FALSE\");\n}\n"], ["/Catime/src/startup.c", "/**\n * @file startup.c\n * @brief Implementation of auto-start functionality\n * \n * This file implements the application's auto-start related functionality,\n * including checking if auto-start is enabled, creating and deleting auto-start shortcuts.\n */\n\n#include \"../include/startup.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/config.h\"\n#include \"../include/timer.h\"\n\n#ifndef CSIDL_STARTUP\n#define CSIDL_STARTUP 0x0007\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern int countup_elapsed_time;\nextern int CLOCK_DEFAULT_START_TIME;\nextern char CLOCK_STARTUP_MODE[20];\n/// @}\n\n/**\n * @brief Check if the application is set to auto-start at system boot\n * @return BOOL Returns TRUE if auto-start is enabled, otherwise FALSE\n */\nBOOL IsAutoStartEnabled(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n return GetFileAttributesW(startupPath) != INVALID_FILE_ATTRIBUTES;\n }\n return FALSE;\n}\n\n/**\n * @brief Create auto-start shortcut\n * @return BOOL Returns TRUE if creation was successful, otherwise FALSE\n */\nBOOL CreateShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n wchar_t exePath[MAX_PATH];\n IShellLinkW* pShellLink = NULL;\n IPersistFile* pPersistFile = NULL;\n BOOL success = FALSE;\n \n GetModuleFileNameW(NULL, exePath, MAX_PATH);\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n HRESULT hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkW, (void**)&pShellLink);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->SetPath(pShellLink, exePath);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->QueryInterface(pShellLink,\n &IID_IPersistFile,\n (void**)&pPersistFile);\n if (SUCCEEDED(hr)) {\n hr = pPersistFile->lpVtbl->Save(pPersistFile, startupPath, TRUE);\n if (SUCCEEDED(hr)) {\n success = TRUE;\n }\n pPersistFile->lpVtbl->Release(pPersistFile);\n }\n }\n pShellLink->lpVtbl->Release(pShellLink);\n }\n }\n \n return success;\n}\n\n/**\n * @brief Delete auto-start shortcut\n * @return BOOL Returns TRUE if deletion was successful, otherwise FALSE\n */\nBOOL RemoveShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n return DeleteFileW(startupPath);\n }\n return FALSE;\n}\n\n/**\n * @brief Update auto-start shortcut\n * \n * Check if auto-start is enabled, if so, delete the old shortcut and create a new one,\n * ensuring that the auto-start functionality works correctly even if the application location changes.\n * \n * @return BOOL Returns TRUE if update was successful, otherwise FALSE\n */\nBOOL UpdateStartupShortcut(void) {\n // If auto-start is already enabled\n if (IsAutoStartEnabled()) {\n // First delete the existing shortcut\n RemoveShortcut();\n // Create a new shortcut\n return CreateShortcut();\n }\n return TRUE; // Auto-start not enabled, considered successful\n}\n\n/**\n * @brief Apply startup mode settings\n * @param hwnd Window handle\n * \n * Initialize the application's display state according to the startup mode settings in the configuration file\n */\nvoid ApplyStartupMode(HWND hwnd) {\n // Read startup mode from configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", CLOCK_STARTUP_MODE);\n break;\n }\n }\n fclose(configFile);\n \n // Apply startup mode\n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n // Set to count-up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n // Set to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n // Set to no display mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n } else { // Default to countdown mode \"COUNTDOWN\"\n // Set to countdown mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n \n // Read default countdown time\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n \n // If countdown is set, start the timer\n if (CLOCK_TOTAL_TIME > 0) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n"], ["/Catime/src/async_update_checker.c", "/**\n * @file async_update_checker.c\n * @brief Asynchronous application update checking functionality\n */\n\n#include \n#include \n#include \"../include/async_update_checker.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n\ntypedef struct {\n HWND hwnd;\n BOOL silentCheck;\n} UpdateThreadParams;\n\nstatic HANDLE g_hUpdateThread = NULL;\nstatic BOOL g_bUpdateThreadRunning = FALSE;\n\n/**\n * @brief Clean up update check thread resources\n */\nvoid CleanupUpdateThread() {\n LOG_INFO(\"Cleaning up update check thread resources\");\n if (g_hUpdateThread != NULL) {\n DWORD waitResult = WaitForSingleObject(g_hUpdateThread, 1000);\n if (waitResult == WAIT_TIMEOUT) {\n LOG_WARNING(\"Wait for thread end timed out, forcibly closing thread handle\");\n } else if (waitResult == WAIT_OBJECT_0) {\n LOG_INFO(\"Thread has ended normally\");\n } else {\n LOG_WARNING(\"Wait for thread returned unexpected result: %lu\", waitResult);\n }\n\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n g_bUpdateThreadRunning = FALSE;\n LOG_INFO(\"Thread resources have been cleaned up\");\n } else {\n LOG_INFO(\"Update check thread not running, no cleanup needed\");\n }\n}\n\n/**\n * @brief Update check thread function\n * @param param Thread parameters\n */\nunsigned __stdcall UpdateCheckThreadProc(void* param) {\n LOG_INFO(\"Update check thread started\");\n\n UpdateThreadParams* threadParams = (UpdateThreadParams*)param;\n if (!threadParams) {\n LOG_ERROR(\"Thread parameters are null, cannot perform update check\");\n g_bUpdateThreadRunning = FALSE;\n _endthreadex(1);\n return 1;\n }\n\n HWND hwnd = threadParams->hwnd;\n BOOL silentCheck = threadParams->silentCheck;\n\n LOG_INFO(\"Thread parameters parsed successfully, window handle: 0x%p, silent check mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n\n free(threadParams);\n LOG_INFO(\"Thread parameter memory freed\");\n\n LOG_INFO(\"Starting update check\");\n CheckForUpdateSilent(hwnd, silentCheck);\n LOG_INFO(\"Update check completed\");\n\n g_bUpdateThreadRunning = FALSE;\n\n _endthreadex(0);\n return 0;\n}\n\n/**\n * @brief Check for application updates asynchronously\n * @param hwnd Window handle\n * @param silentCheck Whether to perform a silent check\n */\nvoid CheckForUpdateAsync(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Asynchronous update check requested, window handle: 0x%p, silent mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n\n if (g_bUpdateThreadRunning) {\n LOG_INFO(\"Update check thread already running, skipping this check request\");\n return;\n }\n\n if (g_hUpdateThread != NULL) {\n LOG_INFO(\"Found old thread handle, cleaning up...\");\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n LOG_INFO(\"Old thread handle closed\");\n }\n\n LOG_INFO(\"Allocating memory for thread parameters\");\n UpdateThreadParams* threadParams = (UpdateThreadParams*)malloc(sizeof(UpdateThreadParams));\n if (!threadParams) {\n LOG_ERROR(\"Thread parameter memory allocation failed, cannot start update check thread\");\n return;\n }\n\n threadParams->hwnd = hwnd;\n threadParams->silentCheck = silentCheck;\n LOG_INFO(\"Thread parameters set up\");\n\n g_bUpdateThreadRunning = TRUE;\n\n LOG_INFO(\"Preparing to create update check thread\");\n HANDLE hThread = (HANDLE)_beginthreadex(\n NULL,\n 0,\n UpdateCheckThreadProc,\n threadParams,\n 0,\n NULL\n );\n\n if (hThread) {\n LOG_INFO(\"Update check thread created successfully, thread handle: 0x%p\", hThread);\n g_hUpdateThread = hThread;\n } else {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Update check thread creation failed, error code: %lu, error message: %s\", errorCode, errorMsg);\n\n free(threadParams);\n g_bUpdateThreadRunning = FALSE;\n }\n}"], ["/Catime/src/config.c", "/**\n * @file config.c\n * @brief Configuration file management module implementation\n */\n\n#include \"../include/config.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define MAX_POMODORO_TIMES 10\n\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nint POMODORO_TIMES[MAX_POMODORO_TIMES] = {1500, 300, 1500, 600};\nint POMODORO_TIMES_COUNT = 4;\n\nchar CLOCK_TIMEOUT_MESSAGE_TEXT[100] = \"时间到啦!\";\nchar POMODORO_TIMEOUT_MESSAGE_TEXT[100] = \"番茄钟时间到!\";\nchar POMODORO_CYCLE_COMPLETE_TEXT[100] = \"所有番茄钟循环完成!\";\n\nint NOTIFICATION_TIMEOUT_MS = 3000;\nint NOTIFICATION_MAX_OPACITY = 95;\nNotificationType NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\nBOOL NOTIFICATION_DISABLED = FALSE;\n\nchar NOTIFICATION_SOUND_FILE[MAX_PATH] = \"\";\nint NOTIFICATION_SOUND_VOLUME = 100;\n\n/** @brief Read string value from INI file */\nDWORD ReadIniString(const char* section, const char* key, const char* defaultValue,\n char* returnValue, DWORD returnSize, const char* filePath) {\n return GetPrivateProfileStringA(section, key, defaultValue, returnValue, returnSize, filePath);\n}\n\n/** @brief Write string value to INI file */\nBOOL WriteIniString(const char* section, const char* key, const char* value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value, filePath);\n}\n\n/** @brief Read integer value from INI */\nint ReadIniInt(const char* section, const char* key, int defaultValue, \n const char* filePath) {\n return GetPrivateProfileIntA(section, key, defaultValue, filePath);\n}\n\n/** @brief Write integer value to INI file */\nBOOL WriteIniInt(const char* section, const char* key, int value,\n const char* filePath) {\n char valueStr[32];\n snprintf(valueStr, sizeof(valueStr), \"%d\", value);\n return WritePrivateProfileStringA(section, key, valueStr, filePath);\n}\n\n/** @brief Write boolean value to INI file */\nBOOL WriteIniBool(const char* section, const char* key, BOOL value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value ? \"TRUE\" : \"FALSE\", filePath);\n}\n\n/** @brief Read boolean value from INI */\nBOOL ReadIniBool(const char* section, const char* key, BOOL defaultValue, \n const char* filePath) {\n char value[8];\n GetPrivateProfileStringA(section, key, defaultValue ? \"TRUE\" : \"FALSE\", \n value, sizeof(value), filePath);\n return _stricmp(value, \"TRUE\") == 0;\n}\n\n/** @brief Check if configuration file exists */\nBOOL FileExists(const char* filePath) {\n return GetFileAttributesA(filePath) != INVALID_FILE_ATTRIBUTES;\n}\n\n/** @brief Get configuration file path */\nvoid GetConfigPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\config.ini\", appdata_path) >= size) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Create default configuration file */\nvoid CreateDefaultConfig(const char* config_path) {\n // Get system default language ID\n LANGID systemLangID = GetUserDefaultUILanguage();\n int defaultLanguage = APP_LANG_ENGLISH; // Default to English\n const char* langName = \"English\"; // Default language name\n \n // Set default language based on system language ID\n switch (PRIMARYLANGID(systemLangID)) {\n case LANG_CHINESE:\n if (SUBLANGID(systemLangID) == SUBLANG_CHINESE_SIMPLIFIED) {\n defaultLanguage = APP_LANG_CHINESE_SIMP;\n langName = \"Chinese_Simplified\";\n } else {\n defaultLanguage = APP_LANG_CHINESE_TRAD;\n langName = \"Chinese_Traditional\";\n }\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n langName = \"Spanish\";\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n langName = \"French\";\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n langName = \"German\";\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n langName = \"Russian\";\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n langName = \"Portuguese\";\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n langName = \"Japanese\";\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n langName = \"Korean\";\n break;\n case LANG_ENGLISH:\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n langName = \"English\";\n break;\n }\n \n // Choose default settings based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", \"TRUE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 1; i <= 5; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n config_path);\n}\n\n/** @brief Extract filename from file path */\nvoid ExtractFileName(const char* path, char* name, size_t nameSize) {\n if (!path || !name || nameSize == 0) return;\n \n // First convert to wide characters to properly handle Unicode paths\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, wPath, MAX_PATH);\n \n // Look for the last backslash or forward slash\n wchar_t* lastSlash = wcsrchr(wPath, L'\\\\');\n if (!lastSlash) lastSlash = wcsrchr(wPath, L'/');\n \n wchar_t wName[MAX_PATH] = {0};\n if (lastSlash) {\n wcscpy(wName, lastSlash + 1);\n } else {\n wcscpy(wName, wPath);\n }\n \n // Convert back to UTF-8\n WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, nameSize, NULL, NULL);\n}\n\n/** @brief Check and create resource folders */\nvoid CheckAndCreateResourceFolders() {\n char config_path[MAX_PATH];\n char base_path[MAX_PATH];\n char resource_path[MAX_PATH];\n char *last_slash;\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Copy configuration file path\n strncpy(base_path, config_path, MAX_PATH - 1);\n base_path[MAX_PATH - 1] = '\\0';\n \n // Find the last slash or backslash, which marks the beginning of the filename\n last_slash = strrchr(base_path, '\\\\');\n if (!last_slash) {\n last_slash = strrchr(base_path, '/');\n }\n \n if (last_slash) {\n // Truncate path to directory part\n *(last_slash + 1) = '\\0';\n \n // Create resources main directory\n snprintf(resource_path, MAX_PATH, \"%sresources\", base_path);\n DWORD attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create resources folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n return;\n }\n }\n \n // Create audio subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\audio\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create audio folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create images subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\images\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create images folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create animations subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\animations\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create animations folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create themes subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\themes\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create themes folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create plug-in subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\plug-in\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create plug-in folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n }\n}\n\n/** @brief Read and parse configuration file */\nvoid ReadConfig() {\n // Check and create resource folders\n CheckAndCreateResourceFolders();\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Check if configuration file exists, create default configuration if it doesn't\n if (!FileExists(config_path)) {\n CreateDefaultConfig(config_path);\n }\n \n // Check configuration file version\n char version[32] = {0};\n BOOL versionMatched = FALSE;\n \n // Read current version information\n ReadIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", \"\", version, sizeof(version), config_path);\n \n // Compare if version matches\n if (strcmp(version, CATIME_VERSION) == 0) {\n versionMatched = TRUE;\n }\n \n // If version doesn't match, recreate the configuration file\n if (!versionMatched) {\n CreateDefaultConfig(config_path);\n }\n\n // Reset time options\n time_options_count = 0;\n memset(time_options, 0, sizeof(time_options));\n \n // Reset recent files count\n CLOCK_RECENT_FILES_COUNT = 0;\n \n // Read basic settings\n // ======== [General] Section ========\n char language[32] = {0};\n ReadIniString(INI_SECTION_GENERAL, \"LANGUAGE\", \"English\", language, sizeof(language), config_path);\n \n // Convert language name to enum value\n int languageSetting = APP_LANG_ENGLISH; // Default to English\n \n if (strcmp(language, \"Chinese_Simplified\") == 0) {\n languageSetting = APP_LANG_CHINESE_SIMP;\n } else if (strcmp(language, \"Chinese_Traditional\") == 0) {\n languageSetting = APP_LANG_CHINESE_TRAD;\n } else if (strcmp(language, \"English\") == 0) {\n languageSetting = APP_LANG_ENGLISH;\n } else if (strcmp(language, \"Spanish\") == 0) {\n languageSetting = APP_LANG_SPANISH;\n } else if (strcmp(language, \"French\") == 0) {\n languageSetting = APP_LANG_FRENCH;\n } else if (strcmp(language, \"German\") == 0) {\n languageSetting = APP_LANG_GERMAN;\n } else if (strcmp(language, \"Russian\") == 0) {\n languageSetting = APP_LANG_RUSSIAN;\n } else if (strcmp(language, \"Portuguese\") == 0) {\n languageSetting = APP_LANG_PORTUGUESE;\n } else if (strcmp(language, \"Japanese\") == 0) {\n languageSetting = APP_LANG_JAPANESE;\n } else if (strcmp(language, \"Korean\") == 0) {\n languageSetting = APP_LANG_KOREAN;\n } else {\n // Try to parse as number (for backward compatibility)\n int langValue = atoi(language);\n if (langValue >= 0 && langValue < APP_LANG_COUNT) {\n languageSetting = langValue;\n } else {\n languageSetting = APP_LANG_ENGLISH; // Default to English\n }\n }\n \n // ======== [Display] Section ========\n ReadIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", CLOCK_TEXT_COLOR, sizeof(CLOCK_TEXT_COLOR), config_path);\n CLOCK_BASE_FONT_SIZE = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n ReadIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", FONT_FILE_NAME, sizeof(FONT_FILE_NAME), config_path);\n \n // Extract internal name from font filename\n size_t font_name_len = strlen(FONT_FILE_NAME);\n if (font_name_len > 4 && strcmp(FONT_FILE_NAME + font_name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = font_name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n CLOCK_WINDOW_POS_X = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n CLOCK_WINDOW_POS_Y = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n \n char scaleStr[16] = {0};\n ReadIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", scaleStr, sizeof(scaleStr), config_path);\n CLOCK_WINDOW_SCALE = atof(scaleStr);\n \n CLOCK_WINDOW_TOPMOST = ReadIniBool(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", TRUE, config_path);\n \n // Check and replace pure black color\n if (strcasecmp(CLOCK_TEXT_COLOR, \"#000000\") == 0) {\n strncpy(CLOCK_TEXT_COLOR, \"#000001\", sizeof(CLOCK_TEXT_COLOR) - 1);\n }\n \n // ======== [Timer] Section ========\n CLOCK_DEFAULT_START_TIME = ReadIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n CLOCK_USE_24HOUR = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", FALSE, config_path);\n CLOCK_SHOW_SECONDS = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", FALSE, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", CLOCK_TIMEOUT_TEXT, sizeof(CLOCK_TIMEOUT_TEXT), config_path);\n \n // Read timeout action\n char timeoutAction[32] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", timeoutAction, sizeof(timeoutAction), config_path);\n \n if (strcmp(timeoutAction, \"MESSAGE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"LOCK\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n } else if (strcmp(timeoutAction, \"SHUTDOWN\") == 0) {\n // Even if SHUTDOWN exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"RESTART\") == 0) {\n // Even if RESTART exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"OPEN_FILE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n } else if (strcmp(timeoutAction, \"SHOW_TIME\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n } else if (strcmp(timeoutAction, \"COUNT_UP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n } else if (strcmp(timeoutAction, \"OPEN_WEBSITE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n } else if (strcmp(timeoutAction, \"SLEEP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n } else if (strcmp(timeoutAction, \"RUN_COMMAND\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n } else if (strcmp(timeoutAction, \"HTTP_REQUEST\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n }\n \n // Read timeout file and website settings\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", CLOCK_TIMEOUT_FILE_PATH, MAX_PATH, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", CLOCK_TIMEOUT_WEBSITE_URL, MAX_PATH, config_path);\n \n // If file path is valid, ensure timeout action is set to open file\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n GetFileAttributesA(CLOCK_TIMEOUT_FILE_PATH) != INVALID_FILE_ATTRIBUTES) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n }\n \n // If URL is valid, ensure timeout action is set to open website\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n }\n \n // Read time options\n char timeOptions[256] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", timeOptions, sizeof(timeOptions), config_path);\n \n char *token = strtok(timeOptions, \",\");\n while (token && time_options_count < MAX_TIME_OPTIONS) {\n while (*token == ' ') token++;\n time_options[time_options_count++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Read startup mode\n ReadIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", CLOCK_STARTUP_MODE, sizeof(CLOCK_STARTUP_MODE), config_path);\n \n // ======== [Pomodoro] Section ========\n char pomodoroTimeOptions[256] = {0};\n ReadIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", pomodoroTimeOptions, sizeof(pomodoroTimeOptions), config_path);\n \n // Reset pomodoro time count\n POMODORO_TIMES_COUNT = 0;\n \n // Parse all pomodoro time values\n token = strtok(pomodoroTimeOptions, \",\");\n while (token && POMODORO_TIMES_COUNT < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[POMODORO_TIMES_COUNT++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Even though we now use a new array to store all times,\n // keep these three variables for backward compatibility\n if (POMODORO_TIMES_COUNT > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (POMODORO_TIMES_COUNT > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (POMODORO_TIMES_COUNT > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[3]; // Note this is the 4th value\n }\n \n // Read pomodoro loop count\n POMODORO_LOOP_COUNT = ReadIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n \n // ======== [Notification] Section ========\n ReadIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", \n CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", \n POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", \n POMODORO_CYCLE_COMPLETE_TEXT, sizeof(POMODORO_CYCLE_COMPLETE_TEXT), config_path);\n \n NOTIFICATION_TIMEOUT_MS = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n NOTIFICATION_MAX_OPACITY = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n \n // Ensure opacity is within valid range (1-100)\n if (NOTIFICATION_MAX_OPACITY < 1) NOTIFICATION_MAX_OPACITY = 1;\n if (NOTIFICATION_MAX_OPACITY > 100) NOTIFICATION_MAX_OPACITY = 100;\n \n char notificationType[32] = {0};\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", \"CATIME\", notificationType, sizeof(notificationType), config_path);\n \n // Set notification type\n if (strcmp(notificationType, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(notificationType, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(notificationType, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Read notification audio file path\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", \n NOTIFICATION_SOUND_FILE, MAX_PATH, config_path);\n \n // Read notification audio volume\n NOTIFICATION_SOUND_VOLUME = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n \n // Read whether to disable notification window\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n \n // Ensure volume is within valid range (0-100)\n if (NOTIFICATION_SOUND_VOLUME < 0) NOTIFICATION_SOUND_VOLUME = 0;\n if (NOTIFICATION_SOUND_VOLUME > 100) NOTIFICATION_SOUND_VOLUME = 100;\n \n // ======== [Colors] Section ========\n char colorOptions[1024] = {0};\n ReadIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n colorOptions, sizeof(colorOptions), config_path);\n \n // Parse color options\n token = strtok(colorOptions, \",\");\n COLOR_OPTIONS_COUNT = 0;\n while (token) {\n COLOR_OPTIONS = realloc(COLOR_OPTIONS, sizeof(PredefinedColor) * (COLOR_OPTIONS_COUNT + 1));\n if (COLOR_OPTIONS) {\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = strdup(token);\n COLOR_OPTIONS_COUNT++;\n }\n token = strtok(NULL, \",\");\n }\n \n // ======== [RecentFiles] Section ========\n // Read recent file records\n for (int i = 1; i <= MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n \n char filePath[MAX_PATH] = {0};\n ReadIniString(INI_SECTION_RECENTFILES, key, \"\", filePath, MAX_PATH, config_path);\n \n if (strlen(filePath) > 0) {\n // Convert to wide characters to properly check if the file exists\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, widePath, MAX_PATH);\n \n // Check if file exists\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n ExtractFileName(filePath, CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, MAX_PATH);\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n \n // ======== [Hotkeys] Section ========\n // Read hotkey configurations from INI file\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n // Read hotkey settings\n char hotkeyStr[32] = {0};\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n showTimeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countUpHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countdownHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown1Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown2Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown3Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pomodoroHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n toggleVisibilityHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n editModeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pauseResumeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n restartTimerHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n customCountdownHotkey = StringToHotkey(hotkeyStr);\n \n last_config_time = time(NULL);\n\n // Apply window position\n HWND hwnd = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwnd) {\n SetWindowPos(hwnd, NULL, CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n\n // Apply language settings\n SetLanguage((AppLanguage)languageSetting);\n}\n\n/** @brief Write timeout action configuration */\nvoid WriteConfigTimeoutAction(const char* action) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n // For shutdown or restart actions, don't write them to the config file, write \"MESSAGE\" instead\n const char* actual_action = action;\n if (strcmp(action, \"RESTART\") == 0 || strcmp(action, \"SHUTDOWN\") == 0 || strcmp(action, \"SLEEP\") == 0) {\n actual_action = \"MESSAGE\";\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write time options configuration */\nvoid WriteConfigTimeOptions(const char* options) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIME_OPTIONS=\", 19) == 0) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Load recently used file records */\nvoid LoadRecentFiles(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) return;\n\n char line[MAX_PATH];\n CLOCK_RECENT_FILES_COUNT = 0;\n\n while (fgets(line, sizeof(line), file)) {\n // Support for the CLOCK_RECENT_FILE_N=path format\n if (strncmp(line, \"CLOCK_RECENT_FILE_\", 18) == 0) {\n char *path = strchr(line + 18, '=');\n if (path) {\n path++; // Skip the equals sign\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n // Also update the old format for compatibility\n else if (strncmp(line, \"CLOCK_RECENT_FILE=\", 18) == 0) {\n char *path = line + 18;\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n\n fclose(file);\n}\n\n/** @brief Save recently used file record */\nvoid SaveRecentFile(const char* filePath) {\n // Check if the file path is valid\n if (!filePath || strlen(filePath) == 0) return;\n \n // Convert to wide characters to check if the file exists\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) == INVALID_FILE_ATTRIBUTES) {\n // File doesn't exist, don't add it\n return;\n }\n \n // Check if the file is already in the list\n int existingIndex = -1;\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n if (strcmp(CLOCK_RECENT_FILES[i].path, filePath) == 0) {\n existingIndex = i;\n break;\n }\n }\n \n if (existingIndex == 0) {\n // File is already at the top of the list, no action needed\n return;\n }\n \n if (existingIndex > 0) {\n // File is in the list, but not at the top, need to move it\n RecentFile temp = CLOCK_RECENT_FILES[existingIndex];\n \n // Move elements backward\n for (int i = existingIndex; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Put it at the first position\n CLOCK_RECENT_FILES[0] = temp;\n } else {\n // File is not in the list, need to add it\n // First ensure the list doesn't exceed 5 items\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n CLOCK_RECENT_FILES_COUNT++;\n }\n \n // Move elements backward\n for (int i = CLOCK_RECENT_FILES_COUNT - 1; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Add new file to the first position\n strncpy(CLOCK_RECENT_FILES[0].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[0].path[MAX_PATH - 1] = '\\0';\n \n // Extract filename\n ExtractFileName(filePath, CLOCK_RECENT_FILES[0].name, MAX_PATH);\n }\n \n // Update configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n WriteConfig(configPath);\n}\n\n/** @brief Convert UTF8 to ANSI encoding */\nchar* UTF8ToANSI(const char* utf8Str) {\n int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, NULL, 0);\n if (wlen == 0) {\n return _strdup(utf8Str);\n }\n\n wchar_t* wstr = (wchar_t*)malloc(sizeof(wchar_t) * wlen);\n if (!wstr) {\n return _strdup(utf8Str);\n }\n\n if (MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, wstr, wlen) == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n int len = WideCharToMultiByte(936, 0, wstr, -1, NULL, 0, NULL, NULL);\n if (len == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n char* str = (char*)malloc(len);\n if (!str) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n if (WideCharToMultiByte(936, 0, wstr, -1, str, len, NULL, NULL) == 0) {\n free(wstr);\n free(str);\n return _strdup(utf8Str);\n }\n\n free(wstr);\n return str;\n}\n\n/** @brief Write pomodoro time settings */\nvoid WriteConfigPomodoroTimes(int work, int short_break, int long_break) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n // Update global variables\n // Maintain backward compatibility, while updating the POMODORO_TIMES array\n POMODORO_WORK_TIME = work;\n POMODORO_SHORT_BREAK = short_break;\n POMODORO_LONG_BREAK = long_break;\n \n // Ensure at least these three time values exist\n POMODORO_TIMES[0] = work;\n if (POMODORO_TIMES_COUNT < 1) POMODORO_TIMES_COUNT = 1;\n \n if (POMODORO_TIMES_COUNT > 1) {\n POMODORO_TIMES[1] = short_break;\n } else if (short_break > 0) {\n POMODORO_TIMES[1] = short_break;\n POMODORO_TIMES_COUNT = 2;\n }\n \n if (POMODORO_TIMES_COUNT > 2) {\n POMODORO_TIMES[2] = long_break;\n } else if (long_break > 0) {\n POMODORO_TIMES[2] = long_break;\n POMODORO_TIMES_COUNT = 3;\n }\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n // Look for POMODORO_TIME_OPTIONS line\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write all pomodoro times\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If POMODORO_TIME_OPTIONS was not found, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro loop count configuration */\nvoid WriteConfigPomodoroLoopCount(int loop_count) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If the key was not found in the configuration file, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n POMODORO_LOOP_COUNT = loop_count;\n}\n\n/** @brief Write window topmost status configuration */\nvoid WriteConfigTopmost(const char* topmost) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"WINDOW_TOPMOST=\", 15) == 0) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write timeout open file path */\nvoid WriteConfigTimeoutFile(const char* filePath) {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n strncpy(CLOCK_TIMEOUT_FILE_PATH, filePath, MAX_PATH - 1);\n CLOCK_TIMEOUT_FILE_PATH[MAX_PATH - 1] = '\\0';\n \n // Use WriteConfig to completely rewrite the configuration file, maintaining structural consistency\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n}\n\n/** @brief Write all configuration settings to file */\nvoid WriteConfig(const char* config_path) {\n // Get the name of the current language\n AppLanguage currentLang = GetCurrentLanguage();\n const char* langName;\n \n switch (currentLang) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n case APP_LANG_ENGLISH:\n default:\n langName = \"English\";\n break;\n }\n \n // Choose string representation based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Read hotkey settings\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0};\n \n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Prepare time options string\n char timeOptionsStr[256] = {0};\n for (int i = 0; i < time_options_count; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", time_options[i]);\n \n if (i > 0) {\n strcat(timeOptionsStr, \",\");\n }\n strcat(timeOptionsStr, buffer);\n }\n \n // Prepare pomodoro time options string\n char pomodoroTimesStr[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", POMODORO_TIMES[i]);\n \n if (i > 0) {\n strcat(pomodoroTimesStr, \",\");\n }\n strcat(pomodoroTimesStr, buffer);\n }\n \n // Prepare color options string\n char colorOptionsStr[1024] = {0};\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (i > 0) {\n strcat(colorOptionsStr, \",\");\n }\n strcat(colorOptionsStr, COLOR_OPTIONS[i].hexColor);\n }\n \n // Determine timeout action string\n const char* timeoutActionStr;\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_LOCK:\n timeoutActionStr = \"LOCK\";\n break;\n case TIMEOUT_ACTION_SHUTDOWN:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RESTART:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_OPEN_FILE:\n timeoutActionStr = \"OPEN_FILE\";\n break;\n case TIMEOUT_ACTION_SHOW_TIME:\n timeoutActionStr = \"SHOW_TIME\";\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n timeoutActionStr = \"COUNT_UP\";\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n timeoutActionStr = \"OPEN_WEBSITE\";\n break;\n case TIMEOUT_ACTION_SLEEP:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n timeoutActionStr = \"RUN_COMMAND\";\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n timeoutActionStr = \"HTTP_REQUEST\";\n break;\n default:\n timeoutActionStr = \"MESSAGE\";\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", IsShortcutCheckDone() ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", CLOCK_TEXT_COLOR, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", CLOCK_BASE_FONT_SIZE, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", FONT_FILE_NAME, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", CLOCK_WINDOW_POS_X, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", CLOCK_WINDOW_POS_Y, config_path);\n \n char scaleStr[16];\n snprintf(scaleStr, sizeof(scaleStr), \"%.2f\", CLOCK_WINDOW_SCALE);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", scaleStr, config_path);\n \n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", CLOCK_WINDOW_TOPMOST ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", CLOCK_DEFAULT_START_TIME, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", CLOCK_USE_24HOUR ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", CLOCK_SHOW_SECONDS ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", CLOCK_TIMEOUT_TEXT, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", timeoutActionStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", CLOCK_TIMEOUT_FILE_PATH, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", CLOCK_TIMEOUT_WEBSITE_URL, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", timeOptionsStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", CLOCK_STARTUP_MODE, config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", pomodoroTimesStr, config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", POMODORO_LOOP_COUNT, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", CLOCK_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", POMODORO_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", POMODORO_CYCLE_COMPLETE_TEXT, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", NOTIFICATION_TIMEOUT_MS, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", NOTIFICATION_MAX_OPACITY, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", NOTIFICATION_SOUND_FILE, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", NOTIFICATION_SOUND_VOLUME, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", NOTIFICATION_DISABLED ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", showTimeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", countUpStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", countdownStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", quickCountdown1Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", quickCountdown2Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", quickCountdown3Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", pomodoroStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", toggleVisibilityStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", editModeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", pauseResumeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", restartTimerStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr, config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, CLOCK_RECENT_FILES[i].path, config_path);\n }\n \n // Clear unused file records\n for (int i = CLOCK_RECENT_FILES_COUNT; i < MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", colorOptionsStr, config_path);\n}\n\n/** @brief Write timeout open website URL */\nvoid WriteConfigTimeoutWebsite(const char* url) {\n // Only set timeout action to open website if a valid URL is provided\n if (url && url[0] != '\\0') {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n strncpy(CLOCK_TIMEOUT_WEBSITE_URL, url, MAX_PATH - 1);\n CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH - 1] = '\\0';\n \n // Then update the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL actionFound = FALSE;\n BOOL urlFound = FALSE;\n \n // Read original configuration file, update timeout action and URL\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n actionFound = TRUE;\n } else if (strncmp(line, \"CLOCK_TIMEOUT_WEBSITE=\", 22) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n urlFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If these items are not in the configuration, add them\n if (!actionFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n }\n if (!urlFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n }\n}\n\n/** @brief Write startup mode configuration */\nvoid WriteConfigStartupMode(const char* mode) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n // Update global variable\n strncpy(CLOCK_STARTUP_MODE, mode, sizeof(CLOCK_STARTUP_MODE) - 1);\n CLOCK_STARTUP_MODE[sizeof(CLOCK_STARTUP_MODE) - 1] = '\\0';\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro time options */\nvoid WriteConfigPomodoroTimeOptions(int* times, int count) {\n if (!times || count <= 0) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL optionsFound = FALSE;\n \n // Read original configuration file, update pomodoro time options\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write new time options\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n optionsFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If this item is not in the configuration, add it\n if (!optionsFound) {\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write notification message configuration */\nvoid WriteConfigNotificationMessages(const char* timeout_msg, const char* pomodoro_msg, const char* cycle_complete_msg) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n // Use standard C file operations instead of Windows API\n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL timeoutFound = FALSE;\n BOOL pomodoroFound = FALSE;\n BOOL cycleFound = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n timeoutFound = TRUE;\n } else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n pomodoroFound = TRUE;\n } else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n cycleFound = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If corresponding items are not found in the configuration, add them\n if (!timeoutFound) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n }\n \n if (!pomodoroFound) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n }\n \n if (!cycleFound) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variables\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, timeout_msg, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, pomodoro_msg, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, cycle_complete_msg, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n}\n\n/** @brief Read notification message text from configuration file */\nvoid ReadNotificationMessagesConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current values in memory or default values\n return;\n }\n\n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[1024];\n BOOL timeoutMsgFound = FALSE;\n BOOL pomodoroTimeoutMsgFound = FALSE;\n BOOL cycleCompleteMsgFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n // Process this line\n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, line + 27, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n timeoutMsgFound = TRUE;\n } \n else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, line + 30, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n pomodoroTimeoutMsgFound = TRUE;\n }\n else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, line + 29, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n cycleCompleteMsgFound = TRUE;\n }\n \n // If all messages have been found, can exit loop early\n if (timeoutMsgFound && pomodoroTimeoutMsgFound && cycleCompleteMsgFound) {\n break;\n }\n }\n \n CloseHandle(hFile);\n \n // If corresponding configuration items are not found in the file, ensure variables have default values\n if (!timeoutMsgFound) {\n strcpy(CLOCK_TIMEOUT_MESSAGE_TEXT, \"时间到啦!\"); // Default value\n }\n if (!pomodoroTimeoutMsgFound) {\n strcpy(POMODORO_TIMEOUT_MESSAGE_TEXT, \"番茄钟时间到!\"); // Default value\n }\n if (!cycleCompleteMsgFound) {\n strcpy(POMODORO_CYCLE_COMPLETE_TEXT, \"所有番茄钟循环完成!\"); // Default value\n }\n}\n\n/** @brief Read notification display time from configuration file */\nvoid ReadNotificationTimeoutConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL timeoutFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n int timeout = atoi(line + 24);\n if (timeout > 0) {\n NOTIFICATION_TIMEOUT_MS = timeout;\n }\n timeoutFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!timeoutFound) {\n NOTIFICATION_TIMEOUT_MS = 3000; // Ensure there's a default value\n }\n}\n\n/** @brief Write notification display time configuration */\nvoid WriteConfigNotificationTimeout(int timeout_ms) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_TIMEOUT_MS = timeout_ms;\n}\n\n/** @brief Read maximum notification opacity from configuration file */\nvoid ReadNotificationOpacityConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL opacityFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n int opacity = atoi(line + 25);\n // Ensure opacity is within valid range (1-100)\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n opacityFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!opacityFound) {\n NOTIFICATION_MAX_OPACITY = 95; // Ensure there's a default value\n }\n}\n\n/** @brief Write maximum notification opacity configuration */\nvoid WriteConfigNotificationOpacity(int opacity) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_MAX_OPACITY = opacity;\n}\n\n/** @brief Read notification type setting from configuration file */\nvoid ReadNotificationTypeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *file = fopen(config_path, \"r\");\n if (file) {\n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n char typeStr[32] = {0};\n sscanf(line + 18, \"%31s\", typeStr);\n \n // Set notification type based on the string\n if (strcmp(typeStr, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(typeStr, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(typeStr, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n // Use default value for invalid type\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n }\n break;\n }\n }\n fclose(file);\n }\n}\n\n/** @brief Write notification type configuration */\nvoid WriteConfigNotificationType(NotificationType type) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure type value is within valid range\n if (type < NOTIFICATION_TYPE_CATIME || type > NOTIFICATION_TYPE_OS) {\n type = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Update global variable\n NOTIFICATION_TYPE = type;\n \n // Convert enum to string\n const char* typeStr;\n switch (type) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Create temporary file path\n char temp_path[MAX_PATH];\n strncpy(temp_path, config_path, MAX_PATH - 5);\n strcat(temp_path, \".tmp\");\n \n FILE *source = fopen(config_path, \"r\");\n FILE *target = fopen(temp_path, \"w\");\n \n if (source && target) {\n char line[256];\n BOOL found = FALSE;\n \n // Copy file content, replace target configuration line\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n found = TRUE;\n } else {\n fputs(line, target);\n }\n }\n \n // If configuration item not found, add it to the end of file\n if (!found) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n }\n \n fclose(source);\n fclose(target);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n } else {\n // Clean up potentially open files\n if (source) fclose(source);\n if (target) fclose(target);\n }\n}\n\n/** @brief Get audio folder path */\nvoid GetAudioFolderPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) >= size) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Read notification audio settings from configuration file */\nvoid ReadNotificationSoundConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[1024];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n char* value = line + 23; // Correct offset, skip \"NOTIFICATION_SOUND_FILE=\"\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Ensure path doesn't contain equals sign\n if (value[0] == '=') {\n value++; // If first character is equals sign, skip it\n }\n \n // Copy to global variable, ensure cleared\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, value, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio configuration */\nvoid WriteConfigNotificationSound(const char* sound_file) {\n if (!sound_file) return;\n \n // Check if the path contains equals sign, remove if present\n char clean_path[MAX_PATH] = {0};\n const char* src = sound_file;\n char* dst = clean_path;\n \n while (*src && (dst - clean_path) < (MAX_PATH - 1)) {\n if (*src != '=') {\n *dst++ = *src;\n }\n src++;\n }\n *dst = '\\0';\n \n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Create temporary file path\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE* source = fopen(config_path, \"r\");\n if (!source) return;\n \n FILE* dest = fopen(temp_path, \"w\");\n if (!dest) {\n fclose(source);\n return;\n }\n \n char line[1024];\n int found = 0;\n \n // Copy file content, replace or add notification audio settings\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n found = 1;\n } else {\n fputs(line, dest);\n }\n }\n \n // If configuration item not found, add to end of file\n if (!found) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n }\n \n fclose(source);\n fclose(dest);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, clean_path, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n}\n\n/** @brief Read notification audio volume from configuration file */\nvoid ReadNotificationVolumeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n int volume = atoi(line + 26);\n if (volume >= 0 && volume <= 100) {\n NOTIFICATION_SOUND_VOLUME = volume;\n }\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio volume configuration */\nvoid WriteConfigNotificationVolume(int volume) {\n // Validate volume range\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n \n // Update global variable\n NOTIFICATION_SOUND_VOLUME = volume;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Read hotkey settings from configuration file */\nvoid ReadConfigHotkeys(WORD* showTimeHotkey, WORD* countUpHotkey, WORD* countdownHotkey,\n WORD* quickCountdown1Hotkey, WORD* quickCountdown2Hotkey, WORD* quickCountdown3Hotkey,\n WORD* pomodoroHotkey, WORD* toggleVisibilityHotkey, WORD* editModeHotkey,\n WORD* pauseResumeHotkey, WORD* restartTimerHotkey)\n{\n // Parameter validation\n if (!showTimeHotkey || !countUpHotkey || !countdownHotkey || \n !quickCountdown1Hotkey || !quickCountdown2Hotkey || !quickCountdown3Hotkey ||\n !pomodoroHotkey || !toggleVisibilityHotkey || !editModeHotkey || \n !pauseResumeHotkey || !restartTimerHotkey) return;\n \n // Initialize to 0 (indicates no hotkey set)\n *showTimeHotkey = 0;\n *countUpHotkey = 0;\n *countdownHotkey = 0;\n *quickCountdown1Hotkey = 0;\n *quickCountdown2Hotkey = 0;\n *quickCountdown3Hotkey = 0;\n *pomodoroHotkey = 0;\n *toggleVisibilityHotkey = 0;\n *editModeHotkey = 0;\n *pauseResumeHotkey = 0;\n *restartTimerHotkey = 0;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *showTimeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countUpHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countdownHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown1Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown2Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown3Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pomodoroHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n char* value = line + 25;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *toggleVisibilityHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *editModeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n char* value = line + 20;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pauseResumeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n char* value = line + 21;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *restartTimerHotkey = StringToHotkey(value);\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write hotkey configuration */\nvoid WriteConfigHotkeys(WORD showTimeHotkey, WORD countUpHotkey, WORD countdownHotkey,\n WORD quickCountdown1Hotkey, WORD quickCountdown2Hotkey, WORD quickCountdown3Hotkey,\n WORD pomodoroHotkey, WORD toggleVisibilityHotkey, WORD editModeHotkey,\n WORD pauseResumeHotkey, WORD restartTimerHotkey) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) {\n // If file doesn't exist, create new file\n file = fopen(config_path, \"w\");\n if (!file) return;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0}; // Add custom countdown hotkey\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n // Get custom countdown hotkey value\n WORD customCountdownHotkey = 0;\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Write hotkey configuration\n fprintf(file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n fprintf(file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n fprintf(file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n fprintf(file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n fprintf(file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n fprintf(file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n fprintf(file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n fprintf(file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n fprintf(file, \"HOTKEY_CUSTOM_COUNTDOWN=%s\\n\", customCountdownStr); // Add new hotkey\n \n fclose(file);\n return;\n }\n \n // File exists, read all lines and update hotkey settings\n char temp_path[MAX_PATH];\n sprintf(temp_path, \"%s.tmp\", config_path);\n FILE* temp_file = fopen(temp_path, \"w\");\n \n if (!temp_file) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL foundShowTime = FALSE;\n BOOL foundCountUp = FALSE;\n BOOL foundCountdown = FALSE;\n BOOL foundQuickCountdown1 = FALSE;\n BOOL foundQuickCountdown2 = FALSE;\n BOOL foundQuickCountdown3 = FALSE;\n BOOL foundPomodoro = FALSE;\n BOOL foundToggleVisibility = FALSE;\n BOOL foundEditMode = FALSE;\n BOOL foundPauseResume = FALSE;\n BOOL foundRestartTimer = FALSE;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n \n // Process each line\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n foundShowTime = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n foundCountUp = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n foundCountdown = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n foundQuickCountdown1 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n foundQuickCountdown2 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n foundQuickCountdown3 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n foundPomodoro = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n foundToggleVisibility = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n foundEditMode = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n foundPauseResume = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n foundRestartTimer = TRUE;\n }\n else {\n // Keep other lines\n fputs(line, temp_file);\n }\n }\n \n // Add hotkey configuration items not found\n if (!foundShowTime) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n }\n if (!foundCountUp) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n }\n if (!foundCountdown) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n }\n if (!foundQuickCountdown1) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n }\n if (!foundQuickCountdown2) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n }\n if (!foundQuickCountdown3) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n }\n if (!foundPomodoro) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n }\n if (!foundToggleVisibility) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n }\n if (!foundEditMode) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n }\n if (!foundPauseResume) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n }\n if (!foundRestartTimer) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n }\n \n fclose(file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Convert hotkey value to readable string */\nvoid HotkeyToString(WORD hotkey, char* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) return;\n \n // 如果热键为0,表示未设置\n if (hotkey == 0) {\n strncpy(buffer, \"None\", bufferSize - 1);\n buffer[bufferSize - 1] = '\\0';\n return;\n }\n \n BYTE vk = LOBYTE(hotkey); // 虚拟键码\n BYTE mod = HIBYTE(hotkey); // 修饰键\n \n buffer[0] = '\\0';\n size_t len = 0;\n \n // 添加修饰键\n if (mod & HOTKEYF_CONTROL) {\n strncpy(buffer, \"Ctrl\", bufferSize - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_SHIFT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Shift\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_ALT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Alt\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n // 添加虚拟键\n if (len > 0 && len < bufferSize - 1 && vk != 0) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n \n // 获取虚拟键名称\n if (vk >= 'A' && vk <= 'Z') {\n // 字母键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= '0' && vk <= '9') {\n // 数字键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= VK_F1 && vk <= VK_F24) {\n // 功能键\n char keyName[4];\n sprintf(keyName, \"F%d\", vk - VK_F1 + 1);\n strncat(buffer, keyName, bufferSize - len - 1);\n } else {\n // 其他特殊键\n switch (vk) {\n case VK_BACK: strncat(buffer, \"Backspace\", bufferSize - len - 1); break;\n case VK_TAB: strncat(buffer, \"Tab\", bufferSize - len - 1); break;\n case VK_RETURN: strncat(buffer, \"Enter\", bufferSize - len - 1); break;\n case VK_ESCAPE: strncat(buffer, \"Esc\", bufferSize - len - 1); break;\n case VK_SPACE: strncat(buffer, \"Space\", bufferSize - len - 1); break;\n case VK_PRIOR: strncat(buffer, \"PageUp\", bufferSize - len - 1); break;\n case VK_NEXT: strncat(buffer, \"PageDown\", bufferSize - len - 1); break;\n case VK_END: strncat(buffer, \"End\", bufferSize - len - 1); break;\n case VK_HOME: strncat(buffer, \"Home\", bufferSize - len - 1); break;\n case VK_LEFT: strncat(buffer, \"Left\", bufferSize - len - 1); break;\n case VK_UP: strncat(buffer, \"Up\", bufferSize - len - 1); break;\n case VK_RIGHT: strncat(buffer, \"Right\", bufferSize - len - 1); break;\n case VK_DOWN: strncat(buffer, \"Down\", bufferSize - len - 1); break;\n case VK_INSERT: strncat(buffer, \"Insert\", bufferSize - len - 1); break;\n case VK_DELETE: strncat(buffer, \"Delete\", bufferSize - len - 1); break;\n case VK_NUMPAD0: strncat(buffer, \"Num0\", bufferSize - len - 1); break;\n case VK_NUMPAD1: strncat(buffer, \"Num1\", bufferSize - len - 1); break;\n case VK_NUMPAD2: strncat(buffer, \"Num2\", bufferSize - len - 1); break;\n case VK_NUMPAD3: strncat(buffer, \"Num3\", bufferSize - len - 1); break;\n case VK_NUMPAD4: strncat(buffer, \"Num4\", bufferSize - len - 1); break;\n case VK_NUMPAD5: strncat(buffer, \"Num5\", bufferSize - len - 1); break;\n case VK_NUMPAD6: strncat(buffer, \"Num6\", bufferSize - len - 1); break;\n case VK_NUMPAD7: strncat(buffer, \"Num7\", bufferSize - len - 1); break;\n case VK_NUMPAD8: strncat(buffer, \"Num8\", bufferSize - len - 1); break;\n case VK_NUMPAD9: strncat(buffer, \"Num9\", bufferSize - len - 1); break;\n case VK_MULTIPLY: strncat(buffer, \"Num*\", bufferSize - len - 1); break;\n case VK_ADD: strncat(buffer, \"Num+\", bufferSize - len - 1); break;\n case VK_SUBTRACT: strncat(buffer, \"Num-\", bufferSize - len - 1); break;\n case VK_DECIMAL: strncat(buffer, \"Num.\", bufferSize - len - 1); break;\n case VK_DIVIDE: strncat(buffer, \"Num/\", bufferSize - len - 1); break;\n case VK_OEM_1: strncat(buffer, \";\", bufferSize - len - 1); break;\n case VK_OEM_PLUS: strncat(buffer, \"=\", bufferSize - len - 1); break;\n case VK_OEM_COMMA: strncat(buffer, \",\", bufferSize - len - 1); break;\n case VK_OEM_MINUS: strncat(buffer, \"-\", bufferSize - len - 1); break;\n case VK_OEM_PERIOD: strncat(buffer, \".\", bufferSize - len - 1); break;\n case VK_OEM_2: strncat(buffer, \"/\", bufferSize - len - 1); break;\n case VK_OEM_3: strncat(buffer, \"`\", bufferSize - len - 1); break;\n case VK_OEM_4: strncat(buffer, \"[\", bufferSize - len - 1); break;\n case VK_OEM_5: strncat(buffer, \"\\\\\", bufferSize - len - 1); break;\n case VK_OEM_6: strncat(buffer, \"]\", bufferSize - len - 1); break;\n case VK_OEM_7: strncat(buffer, \"'\", bufferSize - len - 1); break;\n default: \n // 对于其他未知键,使用十六进制表示\n {\n char keyName[8];\n sprintf(keyName, \"0x%02X\", vk);\n strncat(buffer, keyName, bufferSize - len - 1);\n }\n break;\n }\n }\n}\n\n/** @brief Convert string to hotkey value */\nWORD StringToHotkey(const char* str) {\n if (!str || str[0] == '\\0' || strcmp(str, \"None\") == 0) {\n return 0; // 未设置热键\n }\n \n // 尝试直接解析为数字(兼容旧格式)\n if (isdigit(str[0])) {\n return (WORD)atoi(str);\n }\n \n BYTE vk = 0; // 虚拟键码\n BYTE mod = 0; // 修饰键\n \n // 复制字符串以便使用strtok\n char buffer[256];\n strncpy(buffer, str, sizeof(buffer) - 1);\n buffer[sizeof(buffer) - 1] = '\\0';\n \n // 分割字符串,查找修饰键和主键\n char* token = strtok(buffer, \"+\");\n char* lastToken = NULL;\n \n while (token) {\n if (stricmp(token, \"Ctrl\") == 0) {\n mod |= HOTKEYF_CONTROL;\n } else if (stricmp(token, \"Shift\") == 0) {\n mod |= HOTKEYF_SHIFT;\n } else if (stricmp(token, \"Alt\") == 0) {\n mod |= HOTKEYF_ALT;\n } else {\n // 可能是主键\n lastToken = token;\n }\n token = strtok(NULL, \"+\");\n }\n \n // 解析主键\n if (lastToken) {\n // 检查是否是单个字符的字母或数字\n if (strlen(lastToken) == 1) {\n char ch = toupper(lastToken[0]);\n if ((ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) {\n vk = ch;\n }\n } \n // 检查是否是功能键\n else if (lastToken[0] == 'F' && isdigit(lastToken[1])) {\n int fNum = atoi(lastToken + 1);\n if (fNum >= 1 && fNum <= 24) {\n vk = VK_F1 + fNum - 1;\n }\n }\n // 检查特殊键名\n else if (stricmp(lastToken, \"Backspace\") == 0) vk = VK_BACK;\n else if (stricmp(lastToken, \"Tab\") == 0) vk = VK_TAB;\n else if (stricmp(lastToken, \"Enter\") == 0) vk = VK_RETURN;\n else if (stricmp(lastToken, \"Esc\") == 0) vk = VK_ESCAPE;\n else if (stricmp(lastToken, \"Space\") == 0) vk = VK_SPACE;\n else if (stricmp(lastToken, \"PageUp\") == 0) vk = VK_PRIOR;\n else if (stricmp(lastToken, \"PageDown\") == 0) vk = VK_NEXT;\n else if (stricmp(lastToken, \"End\") == 0) vk = VK_END;\n else if (stricmp(lastToken, \"Home\") == 0) vk = VK_HOME;\n else if (stricmp(lastToken, \"Left\") == 0) vk = VK_LEFT;\n else if (stricmp(lastToken, \"Up\") == 0) vk = VK_UP;\n else if (stricmp(lastToken, \"Right\") == 0) vk = VK_RIGHT;\n else if (stricmp(lastToken, \"Down\") == 0) vk = VK_DOWN;\n else if (stricmp(lastToken, \"Insert\") == 0) vk = VK_INSERT;\n else if (stricmp(lastToken, \"Delete\") == 0) vk = VK_DELETE;\n else if (stricmp(lastToken, \"Num0\") == 0) vk = VK_NUMPAD0;\n else if (stricmp(lastToken, \"Num1\") == 0) vk = VK_NUMPAD1;\n else if (stricmp(lastToken, \"Num2\") == 0) vk = VK_NUMPAD2;\n else if (stricmp(lastToken, \"Num3\") == 0) vk = VK_NUMPAD3;\n else if (stricmp(lastToken, \"Num4\") == 0) vk = VK_NUMPAD4;\n else if (stricmp(lastToken, \"Num5\") == 0) vk = VK_NUMPAD5;\n else if (stricmp(lastToken, \"Num6\") == 0) vk = VK_NUMPAD6;\n else if (stricmp(lastToken, \"Num7\") == 0) vk = VK_NUMPAD7;\n else if (stricmp(lastToken, \"Num8\") == 0) vk = VK_NUMPAD8;\n else if (stricmp(lastToken, \"Num9\") == 0) vk = VK_NUMPAD9;\n else if (stricmp(lastToken, \"Num*\") == 0) vk = VK_MULTIPLY;\n else if (stricmp(lastToken, \"Num+\") == 0) vk = VK_ADD;\n else if (stricmp(lastToken, \"Num-\") == 0) vk = VK_SUBTRACT;\n else if (stricmp(lastToken, \"Num.\") == 0) vk = VK_DECIMAL;\n else if (stricmp(lastToken, \"Num/\") == 0) vk = VK_DIVIDE;\n // 检查十六进制格式\n else if (strncmp(lastToken, \"0x\", 2) == 0) {\n vk = (BYTE)strtol(lastToken, NULL, 16);\n }\n }\n \n return MAKEWORD(vk, mod);\n}\n\n/**\n * @brief Read custom countdown hotkey setting from configuration file\n * @param hotkey Pointer to store the hotkey\n */\nvoid ReadCustomCountdownHotkey(WORD* hotkey) {\n if (!hotkey) return;\n \n *hotkey = 0; // 默认为0(未设置)\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_CUSTOM_COUNTDOWN=\", 24) == 0) {\n char* value = line + 24;\n // 去除末尾的换行符\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // 解析热键字符串\n *hotkey = StringToHotkey(value);\n break;\n }\n }\n \n fclose(file);\n}\n\n/**\n * @brief Write a single configuration item to the configuration file\n * @param key Configuration item key name\n * @param value Configuration item value\n * \n * Adds or updates a single configuration item in the configuration file, automatically selects section based on key name\n */\nvoid WriteConfigKeyValue(const char* key, const char* value) {\n if (!key || !value) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Determine which section to place in based on the key name\n const char* section;\n \n if (strcmp(key, \"CONFIG_VERSION\") == 0 ||\n strcmp(key, \"LANGUAGE\") == 0 ||\n strcmp(key, \"SHORTCUT_CHECK_DONE\") == 0) {\n section = INI_SECTION_GENERAL;\n }\n else if (strncmp(key, \"CLOCK_TEXT_COLOR\", 16) == 0 ||\n strncmp(key, \"FONT_FILE_NAME\", 14) == 0 ||\n strncmp(key, \"CLOCK_BASE_FONT_SIZE\", 20) == 0 ||\n strncmp(key, \"WINDOW_SCALE\", 12) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_X\", 18) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_Y\", 18) == 0 ||\n strncmp(key, \"WINDOW_TOPMOST\", 14) == 0) {\n section = INI_SECTION_DISPLAY;\n }\n else if (strncmp(key, \"CLOCK_DEFAULT_START_TIME\", 24) == 0 ||\n strncmp(key, \"CLOCK_USE_24HOUR\", 16) == 0 ||\n strncmp(key, \"CLOCK_SHOW_SECONDS\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIME_OPTIONS\", 18) == 0 ||\n strncmp(key, \"STARTUP_MODE\", 12) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_TEXT\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_ACTION\", 20) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_FILE\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_WEBSITE\", 21) == 0) {\n section = INI_SECTION_TIMER;\n }\n else if (strncmp(key, \"POMODORO_\", 9) == 0) {\n section = INI_SECTION_POMODORO;\n }\n else if (strncmp(key, \"NOTIFICATION_\", 13) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", 26) == 0) {\n section = INI_SECTION_NOTIFICATION;\n }\n else if (strncmp(key, \"HOTKEY_\", 7) == 0) {\n section = INI_SECTION_HOTKEYS;\n }\n else if (strncmp(key, \"CLOCK_RECENT_FILE\", 17) == 0) {\n section = INI_SECTION_RECENTFILES;\n }\n else if (strncmp(key, \"COLOR_OPTIONS\", 13) == 0) {\n section = INI_SECTION_COLORS;\n }\n else {\n // 其他设置放在OPTIONS节\n section = INI_SECTION_OPTIONS;\n }\n \n // 写入配置\n WriteIniString(section, key, value, config_path);\n}\n\n/** @brief Write current language setting to configuration file */\nvoid WriteConfigLanguage(int language) {\n const char* langName;\n \n // Convert language enum value to readable language name\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_ENGLISH:\n langName = \"English\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n default:\n langName = \"English\"; // Default to English\n break;\n }\n \n WriteConfigKeyValue(\"LANGUAGE\", langName);\n}\n\n/** @brief Determine if shortcut check has been performed */\nbool IsShortcutCheckDone(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n return ReadIniBool(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", FALSE, config_path);\n}\n\n/** @brief Set shortcut check status */\nvoid SetShortcutCheckDone(bool done) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // 使用INI写入方式设置状态\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", done ? \"TRUE\" : \"FALSE\", config_path);\n}\n\n/** @brief Read whether to disable notification setting from configuration file */\nvoid ReadNotificationDisabledConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n}\n\n/** @brief Write whether to disable notification configuration */\nvoid WriteConfigNotificationDisabled(BOOL disabled) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_DISABLED=\", 22) == 0) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If configuration item not found in the configuration, add it\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_DISABLED = disabled;\n}\n"], ["/Catime/src/dialog_procedure.c", "/**\n * @file dialog_procedure.c\n * @brief Implementation of dialog message handling procedures\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/audio_player.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/dialog_language.h\"\n\nstatic void DrawColorSelectButton(HDC hdc, HWND hwnd);\n\nextern char inputText[256];\n\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES];\nextern int POMODORO_TIMES_COUNT;\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nWNDPROC wpOrigEditProc;\n\nstatic HWND g_hwndAboutDlg = NULL;\nstatic HWND g_hwndErrorDlg = NULL;\nHWND g_hwndInputDialog = NULL;\nstatic WNDPROC wpOrigLoopEditProc;\n\n#define URL_GITHUB_REPO L\"https://github.com/vladelaina/Catime\"\n\nLRESULT APIENTRY EditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n static BOOL firstKeyProcessed = FALSE;\n\n switch (msg) {\n case WM_SETFOCUS:\n PostMessage(hwnd, EM_SETSEL, 0, -1);\n firstKeyProcessed = FALSE;\n break;\n\n case WM_KEYDOWN:\n if (!firstKeyProcessed) {\n firstKeyProcessed = TRUE;\n }\n\n if (wParam == VK_RETURN) {\n HWND hwndOkButton = GetDlgItem(GetParent(hwnd), CLOCK_IDC_BUTTON_OK);\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwndOkButton);\n return 0;\n }\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n\n case WM_CHAR:\n if (wParam == 1 || (wParam == 'a' || wParam == 'A') && GetKeyState(VK_CONTROL) < 0) {\n return 0;\n }\n if (wParam == VK_RETURN) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(wpOrigEditProc, hwnd, msg, wParam, lParam);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\nvoid ShowErrorDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDD_ERROR_DIALOG),\n hwndParent,\n ErrorDlgProc);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG:\n SetDlgItemTextW(hwndDlg, IDC_ERROR_TEXT,\n GetLocalizedString(L\"输入格式无效,请重新输入。\", L\"Invalid input format, please try again.\"));\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"错误\", L\"Error\"));\n return TRUE;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Input dialog procedure\n */\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n\n g_hwndInputDialog = hwndDlg;\n\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n DWORD dlgId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n\n ApplyDialogLanguage(hwndDlg, (int)dlgId);\n\n if (dlgId == CLOCK_IDD_SHORTCUT_DIALOG) {\n }\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n\n SetFocus(hwndEdit);\n\n PostMessage(hwndDlg, WM_APP+100, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+101, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+102, 0, (LPARAM)hwndEdit);\n\n SendDlgItemMessage(hwndDlg, CLOCK_IDC_EDIT, EM_SETSEL, 0, -1);\n\n SendMessage(hwndDlg, DM_SETDEFID, CLOCK_IDC_BUTTON_OK, 0);\n\n SetTimer(hwndDlg, 9999, 50, NULL);\n\n PostMessage(hwndDlg, WM_APP+103, 0, 0);\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return FALSE;\n }\n\n case WM_CLOSE: {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n\n case WM_CTLCOLOREDIT: {\n HDC hdcEdit = (HDC)wParam;\n SetBkColor(hdcEdit, RGB(0xFF, 0xFF, 0xFF));\n if (!hEditBrush) {\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n }\n return (INT_PTR)hEditBrush;\n }\n\n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, inputText, sizeof(inputText));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (inputText[0] == '\\0' || isAllSpaces) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n int total_seconds;\n if (ParseInput(inputText, &total_seconds)) {\n int dialogId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n if (dialogId == CLOCK_IDD_POMODORO_TIME_DIALOG) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_POMODORO_LOOP_DIALOG) {\n WriteConfigPomodoroLoopCount(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_STARTUP_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_SHORTCUT_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n }\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n return TRUE;\n }\n break;\n\n case WM_TIMER:\n if (wParam == 9999) {\n KillTimer(hwndDlg, 9999);\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit && IsWindow(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n return TRUE;\n }\n break;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n int dlgId = GetDlgCtrlID((HWND)lParam);\n if (dlgId == CLOCK_IDD_COLOR_DIALOG) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n } else {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n }\n return TRUE;\n }\n break;\n\n case WM_APP+100:\n case WM_APP+101:\n case WM_APP+102:\n if (lParam) {\n HWND hwndEdit = (HWND)lParam;\n if (IsWindow(hwndEdit) && IsWindowVisible(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n }\n return TRUE;\n\n case WM_APP+103:\n {\n INPUT inputs[8] = {0};\n int inputCount = 0;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n SendInput(inputCount, inputs, sizeof(INPUT));\n }\n return TRUE;\n\n case WM_DESTROY:\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n g_hwndInputDialog = NULL;\n }\n break;\n }\n return FALSE;\n}\n\nINT_PTR CALLBACK AboutDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HICON hLargeIcon = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n hLargeIcon = (HICON)LoadImage(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDI_CATIME),\n IMAGE_ICON,\n ABOUT_ICON_SIZE,\n ABOUT_ICON_SIZE,\n LR_DEFAULTCOLOR);\n\n if (hLargeIcon) {\n SendDlgItemMessage(hwndDlg, IDC_ABOUT_ICON, STM_SETICON, (WPARAM)hLargeIcon, 0);\n }\n\n ApplyDialogLanguage(hwndDlg, IDD_ABOUT_DIALOG);\n\n const wchar_t* versionFormat = GetDialogLocalizedString(IDD_ABOUT_DIALOG, IDC_VERSION_TEXT);\n if (versionFormat) {\n wchar_t versionText[256];\n StringCbPrintfW(versionText, sizeof(versionText), versionFormat, CATIME_VERSION);\n SetDlgItemTextW(hwndDlg, IDC_VERSION_TEXT, versionText);\n }\n\n SetDlgItemTextW(hwndDlg, IDC_CREDIT_LINK, GetLocalizedString(L\"特别感谢猫屋敷梨梨Official提供的图标\", L\"Special thanks to Neko House Lili Official for the icon\"));\n SetDlgItemTextW(hwndDlg, IDC_CREDITS, GetLocalizedString(L\"鸣谢\", L\"Credits\"));\n SetDlgItemTextW(hwndDlg, IDC_BILIBILI_LINK, GetLocalizedString(L\"BiliBili\", L\"BiliBili\"));\n SetDlgItemTextW(hwndDlg, IDC_GITHUB_LINK, GetLocalizedString(L\"GitHub\", L\"GitHub\"));\n SetDlgItemTextW(hwndDlg, IDC_COPYRIGHT_LINK, GetLocalizedString(L\"版权声明\", L\"Copyright Notice\"));\n SetDlgItemTextW(hwndDlg, IDC_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n const wchar_t* dateFormat = GetLocalizedString(L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\");\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), dateFormat,\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return TRUE;\n }\n\n case WM_DESTROY:\n if (hLargeIcon) {\n DestroyIcon(hLargeIcon);\n hLargeIcon = NULL;\n }\n g_hwndAboutDlg = NULL;\n break;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n g_hwndAboutDlg = NULL;\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDIT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://space.bilibili.com/26087398\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_BILIBILI_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_BILIBILI_SPACE, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_GITHUB_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_GITHUB_REPO, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDITS) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/#thanks\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_SUPPORT) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support.html\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_COPYRIGHT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime#️copyright-notice\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n break;\n\n case WM_CLOSE:\n // Close all child dialogs\n EndDialog(hwndDlg, 0);\n g_hwndAboutDlg = NULL; // Clear dialog handle\n return TRUE;\n\n case WM_CTLCOLORSTATIC:\n {\n HDC hdc = (HDC)wParam;\n HWND hwndCtl = (HWND)lParam;\n \n if (GetDlgCtrlID(hwndCtl) == IDC_CREDIT_LINK || \n GetDlgCtrlID(hwndCtl) == IDC_BILIBILI_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_GITHUB_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_CREDITS ||\n GetDlgCtrlID(hwndCtl) == IDC_COPYRIGHT_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_SUPPORT) {\n SetTextColor(hdc, 0x00D26919); // Keep the same orange color (BGR format)\n SetBkMode(hdc, TRANSPARENT);\n return (INT_PTR)GetStockObject(NULL_BRUSH);\n }\n break;\n }\n }\n return FALSE;\n}\n\n// Add DPI awareness related type definitions (if not provided by the compiler)\n#ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n// DPI_AWARENESS_CONTEXT is a HANDLE\ntypedef HANDLE DPI_AWARENESS_CONTEXT;\n// Related DPI context constants definition\n#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n#endif\n\n// Show the About dialog\nvoid ShowAboutDialog(HWND hwndParent) {\n // If an About dialog already exists, close it first\n if (g_hwndAboutDlg != NULL && IsWindow(g_hwndAboutDlg)) {\n EndDialog(g_hwndAboutDlg, 0);\n g_hwndAboutDlg = NULL;\n }\n \n // Save current DPI awareness context\n HANDLE hOldDpiContext = NULL;\n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n // Function pointer type definitions\n typedef HANDLE (WINAPI* GetThreadDpiAwarenessContextFunc)(void);\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n \n GetThreadDpiAwarenessContextFunc getThreadDpiAwarenessContextFunc = \n (GetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"GetThreadDpiAwarenessContext\");\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (getThreadDpiAwarenessContextFunc && setThreadDpiAwarenessContextFunc) {\n // Save current DPI context\n hOldDpiContext = getThreadDpiAwarenessContextFunc();\n // Set to per-monitor DPI awareness V2 mode\n setThreadDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n }\n }\n \n // Create new About dialog\n g_hwndAboutDlg = CreateDialog(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_ABOUT_DIALOG), \n hwndParent, \n AboutDlgProc);\n \n // Restore original DPI awareness context\n if (hUser32 && hOldDpiContext) {\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (setThreadDpiAwarenessContextFunc) {\n setThreadDpiAwarenessContextFunc(hOldDpiContext);\n }\n }\n \n ShowWindow(g_hwndAboutDlg, SW_SHOW);\n}\n\n// Add global variable to track pomodoro loop count setting dialog handle\nstatic HWND g_hwndPomodoroLoopDialog = NULL;\n\nvoid ShowPomodoroLoopDialog(HWND hwndParent) {\n if (!g_hwndPomodoroLoopDialog) {\n g_hwndPomodoroLoopDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_LOOP_DIALOG),\n hwndParent,\n PomodoroLoopDlgProc\n );\n if (g_hwndPomodoroLoopDialog) {\n ShowWindow(g_hwndPomodoroLoopDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroLoopDialog);\n }\n}\n\n// Add subclassing procedure for loop count edit box\nLRESULT APIENTRY LoopEditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n switch (uMsg) {\n case WM_KEYDOWN: {\n if (wParam == VK_RETURN) {\n // Send BM_CLICK message to the parent window (dialog)\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwnd);\n return 0;\n }\n // Handle Ctrl+A select all\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n }\n case WM_CHAR: {\n // Handle Ctrl+A character message to prevent alert sound\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n // Prevent Enter key from generating character messages for further processing to avoid alert sound\n if (wParam == VK_RETURN) { // VK_RETURN (0x0D) is the char code for Enter\n return 0;\n }\n break;\n }\n }\n return CallWindowProc(wpOrigLoopEditProc, hwnd, uMsg, wParam, lParam);\n}\n\n// Modify helper function to handle numeric input with spaces\nBOOL IsValidNumberInput(const wchar_t* str) {\n // Check if empty\n if (!str || !*str) {\n return FALSE;\n }\n \n BOOL hasDigit = FALSE; // Used to track if at least one digit is found\n wchar_t cleanStr[16] = {0}; // Used to store cleaned string\n int cleanIndex = 0;\n \n // Traverse string, ignore spaces, only keep digits\n for (int i = 0; str[i]; i++) {\n if (iswdigit(str[i])) {\n cleanStr[cleanIndex++] = str[i];\n hasDigit = TRUE;\n } else if (!iswspace(str[i])) { // If not a space and not a digit, then invalid\n return FALSE;\n }\n }\n \n return hasDigit; // Return TRUE as long as there is at least one digit\n}\n\n// Modify PomodoroLoopDlgProc function\nINT_PTR CALLBACK PomodoroLoopDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_LOOP_DIALOG);\n \n // Set static text\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_STATIC, GetLocalizedString(L\"请输入循环次数(1-100):\", L\"Please enter loop count (1-100):\"));\n \n // Set focus to edit box\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetFocus(hwndEdit);\n \n // Subclass edit control\n wpOrigLoopEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, \n (LONG_PTR)LoopEditSubclassProc);\n \n return FALSE;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n wchar_t input_str[16];\n GetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, input_str, sizeof(input_str)/sizeof(wchar_t));\n \n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; input_str[i]; i++) {\n if (!iswspace(input_str[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (input_str[0] == L'\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n \n // Validate input and handle spaces\n if (!IsValidNumberInput(input_str)) {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n \n // Extract digits (ignoring spaces)\n wchar_t cleanStr[16] = {0};\n int cleanIndex = 0;\n for (int i = 0; input_str[i]; i++) {\n if (iswdigit(input_str[i])) {\n cleanStr[cleanIndex++] = input_str[i];\n }\n }\n \n int new_loop_count = _wtoi(cleanStr);\n if (new_loop_count >= 1 && new_loop_count <= 100) {\n // Update configuration file and global variables\n WriteConfigPomodoroLoopCount(new_loop_count);\n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroLoopDialog = NULL;\n } else {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n break;\n\n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigLoopEditProc);\n }\n break;\n\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n return FALSE;\n}\n\n// Add global variable to track website URL dialog handle\nstatic HWND g_hwndWebsiteDialog = NULL;\n\n// Website URL input dialog procedure\nINT_PTR CALLBACK WebsiteDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n // Set dialog as modal\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n \n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // If URL already exists, prefill the edit box\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, CLOCK_TIMEOUT_WEBSITE_URL);\n }\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_WEBSITE_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n char url[MAX_PATH] = {0};\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, url, sizeof(url));\n \n // Check if the input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; url[i]; i++) {\n if (!isspace((unsigned char)url[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (url[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n // Validate URL format - simple check, should at least contain http:// or https://\n if (strncmp(url, \"http://\", 7) != 0 && strncmp(url, \"https://\", 8) != 0) {\n // Add https:// prefix\n char tempUrl[MAX_PATH] = \"https://\";\n StringCbCatA(tempUrl, sizeof(tempUrl), url);\n StringCbCopyA(url, sizeof(url), tempUrl);\n }\n \n // Update configuration\n WriteConfigTimeoutWebsite(url);\n EndDialog(hwndDlg, IDOK);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // User cancelled, don't change timeout action\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n return FALSE;\n}\n\n// Show website URL input dialog\nvoid ShowWebsiteDialog(HWND hwndParent) {\n // Use modal dialog instead of modeless dialog, so we can know whether the user confirmed or cancelled\n INT_PTR result = DialogBox(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_WEBSITE_DIALOG),\n hwndParent,\n WebsiteDialogProc\n );\n \n // Only when the user clicks OK and inputs a valid URL will IDOK be returned, at which point WebsiteDialogProc has already set CLOCK_TIMEOUT_ACTION\n // If the user cancels or closes the dialog, the timeout action won't be changed\n}\n\n// Set global variable to track the Pomodoro combination dialog handle\nstatic HWND g_hwndPomodoroComboDialog = NULL;\n\n// Add Pomodoro combination dialog procedure\nINT_PTR CALLBACK PomodoroComboDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Read current pomodoro time options from configuration and format for display\n char currentOptions[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char timeStr[32];\n int seconds = POMODORO_TIMES[i];\n \n // Format time into human-readable format\n if (seconds >= 3600) {\n int hours = seconds / 3600;\n int mins = (seconds % 3600) / 60;\n int secs = seconds % 60;\n if (mins == 0 && secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh \", hours);\n else if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm \", hours, mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm%ds \", hours, mins, secs);\n } else if (seconds >= 60) {\n int mins = seconds / 60;\n int secs = seconds % 60;\n if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm \", mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm%ds \", mins, secs);\n } else {\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%ds \", seconds);\n }\n \n StringCbCatA(currentOptions, sizeof(currentOptions), timeStr);\n }\n \n // Remove trailing space\n if (strlen(currentOptions) > 0 && currentOptions[strlen(currentOptions) - 1] == ' ') {\n currentOptions[strlen(currentOptions) - 1] = '\\0';\n }\n \n // Set edit box text\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, currentOptions);\n \n // Apply multilingual support - moved here to ensure all default text is covered\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_COMBO_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || LOWORD(wParam) == IDOK) {\n char input[256] = {0};\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, input, sizeof(input));\n \n // Parse input time format and convert to seconds array\n char *token, *saveptr;\n char input_copy[256];\n StringCbCopyA(input_copy, sizeof(input_copy), input);\n \n int times[MAX_POMODORO_TIMES] = {0};\n int times_count = 0;\n \n token = strtok_r(input_copy, \" \", &saveptr);\n while (token && times_count < MAX_POMODORO_TIMES) {\n int seconds = 0;\n if (ParseTimeInput(token, &seconds)) {\n times[times_count++] = seconds;\n }\n token = strtok_r(NULL, \" \", &saveptr);\n }\n \n if (times_count > 0) {\n // Update global variables\n POMODORO_TIMES_COUNT = times_count;\n for (int i = 0; i < times_count; i++) {\n POMODORO_TIMES[i] = times[i];\n }\n \n // Update basic pomodoro times\n if (times_count > 0) POMODORO_WORK_TIME = times[0];\n if (times_count > 1) POMODORO_SHORT_BREAK = times[1];\n if (times_count > 2) POMODORO_LONG_BREAK = times[2];\n \n // Write to configuration file\n WriteConfigPomodoroTimeOptions(times, times_count);\n }\n \n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n }\n \n return FALSE;\n}\n\nvoid ShowPomodoroComboDialog(HWND hwndParent) {\n if (!g_hwndPomodoroComboDialog) {\n g_hwndPomodoroComboDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_COMBO_DIALOG),\n hwndParent,\n PomodoroComboDialogProc\n );\n if (g_hwndPomodoroComboDialog) {\n ShowWindow(g_hwndPomodoroComboDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroComboDialog);\n }\n}\n\nBOOL ParseTimeInput(const char* input, int* seconds) {\n if (!input || !seconds) return FALSE;\n\n *seconds = 0;\n char* buffer = _strdup(input);\n if (!buffer) return FALSE;\n\n int len = strlen(buffer);\n char* pos = buffer;\n int value = 0;\n int tempSeconds = 0;\n\n while (*pos) {\n if (isdigit((unsigned char)*pos)) {\n value = 0;\n while (isdigit((unsigned char)*pos)) {\n value = value * 10 + (*pos - '0');\n pos++;\n }\n\n if (*pos == 'h' || *pos == 'H') {\n tempSeconds += value * 3600;\n pos++;\n } else if (*pos == 'm' || *pos == 'M') {\n tempSeconds += value * 60;\n pos++;\n } else if (*pos == 's' || *pos == 'S') {\n tempSeconds += value;\n pos++;\n } else if (*pos == '\\0') {\n tempSeconds += value * 60;\n } else {\n free(buffer);\n return FALSE;\n }\n } else {\n pos++;\n }\n }\n\n free(buffer);\n *seconds = tempSeconds;\n return TRUE;\n}\n\nstatic HWND g_hwndNotificationMessagesDialog = NULL;\n\nINT_PTR CALLBACK NotificationMessagesDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n\n ReadNotificationMessagesConfig();\n \n // For handling UTF-8 Chinese characters, we need to convert to Unicode\n wchar_t wideText[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT)];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL1, \n GetLocalizedString(L\"Countdown timeout message:\", L\"Countdown timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL2, \n GetLocalizedString(L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL3,\n GetLocalizedString(L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"));\n \n // Localize button text\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"OK\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"Cancel\", L\"Cancel\"));\n \n // Subclass edit boxes to support Ctrl+A for select all\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n // Save original window procedure\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Apply the same subclassing process to other edit boxes\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Select all text in the first edit box\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_EDIT1, EM_SETSEL, 0, -1);\n \n // Set focus to the first edit box\n SetFocus(GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1));\n \n return FALSE; // Return FALSE because we manually set focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n // Get text from edit boxes (Unicode method)\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Save to configuration file and update global variables\n WriteConfigNotificationMessages(timeout_msg, pomodoro_msg, cycle_complete_msg);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification message settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification message settings dialog for modifying various notification prompt texts.\n */\nvoid ShowNotificationMessagesDialog(HWND hwndParent) {\n if (!g_hwndNotificationMessagesDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationMessagesConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_MESSAGES_DIALOG), \n hwndParent, \n NotificationMessagesDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationMessagesDialog);\n }\n}\n\n// Add global variable to track notification display settings dialog handle\nstatic HWND g_hwndNotificationDisplayDialog = NULL;\n\n// Add notification display settings dialog procedure\nINT_PTR CALLBACK NotificationDisplayDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set window to topmost\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n \n // Create brushes\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n \n // Read latest configuration\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n // Set current values to edit boxes\n char buffer[32];\n \n // Display time (seconds, support decimal) - convert milliseconds to seconds\n StringCbPrintfA(buffer, sizeof(buffer), \"%.1f\", (float)NOTIFICATION_TIMEOUT_MS / 1000.0f);\n // Remove trailing .0\n if (strlen(buffer) > 2 && buffer[strlen(buffer)-2] == '.' && buffer[strlen(buffer)-1] == '0') {\n buffer[strlen(buffer)-2] = '\\0';\n }\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, buffer);\n \n // Opacity (percentage)\n StringCbPrintfA(buffer, sizeof(buffer), \"%d\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, buffer);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_LABEL, \n GetLocalizedString(L\"Notification display time (sec):\", L\"Notification display time (sec):\"));\n \n // Modify edit box style, remove ES_NUMBER to allow decimal point\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n LONG style = GetWindowLong(hEditTime, GWL_STYLE);\n SetWindowLong(hEditTime, GWL_STYLE, style & ~ES_NUMBER);\n \n // Subclass edit boxes to support Enter key submission and input restrictions\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Set focus to time edit box\n SetFocus(hEditTime);\n \n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n char timeStr[32] = {0};\n char opacityStr[32] = {0};\n \n // Get user input values\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, timeStr, sizeof(timeStr));\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, opacityStr, sizeof(opacityStr));\n \n // Use more robust method to replace Chinese period\n // First get the text in Unicode format\n wchar_t wTimeStr[32] = {0};\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, wTimeStr, sizeof(wTimeStr)/sizeof(wchar_t));\n \n // Replace Chinese punctuation marks in Unicode text\n for (int i = 0; wTimeStr[i] != L'\\0'; i++) {\n // Recognize various punctuation marks as decimal point\n if (wTimeStr[i] == L'。' || // Chinese period\n wTimeStr[i] == L',' || // Chinese comma\n wTimeStr[i] == L',' || // English comma\n wTimeStr[i] == L'·' || // Chinese middle dot\n wTimeStr[i] == L'`' || // Backtick\n wTimeStr[i] == L':' || // Chinese colon\n wTimeStr[i] == L':' || // English colon\n wTimeStr[i] == L';' || // Chinese semicolon\n wTimeStr[i] == L';' || // English semicolon\n wTimeStr[i] == L'/' || // Forward slash\n wTimeStr[i] == L'\\\\' || // Backslash\n wTimeStr[i] == L'~' || // Tilde\n wTimeStr[i] == L'~' || // Full-width tilde\n wTimeStr[i] == L'、' || // Chinese enumeration comma\n wTimeStr[i] == L'.') { // Full-width period\n wTimeStr[i] = L'.'; // Replace with English decimal point\n }\n }\n \n // Convert processed Unicode text back to ASCII\n WideCharToMultiByte(CP_ACP, 0, wTimeStr, -1, \n timeStr, sizeof(timeStr), NULL, NULL);\n \n // Parse time (seconds) and convert to milliseconds\n float timeInSeconds = atof(timeStr);\n int timeInMs = (int)(timeInSeconds * 1000.0f);\n \n // Allow time to be set to 0 (no notification) or at least 100 milliseconds\n if (timeInMs > 0 && timeInMs < 100) timeInMs = 100;\n \n // Parse opacity\n int opacity = atoi(opacityStr);\n \n // Ensure opacity is in range 1-100\n if (opacity < 1) opacity = 1;\n if (opacity > 100) opacity = 100;\n \n // Write to configuration\n WriteConfigNotificationTimeout(timeInMs);\n WriteConfigNotificationOpacity(opacity);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n }\n break;\n \n // Add handling for WM_CLOSE message\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n HWND hEditOpacity = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEditOpacity, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification display settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification display settings dialog for modifying notification display time and opacity.\n */\nvoid ShowNotificationDisplayDialog(HWND hwndParent) {\n if (!g_hwndNotificationDisplayDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_DISPLAY_DIALOG), \n hwndParent, \n NotificationDisplayDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationDisplayDialog);\n }\n}\n\n// Add global variable to track the integrated notification settings dialog handle\nstatic HWND g_hwndNotificationSettingsDialog = NULL;\n\n/**\n * @brief Audio playback completion callback function\n * @param hwnd Window handle\n * \n * When audio playback completes, changes \"Stop\" button back to \"Test\" button\n */\nstatic void OnAudioPlaybackComplete(HWND hwnd) {\n if (hwnd && IsWindow(hwnd)) {\n const wchar_t* testText = GetLocalizedString(L\"Test\", L\"Test\");\n SetDlgItemTextW(hwnd, IDC_TEST_SOUND_BUTTON, testText);\n \n // Get dialog data\n HWND hwndTestButton = GetDlgItem(hwnd, IDC_TEST_SOUND_BUTTON);\n \n // Send WM_SETTEXT message to update button text\n if (hwndTestButton && IsWindow(hwndTestButton)) {\n SendMessageW(hwndTestButton, WM_SETTEXT, 0, (LPARAM)testText);\n }\n \n // Update global playback state\n if (g_hwndNotificationSettingsDialog == hwnd) {\n // Send message to dialog to notify state change\n SendMessage(hwnd, WM_APP + 100, 0, 0);\n }\n }\n}\n\n/**\n * @brief Populate audio dropdown box\n * @param hwndDlg Dialog handle\n */\nstatic void PopulateSoundComboBox(HWND hwndDlg) {\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n if (!hwndCombo) return;\n\n // Clear dropdown list\n SendMessage(hwndCombo, CB_RESETCONTENT, 0, 0);\n\n // Add \"None\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"None\", L\"None\"));\n \n // Add \"System Beep\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"System Beep\", L\"System Beep\"));\n\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to wide character path\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n\n // Build search path\n wchar_t wSearchPath[MAX_PATH];\n StringCbPrintfW(wSearchPath, sizeof(wSearchPath), L\"%s\\\\*.*\", wAudioPath);\n\n // Find audio files - using Unicode version of API\n WIN32_FIND_DATAW find_data;\n HANDLE hFind = FindFirstFileW(wSearchPath, &find_data);\n if (hFind != INVALID_HANDLE_VALUE) {\n do {\n // Check file extension\n wchar_t* ext = wcsrchr(find_data.cFileName, L'.');\n if (ext && (\n _wcsicmp(ext, L\".flac\") == 0 ||\n _wcsicmp(ext, L\".mp3\") == 0 ||\n _wcsicmp(ext, L\".wav\") == 0\n )) {\n // Add Unicode filename directly to dropdown\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)find_data.cFileName);\n }\n } while (FindNextFileW(hFind, &find_data));\n FindClose(hFind);\n }\n\n // Set currently selected audio file\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n // Check if it's the special system beep marker\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n // Select \"System Beep\" option (index 1)\n SendMessage(hwndCombo, CB_SETCURSEL, 1, 0);\n } else {\n wchar_t wSoundFile[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, NOTIFICATION_SOUND_FILE, -1, wSoundFile, MAX_PATH);\n \n // Get filename part\n wchar_t* fileName = wcsrchr(wSoundFile, L'\\\\');\n if (fileName) fileName++;\n else fileName = wSoundFile;\n \n // Find and select the file in dropdown\n int index = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)fileName);\n if (index != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, index, 0);\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n }\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n}\n\n/**\n * @brief Integrated notification settings dialog procedure\n * @param hwndDlg Dialog handle\n * @param msg Message type\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return INT_PTR Message processing result\n * \n * Integrates notification content and notification display settings in a unified interface\n */\nINT_PTR CALLBACK NotificationSettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static BOOL isPlaying = FALSE; // Add a static variable to track playback status\n static int originalVolume = 0; // Add a static variable to store original volume\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Read latest configuration to global variables\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n // Save original volume value for restoration when canceling\n originalVolume = NOTIFICATION_SOUND_VOLUME;\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG);\n \n // Set notification message text - using Unicode functions\n wchar_t wideText[256];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Set notification display time\n SYSTEMTIME st = {0};\n GetLocalTime(&st);\n \n // Read notification disabled setting\n ReadNotificationDisabledConfig();\n \n // Set checkbox based on disabled state\n CheckDlgButton(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK, NOTIFICATION_DISABLED ? BST_CHECKED : BST_UNCHECKED);\n \n // Enable/disable time control based on state\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !NOTIFICATION_DISABLED);\n \n // Set time control value - display actual configured time regardless of disabled state\n int totalSeconds = NOTIFICATION_TIMEOUT_MS / 1000;\n st.wHour = totalSeconds / 3600;\n st.wMinute = (totalSeconds % 3600) / 60;\n st.wSecond = totalSeconds % 60;\n \n // Set time control's initial value\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_SETSYSTEMTIME, \n GDT_VALID, (LPARAM)&st);\n\n // Set notification opacity slider\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n SendMessage(hwndOpacitySlider, TBM_SETRANGE, TRUE, MAKELONG(1, 100));\n SendMessage(hwndOpacitySlider, TBM_SETPOS, TRUE, NOTIFICATION_MAX_OPACITY);\n \n // Update opacity text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n // Set notification type radio buttons\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_OS:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_OS, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, BST_CHECKED);\n break;\n }\n \n // Populate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Set volume slider\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n SendMessage(hwndSlider, TBM_SETRANGE, TRUE, MAKELONG(0, 100));\n SendMessage(hwndSlider, TBM_SETPOS, TRUE, NOTIFICATION_SOUND_VOLUME);\n \n // Update volume text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", NOTIFICATION_SOUND_VOLUME);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Reset playback state on initialization\n isPlaying = FALSE;\n \n // Set audio playback completion callback\n SetAudioPlaybackCompleteCallback(hwndDlg, OnAudioPlaybackComplete);\n \n // Save dialog handle\n g_hwndNotificationSettingsDialog = hwndDlg;\n \n return TRUE;\n }\n \n case WM_HSCROLL: {\n // Handle slider drag events\n if (GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER) == (HWND)lParam) {\n // Get slider's current position\n int volume = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update volume percentage text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", volume);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Apply volume setting in real-time\n SetAudioVolume(volume);\n \n return TRUE;\n }\n else if (GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT) == (HWND)lParam) {\n // Get slider's current position\n int opacity = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update opacity percentage text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", opacity);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND:\n // Handle notification disable checkbox state change\n if (LOWORD(wParam) == IDC_DISABLE_NOTIFICATION_CHECK && HIWORD(wParam) == BN_CLICKED) {\n BOOL isChecked = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !isChecked);\n return TRUE;\n }\n else if (LOWORD(wParam) == IDOK) {\n // Get notification message text - using Unicode functions\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Get notification display time\n SYSTEMTIME st = {0};\n \n // Check if notification disable checkbox is checked\n BOOL isDisabled = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n \n // Save disabled state\n NOTIFICATION_DISABLED = isDisabled;\n WriteConfigNotificationDisabled(isDisabled);\n \n // Get notification time settings\n // Get notification time settings\n if (SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_GETSYSTEMTIME, 0, (LPARAM)&st) == GDT_VALID) {\n // Calculate total seconds: hours*3600 + minutes*60 + seconds\n int totalSeconds = st.wHour * 3600 + st.wMinute * 60 + st.wSecond;\n \n if (totalSeconds == 0) {\n // If time is 00:00:00, set to 0 (meaning disable notifications)\n NOTIFICATION_TIMEOUT_MS = 0;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n \n } else if (!isDisabled) {\n // Only update non-zero notification time if not disabled\n NOTIFICATION_TIMEOUT_MS = totalSeconds * 1000;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n }\n }\n // If notifications are disabled, don't modify notification time configuration\n \n // Get notification opacity (from slider)\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n int opacity = (int)SendMessage(hwndOpacitySlider, TBM_GETPOS, 0, 0);\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n \n // Get notification type\n if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_OS)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n }\n \n // Get selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n if (index > 0) { // 0 is \"None\" option\n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Check if \"System Beep\" is selected\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker to represent system beep\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n } else {\n NOTIFICATION_SOUND_FILE[0] = '\\0';\n }\n \n // Get volume slider position\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n NOTIFICATION_SOUND_VOLUME = volume;\n \n // Save all settings\n WriteConfigNotificationMessages(\n timeout_msg,\n pomodoro_msg,\n cycle_complete_msg\n );\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n WriteConfigNotificationOpacity(NOTIFICATION_MAX_OPACITY);\n WriteConfigNotificationType(NOTIFICATION_TYPE);\n WriteConfigNotificationSound(NOTIFICATION_SOUND_FILE);\n WriteConfigNotificationVolume(NOTIFICATION_SOUND_VOLUME);\n \n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Restore original volume setting\n NOTIFICATION_SOUND_VOLUME = originalVolume;\n \n // Reapply original volume\n SetAudioVolume(originalVolume);\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDC_TEST_SOUND_BUTTON) {\n if (!isPlaying) {\n // Currently not playing, start playback and change button text to \"Stop\"\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n \n if (index > 0) { // 0 is the \"None\" option\n // Get current slider volume and apply it\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n SetAudioVolume(volume);\n \n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Temporarily save current audio settings\n char tempSoundFile[MAX_PATH];\n StringCbCopyA(tempSoundFile, sizeof(tempSoundFile), NOTIFICATION_SOUND_FILE);\n \n // Temporarily set audio file\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n \n // Play audio\n if (PlayNotificationSound(hwndDlg)) {\n // Playback successful, change button text to \"Stop\"\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Stop\", L\"Stop\"));\n isPlaying = TRUE;\n }\n \n // Restore previous settings\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), tempSoundFile);\n }\n } else {\n // Currently playing, stop playback and restore button text\n StopNotificationSound();\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Test\", L\"Test\"));\n isPlaying = FALSE;\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDC_OPEN_SOUND_DIR_BUTTON) {\n // Get audio directory path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Ensure directory exists\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n \n // Open directory\n ShellExecuteW(hwndDlg, L\"open\", wAudioPath, NULL, NULL, SW_SHOWNORMAL);\n \n // Record currently selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Try to restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n } else {\n // If previous selection not found, default to \"None\"\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0);\n }\n }\n \n return TRUE;\n } else if (LOWORD(wParam) == IDC_NOTIFICATION_SOUND_COMBO && HIWORD(wParam) == CBN_DROPDOWN) {\n // When dropdown is about to open, reload file list\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n \n // Record currently selected file\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n }\n }\n \n return TRUE;\n }\n break;\n \n // Add custom message handling for audio playback completion notification\n case WM_APP + 100:\n // Audio playback is complete, update button state\n isPlaying = FALSE;\n return TRUE;\n \n case WM_CLOSE:\n // Make sure to stop playback when closing dialog\n if (isPlaying) {\n StopNotificationSound();\n }\n \n // Clean up callback\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Clean up callback when dialog is destroyed\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n g_hwndNotificationSettingsDialog = NULL;\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Display integrated notification settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays a unified dialog that includes both notification content and display settings\n */\nvoid ShowNotificationSettingsDialog(HWND hwndParent) {\n if (!g_hwndNotificationSettingsDialog) {\n // Ensure the latest configuration values are read first\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG), \n hwndParent, \n NotificationSettingsDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationSettingsDialog);\n }\n}"], ["/Catime/src/timer_events.c", "/**\n * @file timer_events.c\n * @brief Implementation of timer event handling\n * \n * This file implements the functionality related to the application's timer event handling,\n * including countdown and count-up mode event processing.\n */\n\n#include \n#include \n#include \"../include/timer_events.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \"../include/window.h\"\n#include \"audio_player.h\" // Include header reference\n\n// Maximum capacity of Pomodoro time list\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Index of the currently executing Pomodoro time\nint current_pomodoro_time_index = 0;\n\n// Define current_pomodoro_phase variable, which is declared as extern in pomodoro.h\nPOMODORO_PHASE current_pomodoro_phase = POMODORO_PHASE_IDLE;\n\n// Number of completed Pomodoro cycles\nint complete_pomodoro_cycles = 0;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\n\n// Variable declarations imported from main.c, for timeout actions\nextern int elapsed_time;\nextern BOOL message_shown;\n\n// Custom message text imported from config.c\nextern char CLOCK_TIMEOUT_MESSAGE_TEXT[100];\nextern char POMODORO_TIMEOUT_MESSAGE_TEXT[100]; // New Pomodoro-specific prompt\nextern char POMODORO_CYCLE_COMPLETE_TEXT[100];\n\n// Define ClockState type\ntypedef enum {\n CLOCK_STATE_IDLE,\n CLOCK_STATE_COUNTDOWN,\n CLOCK_STATE_COUNTUP,\n CLOCK_STATE_POMODORO\n} ClockState;\n\n// Define PomodoroState type\ntypedef struct {\n BOOL isLastCycle;\n int cycleIndex;\n int totalCycles;\n} PomodoroState;\n\nextern HWND g_hwnd; // Main window handle\nextern ClockState g_clockState;\nextern PomodoroState g_pomodoroState;\n\n// Timer behavior function declarations\nextern void ShowTrayNotification(HWND hwnd, const char* message);\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void OpenFileByPath(const char* filePath);\nextern void OpenWebsite(const char* url);\nextern void SleepComputer(void);\nextern void ShutdownComputer(void);\nextern void RestartComputer(void);\nextern void SetTimeDisplay(void);\nextern void ShowCountUp(HWND hwnd);\n\n// Add external function declaration to the beginning of the file or before the function\nextern void StopNotificationSound(void);\n\n/**\n * @brief Convert UTF-8 encoded char* string to wchar_t* string\n * @param utf8String Input UTF-8 string\n * @return Converted wchar_t* string, memory needs to be freed with free() after use. Returns NULL if conversion fails.\n */\nstatic wchar_t* Utf8ToWideChar(const char* utf8String) {\n if (!utf8String || utf8String[0] == '\\0') {\n return NULL; // Return NULL to handle empty strings or NULL pointers\n }\n int size_needed = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, NULL, 0);\n if (size_needed == 0) {\n // Conversion failed\n return NULL;\n }\n wchar_t* wideString = (wchar_t*)malloc(size_needed * sizeof(wchar_t));\n if (!wideString) {\n // Memory allocation failed\n return NULL;\n }\n int result = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, wideString, size_needed);\n if (result == 0) {\n // Conversion failed\n free(wideString);\n return NULL;\n }\n return wideString;\n}\n\n/**\n * @brief Convert wide character string to UTF-8 encoded regular string and display notification\n * @param hwnd Window handle\n * @param message Wide character string message to display (read from configuration and converted)\n */\nstatic void ShowLocalizedNotification(HWND hwnd, const wchar_t* message) {\n // Don't display if message is empty\n if (!message || message[0] == L'\\0') {\n return;\n }\n\n // Calculate required buffer size\n int size_needed = WideCharToMultiByte(CP_UTF8, 0, message, -1, NULL, 0, NULL, NULL);\n if (size_needed == 0) return; // Conversion failed\n\n // Allocate memory\n char* utf8Msg = (char*)malloc(size_needed);\n if (utf8Msg) {\n // Convert to UTF-8\n int result = WideCharToMultiByte(CP_UTF8, 0, message, -1, utf8Msg, size_needed, NULL, NULL);\n\n if (result > 0) {\n // Display notification using the new ShowNotification function\n ShowNotification(hwnd, utf8Msg);\n \n // If timeout action is MESSAGE, play notification audio\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE) {\n // Read the latest audio settings\n ReadNotificationSoundConfig();\n \n // Play notification audio\n PlayNotificationSound(hwnd);\n }\n }\n\n // Free memory\n free(utf8Msg);\n }\n}\n\n/**\n * @brief Set Pomodoro to work phase\n * \n * Reset all timer counts and set Pomodoro to work phase\n */\nvoid InitializePomodoro(void) {\n // Use existing enum value POMODORO_PHASE_WORK instead of POMODORO_PHASE_RUNNING\n current_pomodoro_phase = POMODORO_PHASE_WORK;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Set initial countdown to the first time value\n if (POMODORO_TIMES_COUNT > 0) {\n CLOCK_TOTAL_TIME = POMODORO_TIMES[0];\n } else {\n // If no time is configured, use default 25 minutes\n CLOCK_TOTAL_TIME = 1500;\n }\n \n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n}\n\n/**\n * @brief Handle timer messages\n * @param hwnd Window handle\n * @param wp Message parameter\n * @return BOOL Whether the message was handled\n */\nBOOL HandleTimerEvent(HWND hwnd, WPARAM wp) {\n if (wp == 1) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // In current time display mode, reset the last displayed second on each timer trigger to ensure the latest time is displayed\n extern int last_displayed_second;\n last_displayed_second = -1; // Force reset of seconds cache to ensure the latest system time is displayed each time\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n return TRUE;\n }\n\n // If timer is paused, don't update time\n if (CLOCK_IS_PAUSED) {\n return TRUE;\n }\n\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time++;\n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n if (countdown_elapsed_time < CLOCK_TOTAL_TIME) {\n countdown_elapsed_time++;\n if (countdown_elapsed_time >= CLOCK_TOTAL_TIME && !countdown_message_shown) {\n countdown_message_shown = TRUE;\n\n // Re-read message text from config file before displaying notification\n ReadNotificationMessagesConfig();\n // Force re-read notification type config to ensure latest settings are used\n ReadNotificationTypeConfig();\n \n // Variable declaration before branches to ensure availability in all branches\n wchar_t* timeoutMsgW = NULL;\n\n // Check if in Pomodoro mode - must meet all three conditions:\n // 1. Current Pomodoro phase is not IDLE \n // 2. Pomodoro time configuration is valid\n // 3. Current countdown total time matches the time at current index in the Pomodoro time list\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE && \n POMODORO_TIMES_COUNT > 0 && \n current_pomodoro_time_index < POMODORO_TIMES_COUNT &&\n CLOCK_TOTAL_TIME == POMODORO_TIMES[current_pomodoro_time_index]) {\n \n // Use Pomodoro-specific prompt message\n timeoutMsgW = Utf8ToWideChar(POMODORO_TIMEOUT_MESSAGE_TEXT);\n \n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"番茄钟时间到!\"); // Fallback\n }\n \n // Move to next time period\n current_pomodoro_time_index++;\n \n // Check if a complete cycle has been finished\n if (current_pomodoro_time_index >= POMODORO_TIMES_COUNT) {\n // Reset index back to the first time\n current_pomodoro_time_index = 0;\n \n // Increase completed cycle count\n complete_pomodoro_cycles++;\n \n // Check if all configured loop counts have been completed\n if (complete_pomodoro_cycles >= POMODORO_LOOP_COUNT) {\n // All loop counts completed, end Pomodoro\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_TOTAL_TIME = 0;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n \n // Try to read and convert completion message from config\n wchar_t* cycleCompleteMsgW = Utf8ToWideChar(POMODORO_CYCLE_COMPLETE_TEXT);\n // Display completion prompt (using config or default value)\n if (cycleCompleteMsgW) {\n ShowLocalizedNotification(hwnd, cycleCompleteMsgW);\n free(cycleCompleteMsgW); // Free completion message memory\n } else {\n ShowLocalizedNotification(hwnd, L\"所有番茄钟循环完成!\"); // Fallback\n }\n \n // Switch to idle state - add the following code\n CLOCK_COUNT_UP = FALSE; // Ensure not in count-up mode\n CLOCK_SHOW_CURRENT_TIME = FALSE; // Ensure not in current time display mode\n message_shown = TRUE; // Mark message as shown\n \n // Force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n KillTimer(hwnd, 1);\n if (timeoutMsgW) free(timeoutMsgW); // Free timeout message memory\n return TRUE;\n }\n }\n \n // Set countdown for next time period\n CLOCK_TOTAL_TIME = POMODORO_TIMES[current_pomodoro_time_index];\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n \n // If it's the first time period in a new round, display cycle prompt\n if (current_pomodoro_time_index == 0 && complete_pomodoro_cycles > 0) {\n wchar_t cycleMsg[100];\n // GetLocalizedString needs to be reconsidered, or hardcode English/Chinese\n // Temporarily keep the original approach, but ideally should be configurable\n const wchar_t* formatStr = GetLocalizedString(L\"开始第 %d 轮番茄钟\", L\"Starting Pomodoro cycle %d\");\n swprintf(cycleMsg, 100, formatStr, complete_pomodoro_cycles + 1);\n ShowLocalizedNotification(hwnd, cycleMsg); // Call the modified function\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // Not in Pomodoro mode, or switched to normal countdown mode\n // Use normal countdown prompt message\n timeoutMsgW = Utf8ToWideChar(CLOCK_TIMEOUT_MESSAGE_TEXT);\n \n // Only display notification message if timeout action is not open file, lock, shutdown, or restart\n if (CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_OPEN_FILE && \n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_LOCK &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SHUTDOWN &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_RESTART &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SLEEP) {\n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"时间到!\"); // Fallback\n }\n }\n \n // If current mode is not Pomodoro (manually switched to normal countdown), ensure not to return to Pomodoro cycle\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n (current_pomodoro_time_index >= POMODORO_TIMES_COUNT ||\n CLOCK_TOTAL_TIME != POMODORO_TIMES[current_pomodoro_time_index])) {\n // If switched to normal countdown, reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n // If sleep option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute sleep command\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n return TRUE;\n }\n \n // If shutdown option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute shutdown command\n system(\"shutdown /s /t 0\");\n return TRUE;\n }\n \n // If restart option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute restart command\n system(\"shutdown /r /t 0\");\n return TRUE;\n }\n \n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n // Notification already displayed, no additional operation needed\n break;\n case TIMEOUT_ACTION_LOCK:\n LockWorkStation();\n break;\n case TIMEOUT_ACTION_OPEN_FILE: {\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0) {\n wchar_t wPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_FILE_PATH, -1, wPath, MAX_PATH);\n \n HINSTANCE result = ShellExecuteW(NULL, L\"open\", wPath, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)result <= 32) {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"无法打开文件\", L\"Failed to open file\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case TIMEOUT_ACTION_SHOW_TIME:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to count-up mode and reset\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countup_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set Pomodoro state to idle\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n wchar_t wideUrl[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_WEBSITE_URL, -1, wideUrl, MAX_PATH);\n ShellExecuteW(NULL, L\"open\", wideUrl, NULL, NULL, SW_NORMAL);\n }\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n }\n\n // Free converted wide string memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return TRUE;\n }\n return FALSE;\n}\n\nvoid OnTimerTimeout(HWND hwnd) {\n // Execute different behaviors based on timeout action\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE: {\n char utf8Msg[256] = {0};\n \n // Select different prompt messages based on current state\n if (g_clockState == CLOCK_STATE_POMODORO) {\n // Check if Pomodoro has completed all cycles\n if (g_pomodoroState.isLastCycle && g_pomodoroState.cycleIndex >= g_pomodoroState.totalCycles - 1) {\n strncpy(utf8Msg, POMODORO_CYCLE_COMPLETE_TEXT, sizeof(utf8Msg) - 1);\n } else {\n strncpy(utf8Msg, POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n } else {\n strncpy(utf8Msg, CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n \n utf8Msg[sizeof(utf8Msg) - 1] = '\\0'; // Ensure string ends with null character\n \n // Display custom prompt message\n ShowNotification(hwnd, utf8Msg);\n \n // Read latest audio settings and play alert sound\n ReadNotificationSoundConfig();\n PlayNotificationSound(hwnd);\n \n break;\n }\n case TIMEOUT_ACTION_RUN_COMMAND: {\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n case TIMEOUT_ACTION_HTTP_REQUEST: {\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n\n }\n}\n\n// Add missing global variable definitions (if not defined elsewhere)\n#ifndef STUB_VARIABLES_DEFINED\n#define STUB_VARIABLES_DEFINED\n// Main window handle\nHWND g_hwnd = NULL;\n// Current clock state\nClockState g_clockState = CLOCK_STATE_IDLE;\n// Pomodoro state\nPomodoroState g_pomodoroState = {FALSE, 0, 1};\n#endif\n\n// Add stub function definitions if needed\n#ifndef STUB_FUNCTIONS_DEFINED\n#define STUB_FUNCTIONS_DEFINED\n__attribute__((weak)) void SleepComputer(void) {\n // This is a weak symbol definition, if there's an actual implementation elsewhere, that implementation will be used\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n}\n\n__attribute__((weak)) void ShutdownComputer(void) {\n system(\"shutdown /s /t 0\");\n}\n\n__attribute__((weak)) void RestartComputer(void) {\n system(\"shutdown /r /t 0\");\n}\n\n__attribute__((weak)) void SetTimeDisplay(void) {\n // Stub implementation for setting time display\n}\n\n__attribute__((weak)) void ShowCountUp(HWND hwnd) {\n // Stub implementation for showing count-up\n}\n#endif\n"], ["/Catime/src/tray_menu.c", "/**\n * @file tray_menu.c\n * @brief Implementation of system tray menu functionality\n * \n * This file implements the system tray menu functionality for the application, including:\n * - Right-click menu and its submenus\n * - Color selection menu\n * - Font settings menu\n * - Timeout action settings\n * - Pomodoro functionality\n * - Preset time management\n * - Multi-language interface support\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/timer.h\"\n#include \"../resource/resource.h\"\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_USE_24HOUR;\nextern BOOL CLOCK_SHOW_SECONDS;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_EDIT_MODE;\nextern char CLOCK_STARTUP_MODE[20];\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\nextern int time_options[];\nextern int time_options_count;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern char CLOCK_TIMEOUT_FILE_PATH[MAX_PATH];\nextern char CLOCK_TIMEOUT_TEXT[50];\nextern BOOL CLOCK_WINDOW_TOPMOST; ///< Whether the window is always on top\n\n// Add Pomodoro related variable declarations\nextern int POMODORO_WORK_TIME; ///< Work time (seconds)\nextern int POMODORO_SHORT_BREAK; ///< Short break time (seconds)\nextern int POMODORO_LONG_BREAK; ///< Long break time (seconds)\nextern int POMODORO_LOOP_COUNT; ///< Loop count\n\n// Pomodoro time array and count variables\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Add to external variable declaration section\nextern char CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH]; ///< URL for timeout open website\nextern int current_pomodoro_time_index; // Current Pomodoro time index\nextern POMODORO_PHASE current_pomodoro_phase; // Pomodoro phase\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t size);\nextern BOOL IsAutoStartEnabled(void);\nextern void WriteConfigStartupMode(const char* mode);\nextern void ClearColorOptions(void);\nextern void AddColorOption(const char* color);\n/// @}\n\n/**\n * @brief Read timeout action settings from configuration file\n * \n * Read the timeout action settings saved in the configuration file and update the global variable CLOCK_TIMEOUT_ACTION\n */\nvoid ReadTimeoutActionFromConfig() {\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"TIMEOUT_ACTION=\", 15) == 0) {\n int action = 0;\n sscanf(line, \"TIMEOUT_ACTION=%d\", &action);\n CLOCK_TIMEOUT_ACTION = (TimeoutActionType)action;\n break;\n }\n }\n fclose(configFile);\n }\n}\n\n/**\n * @brief Recent file structure\n * \n * Store information about recently used files, including full path and display name\n */\ntypedef struct {\n char path[MAX_PATH]; ///< Full file path\n char name[MAX_PATH]; ///< File display name (may be truncated)\n} RecentFile;\n\nextern RecentFile CLOCK_RECENT_FILES[];\nextern int CLOCK_RECENT_FILES_COUNT;\n\n/**\n * @brief Format Pomodoro time to wide string\n * @param seconds Number of seconds\n * @param buffer Output buffer\n * @param bufferSize Buffer size\n */\nstatic void FormatPomodoroTime(int seconds, wchar_t* buffer, size_t bufferSize) {\n int minutes = seconds / 60;\n int secs = seconds % 60;\n int hours = minutes / 60;\n minutes %= 60;\n \n if (hours > 0) {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d:%02d\", hours, minutes, secs);\n } else {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d\", minutes, secs);\n }\n}\n\n/**\n * @brief Truncate long file names\n * \n * @param fileName Original file name\n * @param truncated Truncated file name buffer\n * @param maxLen Maximum display length (excluding terminator)\n * \n * If the file name exceeds the specified length, it uses the format \"first 12 characters...last 12 characters.extension\" for intelligent truncation.\n * This function preserves the file extension to ensure users can identify the file type.\n */\nvoid TruncateFileName(const wchar_t* fileName, wchar_t* truncated, size_t maxLen) {\n if (!fileName || !truncated || maxLen <= 7) return; // At least need to display \"x...y\"\n \n size_t nameLen = wcslen(fileName);\n if (nameLen <= maxLen) {\n // File name does not exceed the length limit, copy directly\n wcscpy(truncated, fileName);\n return;\n }\n \n // Find the position of the last dot (extension separator)\n const wchar_t* lastDot = wcsrchr(fileName, L'.');\n const wchar_t* fileNameNoExt = fileName;\n const wchar_t* ext = L\"\";\n size_t nameNoExtLen = nameLen;\n size_t extLen = 0;\n \n if (lastDot && lastDot != fileName) {\n // Has valid extension\n ext = lastDot; // Extension including dot\n extLen = wcslen(ext);\n nameNoExtLen = lastDot - fileName; // Length of file name without extension\n }\n \n // If the pure file name length is less than or equal to 27 characters (12+3+12), use the old truncation method\n if (nameNoExtLen <= 27) {\n // Simple truncation of main file name, preserving extension\n wcsncpy(truncated, fileName, maxLen - extLen - 3);\n truncated[maxLen - extLen - 3] = L'\\0';\n wcscat(truncated, L\"...\");\n wcscat(truncated, ext);\n return;\n }\n \n // Use new truncation method: first 12 characters + ... + last 12 characters + extension\n wchar_t buffer[MAX_PATH];\n \n // Copy first 12 characters\n wcsncpy(buffer, fileName, 12);\n buffer[12] = L'\\0';\n \n // Add ellipsis\n wcscat(buffer, L\"...\");\n \n // Copy last 12 characters (excluding extension part)\n wcsncat(buffer, fileName + nameNoExtLen - 12, 12);\n \n // Add extension\n wcscat(buffer, ext);\n \n // Copy result to output buffer\n wcscpy(truncated, buffer);\n}\n\n/**\n * @brief Display color and settings menu\n * \n * @param hwnd Window handle\n * \n * Create and display the application's main settings menu, including:\n * - Edit mode toggle\n * - Timeout action settings\n * - Preset time management\n * - Startup mode settings\n * - Font selection\n * - Color settings\n * - Language selection\n * - Help and about information\n */\nvoid ShowColorMenu(HWND hwnd) {\n // Read timeout action settings from the configuration file before creating the menu\n ReadTimeoutActionFromConfig();\n \n // Set mouse cursor to default arrow to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n HMENU hMenu = CreatePopupMenu();\n \n // Add edit mode option\n AppendMenuW(hMenu, MF_STRING | (CLOCK_EDIT_MODE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_EDIT_MODE, \n GetLocalizedString(L\"编辑模式\", L\"Edit Mode\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Timeout action menu\n HMENU hTimeoutMenu = CreatePopupMenu();\n \n // 1. Show message\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_SHOW_MESSAGE, \n GetLocalizedString(L\"显示消息\", L\"Show Message\"));\n\n // 2. Show current time\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHOW_TIME ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_SHOW_TIME, \n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n\n // 3. Count up\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_COUNT_UP ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_COUNT_UP, \n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n\n // 4. Lock screen\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_LOCK ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LOCK_SCREEN,\n GetLocalizedString(L\"锁定屏幕\", L\"Lock Screen\"));\n\n // First separator\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // 5. Open file (submenu)\n HMENU hFileMenu = CreatePopupMenu();\n\n // First add recent files list\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n wchar_t wFileName[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[i].name, -1, wFileName, MAX_PATH);\n \n // Truncate long file names\n wchar_t truncatedName[MAX_PATH];\n TruncateFileName(wFileName, truncatedName, 25); // Limit to 25 characters\n \n // Check if this is the currently selected file and the current timeout action is \"open file\"\n BOOL isCurrentFile = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE && \n strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n strcmp(CLOCK_RECENT_FILES[i].path, CLOCK_TIMEOUT_FILE_PATH) == 0);\n \n // Use menu item check state to indicate selection\n AppendMenuW(hFileMenu, MF_STRING | (isCurrentFile ? MF_CHECKED : 0), \n CLOCK_IDM_RECENT_FILE_1 + i, truncatedName);\n }\n \n // Add separator if there are recent files\n if (CLOCK_RECENT_FILES_COUNT > 0) {\n AppendMenuW(hFileMenu, MF_SEPARATOR, 0, NULL);\n }\n\n // Finally add \"Browse...\" option\n AppendMenuW(hFileMenu, MF_STRING, CLOCK_IDM_BROWSE_FILE,\n GetLocalizedString(L\"浏览...\", L\"Browse...\"));\n\n // Add \"Open File\" as a submenu to the timeout action menu\n AppendMenuW(hTimeoutMenu, MF_POPUP | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE ? MF_CHECKED : MF_UNCHECKED), \n (UINT_PTR)hFileMenu, \n GetLocalizedString(L\"打开文件/软件\", L\"Open File/Software\"));\n\n // 6. Open website\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_WEBSITE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_OPEN_WEBSITE,\n GetLocalizedString(L\"打开网站\", L\"Open Website\"));\n\n // Second separator\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // Add a non-selectable hint option\n AppendMenuW(hTimeoutMenu, MF_STRING | MF_GRAYED | MF_DISABLED, \n 0, // Use ID 0 to indicate non-selectable menu item\n GetLocalizedString(L\"以下超时动作为一次性\", L\"Following actions are one-time only\"));\n\n // 7. Shutdown\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHUTDOWN,\n GetLocalizedString(L\"关机\", L\"Shutdown\"));\n\n // 8. Restart\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RESTART,\n GetLocalizedString(L\"重启\", L\"Restart\"));\n\n // 9. Sleep\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SLEEP,\n GetLocalizedString(L\"睡眠\", L\"Sleep\"));\n\n // Third separator and Advanced menu\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n\n // Create Advanced submenu\n HMENU hAdvancedMenu = CreatePopupMenu();\n\n // Add \"Run Command\" option\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RUN_COMMAND,\n GetLocalizedString(L\"运行命令\", L\"Run Command\"));\n\n // Add \"HTTP Request\" option\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_HTTP_REQUEST,\n GetLocalizedString(L\"HTTP 请求\", L\"HTTP Request\"));\n\n // Check if any advanced option is selected to determine if the Advanced submenu should be checked\n BOOL isAdvancedOptionSelected = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ||\n CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST);\n\n // Add Advanced submenu to timeout menu - mark as checked if any advanced option is selected\n AppendMenuW(hTimeoutMenu, MF_POPUP | (isAdvancedOptionSelected ? MF_CHECKED : MF_UNCHECKED),\n (UINT_PTR)hAdvancedMenu,\n GetLocalizedString(L\"高级\", L\"Advanced\"));\n\n // Add timeout action menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeoutMenu, \n GetLocalizedString(L\"超时动作\", L\"Timeout Action\"));\n\n // Preset management menu\n HMENU hTimeOptionsMenu = CreatePopupMenu();\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDC_MODIFY_TIME_OPTIONS,\n GetLocalizedString(L\"倒计时预设\", L\"Modify Quick Countdown Options\"));\n \n // Startup settings submenu\n HMENU hStartupSettingsMenu = CreatePopupMenu();\n\n // Read current startup mode\n char currentStartupMode[20] = \"COUNTDOWN\";\n char configPath[MAX_PATH]; \n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\"); \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(configFile);\n }\n \n // Add startup mode options\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNTDOWN\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_SET_COUNTDOWN_TIME,\n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNT_UP\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_COUNT_UP,\n GetLocalizedString(L\"正计时\", L\"Stopwatch\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"SHOW_TIME\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_SHOW_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"NO_DISPLAY\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_NO_DISPLAY,\n GetLocalizedString(L\"不显示\", L\"No Display\"));\n \n AppendMenuW(hStartupSettingsMenu, MF_SEPARATOR, 0, NULL);\n\n // Add auto-start option\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (IsAutoStartEnabled() ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_AUTO_START,\n GetLocalizedString(L\"开机自启动\", L\"Start with Windows\"));\n\n // Add startup settings menu to preset management menu\n AppendMenuW(hTimeOptionsMenu, MF_POPUP, (UINT_PTR)hStartupSettingsMenu,\n GetLocalizedString(L\"启动设置\", L\"Startup Settings\"));\n\n // Add notification settings menu - changed to direct menu item, no longer using submenu\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDM_NOTIFICATION_SETTINGS,\n GetLocalizedString(L\"通知设置\", L\"Notification Settings\"));\n\n // Add preset management menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeOptionsMenu,\n GetLocalizedString(L\"预设管理\", L\"Preset Management\"));\n \n AppendMenuW(hTimeOptionsMenu, MF_STRING | (CLOCK_WINDOW_TOPMOST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TOPMOST,\n GetLocalizedString(L\"置顶\", L\"Always on Top\"));\n\n // Add \"Hotkey Settings\" option after preset management menu\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_HOTKEY_SETTINGS,\n GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Font menu\n HMENU hMoreFontsMenu = CreatePopupMenu();\n HMENU hFontSubMenu = CreatePopupMenu();\n \n // First add commonly used fonts to the main menu\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n // These fonts are kept in the main menu\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n \n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayName[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayName, 100);\n wchar_t* dot = wcsstr(wDisplayName, L\".ttf\");\n if (dot) *dot = L'\\0';\n \n AppendMenuW(hFontSubMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayName);\n }\n }\n\n AppendMenuW(hFontSubMenu, MF_SEPARATOR, 0, NULL);\n\n // Add other fonts to the \"More\" submenu\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n // Exclude fonts already added to the main menu\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n continue;\n }\n\n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayNameMore[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayNameMore, 100);\n wchar_t* dot = wcsstr(wDisplayNameMore, L\".ttf\");\n if (dot) *dot = L'\\0';\n \n AppendMenuW(hMoreFontsMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayNameMore);\n }\n\n // Add \"More\" submenu to main font menu\n AppendMenuW(hFontSubMenu, MF_POPUP, (UINT_PTR)hMoreFontsMenu, GetLocalizedString(L\"更多\", L\"More\"));\n\n // Color menu\n HMENU hColorSubMenu = CreatePopupMenu();\n // Preset color option menu IDs start from 201 to 201+COLOR_OPTIONS_COUNT-1\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n \n MENUITEMINFO mii = { sizeof(MENUITEMINFO) };\n mii.fMask = MIIM_STRING | MIIM_ID | MIIM_STATE | MIIM_FTYPE;\n mii.fType = MFT_STRING | MFT_OWNERDRAW;\n mii.fState = strcmp(CLOCK_TEXT_COLOR, hexColor) == 0 ? MFS_CHECKED : MFS_UNCHECKED;\n mii.wID = 201 + i; // Preset color menu item IDs start from 201\n mii.dwTypeData = (LPSTR)hexColor;\n \n InsertMenuItem(hColorSubMenu, i, TRUE, &mii);\n }\n AppendMenuW(hColorSubMenu, MF_SEPARATOR, 0, NULL);\n\n // Custom color options\n HMENU hCustomizeMenu = CreatePopupMenu();\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_VALUE, \n GetLocalizedString(L\"颜色值\", L\"Color Value\"));\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_PANEL, \n GetLocalizedString(L\"颜色面板\", L\"Color Panel\"));\n\n AppendMenuW(hColorSubMenu, MF_POPUP, (UINT_PTR)hCustomizeMenu, \n GetLocalizedString(L\"自定义\", L\"Customize\"));\n\n // Add font and color menus to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hFontSubMenu, \n GetLocalizedString(L\"字体\", L\"Font\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hColorSubMenu, \n GetLocalizedString(L\"颜色\", L\"Color\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // About menu\n HMENU hAboutMenu = CreatePopupMenu();\n\n // Add \"About\" menu item here\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_ABOUT, GetLocalizedString(L\"关于\", L\"About\"));\n\n // Add separator\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n\n // Add \"Support\" option - open sponsorship page\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n \n // Add \"Feedback\" option - open different feedback links based on language\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_FEEDBACK, GetLocalizedString(L\"反馈\", L\"Feedback\"));\n \n // Add separator\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n \n // Add \"Help\" option - open user guide webpage\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_HELP, GetLocalizedString(L\"使用指南\", L\"User Guide\"));\n\n // Add \"Check for Updates\" option\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_CHECK_UPDATE, \n GetLocalizedString(L\"检查更新\", L\"Check for Updates\"));\n\n // Language selection menu\n HMENU hLangMenu = CreatePopupMenu();\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE, L\"简体中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE_TRAD, L\"繁體中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_ENGLISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_ENGLISH, L\"English\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_SPANISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_SPANISH, L\"Español\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_FRENCH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_FRENCH, L\"Français\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_GERMAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_GERMAN, L\"Deutsch\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_RUSSIAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_RUSSIAN, L\"Русский\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_PORTUGUESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_PORTUGUESE, L\"Português\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_JAPANESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_JAPANESE, L\"日本語\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_KOREAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_KOREAN, L\"한국어\");\n\n AppendMenuW(hAboutMenu, MF_POPUP, (UINT_PTR)hLangMenu, GetLocalizedString(L\"语言\", L\"Language\"));\n\n // Add reset option to the end of the help menu\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, 200,\n GetLocalizedString(L\"重置\", L\"Reset\"));\n\n // Add about menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hAboutMenu,\n GetLocalizedString(L\"帮助\", L\"Help\"));\n\n // Only keep exit option\n AppendMenuW(hMenu, MF_STRING, 109,\n GetLocalizedString(L\"退出\", L\"Exit\"));\n \n // Display menu\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); // This will allow the menu to close automatically when clicking outside\n DestroyMenu(hMenu);\n}\n\n/**\n * @brief Display tray right-click menu\n * \n * @param hwnd Window handle\n * \n * Create and display the system tray right-click menu, dynamically adjusting menu items based on current application state. Includes:\n * - Timer control (pause/resume, restart)\n * - Time display settings (24-hour format, show seconds)\n * - Pomodoro clock settings\n * - Count-up and countdown mode switching\n * - Quick time preset options\n */\nvoid ShowContextMenu(HWND hwnd) {\n // Read timeout action settings from configuration file before creating the menu\n ReadTimeoutActionFromConfig();\n \n // Set mouse cursor to default arrow to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n HMENU hMenu = CreatePopupMenu();\n \n // Timer management menu - added at the top\n HMENU hTimerManageMenu = CreatePopupMenu();\n \n // Set conditions for whether submenu items should be enabled\n // Timer options should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress\n // 3. If in countdown mode, the timer hasn't ended yet (countdown elapsed time is less than total time)\n BOOL timerRunning = (!CLOCK_SHOW_CURRENT_TIME && \n (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0 && countdown_elapsed_time < CLOCK_TOTAL_TIME)));\n \n // Pause/Resume text changes based on current state\n const wchar_t* pauseResumeText = CLOCK_IS_PAUSED ? \n GetLocalizedString(L\"继续\", L\"Resume\") : \n GetLocalizedString(L\"暂停\", L\"Pause\");\n \n // Submenu items are disabled based on conditions, but parent menu item remains selectable\n AppendMenuW(hTimerManageMenu, MF_STRING | (timerRunning ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_PAUSE_RESUME, pauseResumeText);\n \n // Restart option should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress (regardless of whether countdown has ended)\n BOOL canRestart = (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0)));\n \n AppendMenuW(hTimerManageMenu, MF_STRING | (canRestart ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_RESTART, \n GetLocalizedString(L\"重新开始\", L\"Start Over\"));\n \n // Add timer management menu to main menu - parent menu item is always enabled\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimerManageMenu,\n GetLocalizedString(L\"计时管理\", L\"Timer Control\"));\n \n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n \n // Time display menu\n HMENU hTimeMenu = CreatePopupMenu();\n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_CURRENT_TIME ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_CURRENT_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_USE_24HOUR ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_24HOUR_FORMAT,\n GetLocalizedString(L\"24小时制\", L\"24-Hour Format\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_SECONDS ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_SECONDS,\n GetLocalizedString(L\"显示秒数\", L\"Show Seconds\"));\n \n AppendMenuW(hMenu, MF_POPUP,\n (UINT_PTR)hTimeMenu,\n GetLocalizedString(L\"时间显示\", L\"Time Display\"));\n\n // Before Pomodoro menu, first read the latest configuration values\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\");\n POMODORO_TIMES_COUNT = 0; // Initialize to 0\n \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n char* options = line + 22;\n char* token;\n int index = 0;\n \n token = strtok(options, \",\");\n while (token && index < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[index++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Set the actual number of time options\n POMODORO_TIMES_COUNT = index;\n \n // Ensure at least one valid value\n if (index > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (index > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (index > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[2];\n }\n }\n else if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n sscanf(line, \"POMODORO_LOOP_COUNT=%d\", &POMODORO_LOOP_COUNT);\n // Ensure loop count is at least 1\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n }\n }\n fclose(configFile);\n }\n\n // Pomodoro menu\n HMENU hPomodoroMenu = CreatePopupMenu();\n \n // Add timeBuffer declaration\n wchar_t timeBuffer[64]; // For storing formatted time string\n \n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_START,\n GetLocalizedString(L\"开始\", L\"Start\"));\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Create menu items for each Pomodoro time\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n FormatPomodoroTime(POMODORO_TIMES[i], timeBuffer, sizeof(timeBuffer)/sizeof(wchar_t));\n \n // Support both old and new ID systems\n UINT menuId;\n if (i == 0) menuId = CLOCK_IDM_POMODORO_WORK;\n else if (i == 1) menuId = CLOCK_IDM_POMODORO_BREAK;\n else if (i == 2) menuId = CLOCK_IDM_POMODORO_LBREAK;\n else menuId = CLOCK_IDM_POMODORO_TIME_BASE + i;\n \n // Check if this is the active Pomodoro phase\n BOOL isCurrentPhase = (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n current_pomodoro_time_index == i &&\n !CLOCK_SHOW_CURRENT_TIME &&\n !CLOCK_COUNT_UP && // Add check for not being in count-up mode\n CLOCK_TOTAL_TIME == POMODORO_TIMES[i]);\n \n // Add check mark if it's the current phase\n AppendMenuW(hPomodoroMenu, MF_STRING | (isCurrentPhase ? MF_CHECKED : MF_UNCHECKED), \n menuId, timeBuffer);\n }\n\n // Add loop count option\n wchar_t menuText[64];\n _snwprintf(menuText, sizeof(menuText)/sizeof(wchar_t),\n GetLocalizedString(L\"循环次数: %d\", L\"Loop Count: %d\"),\n POMODORO_LOOP_COUNT);\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_LOOP_COUNT, menuText);\n\n\n // Add separator\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Add combination option\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_COMBINATION,\n GetLocalizedString(L\"组合\", L\"Combination\"));\n \n // Add Pomodoro menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hPomodoroMenu,\n GetLocalizedString(L\"番茄时钟\", L\"Pomodoro\"));\n\n // Count-up menu - changed to direct click to start\n AppendMenuW(hMenu, MF_STRING | (CLOCK_COUNT_UP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_COUNT_UP_START,\n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n\n // Add \"Set Countdown\" option below Count-up\n AppendMenuW(hMenu, MF_STRING, 101, \n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Add quick time options\n for (int i = 0; i < time_options_count; i++) {\n wchar_t menu_item[20];\n _snwprintf(menu_item, sizeof(menu_item)/sizeof(wchar_t), L\"%d\", time_options[i]);\n AppendMenuW(hMenu, MF_STRING, 102 + i, menu_item);\n }\n\n // Display menu\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); // This will allow the menu to close automatically when clicking outside\n DestroyMenu(hMenu);\n}"], ["/Catime/src/notification.c", "/**\n * @file notification.c\n * @brief Application notification system implementation\n * \n * This module implements various notification functions of the application, including:\n * 1. Custom styled popup notification windows with fade-in/fade-out animation effects\n * 2. System tray notification message integration\n * 3. Creation, display and lifecycle management of notification windows\n * \n * The notification system supports UTF-8 encoded Chinese text to ensure correct display in multilingual environments.\n */\n\n#include \n#include \n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\" // Contains definitions of all IDs and constants\n#include // For GET_X_LPARAM and GET_Y_LPARAM macros\n\n// Imported from config.h\n// New: notification type configuration\nextern NotificationType NOTIFICATION_TYPE;\n\n/**\n * Notification window animation state enumeration\n * Tracks the current animation phase of the notification window\n */\ntypedef enum {\n ANIM_FADE_IN, // Fade-in phase - opacity increases from 0 to target value\n ANIM_VISIBLE, // Fully visible phase - maintains maximum opacity\n ANIM_FADE_OUT, // Fade-out phase - opacity decreases from maximum to 0\n} AnimationState;\n\n// Forward declarations\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid RegisterNotificationClass(HINSTANCE hInstance);\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius);\n\n/**\n * @brief Calculate the width required for text rendering\n * @param hdc Device context\n * @param text Text to measure\n * @param font Font to use\n * @return int Width required for text rendering (pixels)\n */\nint CalculateTextWidth(HDC hdc, const wchar_t* text, HFONT font) {\n HFONT oldFont = (HFONT)SelectObject(hdc, font);\n SIZE textSize;\n GetTextExtentPoint32W(hdc, text, wcslen(text), &textSize);\n SelectObject(hdc, oldFont);\n return textSize.cx;\n}\n\n/**\n * @brief Show notification (based on configured notification type)\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays different styles of notifications based on the configured notification type\n */\nvoid ShowNotification(HWND hwnd, const char* message) {\n // Read the latest notification type configuration\n ReadNotificationTypeConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Choose the corresponding notification method based on notification type\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n ShowToastNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n ShowModalNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_OS:\n ShowTrayNotification(hwnd, message);\n break;\n default:\n // Default to using Catime notification window\n ShowToastNotification(hwnd, message);\n break;\n }\n}\n\n/**\n * Modal dialog thread parameter structure\n */\ntypedef struct {\n HWND hwnd; // Parent window handle\n char message[512]; // Message content\n} DialogThreadParams;\n\n/**\n * @brief Thread function to display modal dialog\n * @param lpParam Thread parameter, pointer to DialogThreadParams structure\n * @return DWORD Thread return value\n */\nDWORD WINAPI ShowModalDialogThread(LPVOID lpParam) {\n DialogThreadParams* params = (DialogThreadParams*)lpParam;\n \n // Convert UTF-8 message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, params->message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, display English version directly\n MessageBoxA(params->hwnd, params->message, \"Catime\", MB_OK);\n free(params);\n return 0;\n }\n \n MultiByteToWideChar(CP_UTF8, 0, params->message, -1, wmessage, wlen);\n \n // Display modal dialog with fixed title \"Catime\"\n MessageBoxW(params->hwnd, wmessage, L\"Catime\", MB_OK);\n \n // Free allocated memory\n free(wmessage);\n free(params);\n \n return 0;\n}\n\n/**\n * @brief Display system modal dialog notification\n * @param hwnd Parent window handle\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a modal dialog in a separate thread, which won't block the main program\n */\nvoid ShowModalNotification(HWND hwnd, const char* message) {\n // Create thread parameter structure\n DialogThreadParams* params = (DialogThreadParams*)malloc(sizeof(DialogThreadParams));\n if (!params) return;\n \n // Copy parameters\n params->hwnd = hwnd;\n strncpy(params->message, message, sizeof(params->message) - 1);\n params->message[sizeof(params->message) - 1] = '\\0';\n \n // Create new thread to display dialog\n HANDLE hThread = CreateThread(\n NULL, // Default security attributes\n 0, // Default stack size\n ShowModalDialogThread, // Thread function\n params, // Thread parameter\n 0, // Run thread immediately\n NULL // Don't receive thread ID\n );\n \n // If thread creation fails, free resources\n if (hThread == NULL) {\n free(params);\n // Fall back to non-blocking notification method\n MessageBeep(MB_OK);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Close thread handle, let system clean up automatically\n CloseHandle(hThread);\n}\n\n/**\n * @brief Display custom styled toast notification\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a custom notification window with animation effects in the bottom right corner of the screen:\n * 1. Register notification window class (if needed)\n * 2. Calculate notification display position (bottom right of work area)\n * 3. Create notification window with fade-in/fade-out effects\n * 4. Set auto-close timer\n * \n * Note: If creating custom notification window fails, will fall back to using system tray notification\n */\nvoid ShowToastNotification(HWND hwnd, const char* message) {\n static BOOL isClassRegistered = FALSE;\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n \n // Dynamically read the latest notification settings before displaying notification\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Register notification window class (if not already registered)\n if (!isClassRegistered) {\n RegisterNotificationClass(hInstance);\n isClassRegistered = TRUE;\n }\n \n // Convert message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, fall back to system tray notification\n ShowTrayNotification(hwnd, message);\n return;\n }\n MultiByteToWideChar(CP_UTF8, 0, message, -1, wmessage, wlen);\n \n // Calculate width needed for text\n HDC hdc = GetDC(hwnd);\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Calculate text width and add margins\n int textWidth = CalculateTextWidth(hdc, wmessage, contentFont);\n int notificationWidth = textWidth + 40; // 20 pixel margin on each side\n \n // Ensure width is within allowed range\n if (notificationWidth < NOTIFICATION_MIN_WIDTH) \n notificationWidth = NOTIFICATION_MIN_WIDTH;\n if (notificationWidth > NOTIFICATION_MAX_WIDTH) \n notificationWidth = NOTIFICATION_MAX_WIDTH;\n \n DeleteObject(contentFont);\n ReleaseDC(hwnd, hdc);\n \n // Get work area size, calculate notification window position (bottom right)\n RECT workArea;\n SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);\n \n int x = workArea.right - notificationWidth - 20;\n int y = workArea.bottom - NOTIFICATION_HEIGHT - 20;\n \n // Create notification window, add layered support for transparency effects\n HWND hNotification = CreateWindowExW(\n WS_EX_TOPMOST | WS_EX_LAYERED | WS_EX_TOOLWINDOW, // Keep on top and hide from taskbar\n NOTIFICATION_CLASS_NAME,\n L\"Catime Notification\", // Window title (not visible)\n WS_POPUP, // Borderless popup window style\n x, y, // Bottom right screen position\n notificationWidth, NOTIFICATION_HEIGHT,\n NULL, NULL, hInstance, NULL\n );\n \n // Fall back to system tray notification if creation fails\n if (!hNotification) {\n free(wmessage);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Save message text and window width to window properties\n SetPropW(hNotification, L\"MessageText\", (HANDLE)wmessage);\n SetPropW(hNotification, L\"WindowWidth\", (HANDLE)(LONG_PTR)notificationWidth);\n \n // Set initial animation state to fade-in\n SetPropW(hNotification, L\"AnimState\", (HANDLE)ANIM_FADE_IN);\n SetPropW(hNotification, L\"Opacity\", (HANDLE)0); // Initial opacity is 0\n \n // Set initial window to completely transparent\n SetLayeredWindowAttributes(hNotification, 0, 0, LWA_ALPHA);\n \n // Show window but don't activate (don't steal focus)\n ShowWindow(hNotification, SW_SHOWNOACTIVATE);\n UpdateWindow(hNotification);\n \n // Start fade-in animation\n SetTimer(hNotification, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n \n // Set auto-close timer, using globally configured timeout\n SetTimer(hNotification, NOTIFICATION_TIMER_ID, NOTIFICATION_TIMEOUT_MS, NULL);\n}\n\n/**\n * @brief Register notification window class\n * @param hInstance Application instance handle\n * \n * Registers custom notification window class with Windows, defining basic behavior and appearance:\n * 1. Set window procedure function\n * 2. Define default cursor and background\n * 3. Specify unique window class name\n * \n * This function is only called the first time a notification is displayed, subsequent calls reuse the registered class.\n */\nvoid RegisterNotificationClass(HINSTANCE hInstance) {\n WNDCLASSEXW wc = {0};\n wc.cbSize = sizeof(WNDCLASSEXW);\n wc.lpfnWndProc = NotificationWndProc;\n wc.hInstance = hInstance;\n wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n wc.lpszClassName = NOTIFICATION_CLASS_NAME;\n \n RegisterClassExW(&wc);\n}\n\n/**\n * @brief Notification window message processing procedure\n * @param hwnd Window handle\n * @param msg Message ID\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return LRESULT Message processing result\n * \n * Handles all Windows messages for the notification window, including:\n * - WM_PAINT: Draw notification window content (title, message text)\n * - WM_TIMER: Handle auto-close and animation effects\n * - WM_LBUTTONDOWN: Handle user click to close\n * - WM_DESTROY: Release window resources\n * \n * Specifically handles animation state transition logic to ensure smooth fade-in/fade-out effects.\n */\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_PAINT: {\n PAINTSTRUCT ps;\n HDC hdc = BeginPaint(hwnd, &ps);\n \n // Get window client area size\n RECT clientRect;\n GetClientRect(hwnd, &clientRect);\n \n // Create compatible DC and bitmap for double-buffered drawing to avoid flickering\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, clientRect.right, clientRect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n \n // Fill white background\n HBRUSH whiteBrush = CreateSolidBrush(RGB(255, 255, 255));\n FillRect(memDC, &clientRect, whiteBrush);\n DeleteObject(whiteBrush);\n \n // Draw rectangle with border\n DrawRoundedRectangle(memDC, clientRect, 0);\n \n // Set text drawing mode to transparent background\n SetBkMode(memDC, TRANSPARENT);\n \n // Create title font - bold\n HFONT titleFont = CreateFontW(22, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Create message content font\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Draw title \"Catime\"\n SelectObject(memDC, titleFont);\n SetTextColor(memDC, RGB(0, 0, 0));\n RECT titleRect = {15, 10, clientRect.right - 15, 35};\n DrawTextW(memDC, L\"Catime\", -1, &titleRect, DT_SINGLELINE);\n \n // Draw message content - placed below title, using single line mode\n SelectObject(memDC, contentFont);\n SetTextColor(memDC, RGB(100, 100, 100));\n const wchar_t* message = (const wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n RECT textRect = {15, 35, clientRect.right - 15, clientRect.bottom - 10};\n // Use DT_SINGLELINE|DT_END_ELLIPSIS to ensure text is displayed in one line, with ellipsis for long text\n DrawTextW(memDC, message, -1, &textRect, DT_SINGLELINE|DT_END_ELLIPSIS);\n }\n \n // Copy content from memory DC to window DC\n BitBlt(hdc, 0, 0, clientRect.right, clientRect.bottom, memDC, 0, 0, SRCCOPY);\n \n // Clean up resources\n SelectObject(memDC, oldBitmap);\n DeleteObject(titleFont);\n DeleteObject(contentFont);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n \n EndPaint(hwnd, &ps);\n return 0;\n }\n \n case WM_TIMER:\n if (wParam == NOTIFICATION_TIMER_ID) {\n // Auto-close timer triggered, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // Check current state - only start fade-out when fully visible\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState == ANIM_VISIBLE) {\n // Set to fade-out state\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start animation timer\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n return 0;\n }\n else if (wParam == ANIMATION_TIMER_ID) {\n // Handle animation effect timer\n AnimationState state = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n DWORD opacityVal = (DWORD)(DWORD_PTR)GetPropW(hwnd, L\"Opacity\");\n BYTE opacity = (BYTE)opacityVal;\n \n // Calculate maximum opacity value (percentage converted to 0-255 range)\n BYTE maxOpacity = (BYTE)((NOTIFICATION_MAX_OPACITY * 255) / 100);\n \n switch (state) {\n case ANIM_FADE_IN:\n // Fade-in animation - gradually increase opacity\n if (opacity >= maxOpacity - ANIMATION_STEP) {\n // Reached maximum opacity, completed fade-in\n opacity = maxOpacity;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n \n // Switch to visible state and stop animation\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_VISIBLE);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n } else {\n // Normal fade-in - increase by one step each time\n opacity += ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_FADE_OUT:\n // Fade-out animation - gradually decrease opacity\n if (opacity <= ANIMATION_STEP) {\n // Completely transparent, destroy window\n KillTimer(hwnd, ANIMATION_TIMER_ID); // Make sure to stop timer first\n DestroyWindow(hwnd);\n } else {\n // Normal fade-out - decrease by one step each time\n opacity -= ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_VISIBLE:\n // Fully visible state doesn't need animation, stop timer\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n break;\n }\n return 0;\n }\n break;\n \n case WM_LBUTTONDOWN: {\n // Handle left mouse button click event (close notification early)\n \n // Get current state - only respond to clicks when fully visible or after fade-in completes\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState != ANIM_VISIBLE) {\n return 0; // Ignore click, avoid interference during animation\n }\n \n // Click anywhere, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID); // Stop auto-close timer\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n return 0;\n }\n \n case WM_DESTROY: {\n // Cleanup work when window is destroyed\n \n // Stop all timers\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n \n // Free message text memory\n wchar_t* message = (wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n free(message);\n }\n \n // Remove all window properties\n RemovePropW(hwnd, L\"MessageText\");\n RemovePropW(hwnd, L\"AnimState\");\n RemovePropW(hwnd, L\"Opacity\");\n return 0;\n }\n }\n \n return DefWindowProc(hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Draw rectangle with border\n * @param hdc Device context\n * @param rect Rectangle area\n * @param radius Corner radius (unused)\n * \n * Draws a rectangle with light gray border in the specified device context.\n * This function reserves the corner radius parameter, but current implementation uses standard rectangle.\n * Can be extended to support true rounded rectangles in future versions.\n */\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius) {\n // Create light gray border pen\n HPEN pen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n HPEN oldPen = (HPEN)SelectObject(hdc, pen);\n \n // Use normal rectangle instead of rounded rectangle\n Rectangle(hdc, rect.left, rect.top, rect.right, rect.bottom);\n \n // Clean up resources\n SelectObject(hdc, oldPen);\n DeleteObject(pen);\n}\n\n/**\n * @brief Close all currently displayed Catime notification windows\n * \n * Find and close all notification windows created by Catime, ignoring their current display time settings,\n * directly start fade-out animation. Usually called when switching timer modes to ensure notifications don't continue to display.\n */\nvoid CloseAllNotifications(void) {\n // Find all notification windows created by Catime\n HWND hwnd = NULL;\n HWND hwndPrev = NULL;\n \n // Use FindWindowExW to find each matching window one by one\n // First call with hwndPrev as NULL finds the first window\n // Subsequent calls pass the previously found window handle to find the next window\n while ((hwnd = FindWindowExW(NULL, hwndPrev, NOTIFICATION_CLASS_NAME, NULL)) != NULL) {\n // Check current state\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n \n // Stop current auto-close timer\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // If window hasn't started fading out yet, start fade-out animation\n if (currentState != ANIM_FADE_OUT) {\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start fade-out animation\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n \n // Save current window handle for next search\n hwndPrev = hwnd;\n }\n}\n"], ["/Catime/src/timer.c", "/**\n * @file timer.c\n * @brief Implementation of core timer functionality\n * \n * This file contains the implementation of the core timer logic, including time format conversion, \n * input parsing, configuration saving, and other functionalities,\n * while maintaining various timer states and configuration parameters.\n */\n\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n/** @name Timer status flags\n * @{ */\nBOOL CLOCK_IS_PAUSED = FALSE; ///< Timer pause status flag\nBOOL CLOCK_SHOW_CURRENT_TIME = FALSE; ///< Show current time mode flag\nBOOL CLOCK_USE_24HOUR = TRUE; ///< Use 24-hour format flag\nBOOL CLOCK_SHOW_SECONDS = TRUE; ///< Show seconds flag\nBOOL CLOCK_COUNT_UP = FALSE; ///< Countdown/count-up mode flag\nchar CLOCK_STARTUP_MODE[20] = \"COUNTDOWN\"; ///< Startup mode (countdown/count-up)\n/** @} */\n\n/** @name Timer time parameters \n * @{ */\nint CLOCK_TOTAL_TIME = 0; ///< Total timer time (seconds)\nint countdown_elapsed_time = 0; ///< Countdown elapsed time (seconds)\nint countup_elapsed_time = 0; ///< Count-up accumulated time (seconds)\ntime_t CLOCK_LAST_TIME_UPDATE = 0; ///< Last update timestamp\n\n// High-precision timer related variables\nLARGE_INTEGER timer_frequency; ///< High-precision timer frequency\nLARGE_INTEGER timer_last_count; ///< Last timing point\nBOOL high_precision_timer_initialized = FALSE; ///< High-precision timer initialization flag\n/** @} */\n\n/** @name Message status flags\n * @{ */\nBOOL countdown_message_shown = FALSE; ///< Countdown completion message display status\nBOOL countup_message_shown = FALSE; ///< Count-up completion message display status\nint pomodoro_work_cycles = 0; ///< Pomodoro work cycle count\n/** @} */\n\n/** @name Timeout action configuration\n * @{ */\nTimeoutActionType CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE; ///< Timeout action type\nchar CLOCK_TIMEOUT_TEXT[50] = \"\"; ///< Timeout display text\nchar CLOCK_TIMEOUT_FILE_PATH[MAX_PATH] = \"\"; ///< Timeout executable file path\n/** @} */\n\n/** @name Pomodoro time settings\n * @{ */\nint POMODORO_WORK_TIME = 25 * 60; ///< Pomodoro work time (25 minutes)\nint POMODORO_SHORT_BREAK = 5 * 60; ///< Pomodoro short break time (5 minutes)\nint POMODORO_LONG_BREAK = 15 * 60; ///< Pomodoro long break time (15 minutes)\nint POMODORO_LOOP_COUNT = 1; ///< Pomodoro loop count (default 1 time)\n/** @} */\n\n/** @name Preset time options\n * @{ */\nint time_options[MAX_TIME_OPTIONS]; ///< Preset time options array\nint time_options_count = 0; ///< Number of valid preset times\n/** @} */\n\n/** Last displayed time (seconds), used to prevent time display jumping phenomenon */\nint last_displayed_second = -1;\n\n/**\n * @brief Initialize high-precision timer\n * \n * Get system timer frequency and record initial timing point\n * @return BOOL Whether initialization was successful\n */\nBOOL InitializeHighPrecisionTimer(void) {\n if (!QueryPerformanceFrequency(&timer_frequency)) {\n return FALSE; // System does not support high-precision timer\n }\n \n if (!QueryPerformanceCounter(&timer_last_count)) {\n return FALSE; // Failed to get current count\n }\n \n high_precision_timer_initialized = TRUE;\n return TRUE;\n}\n\n/**\n * @brief Calculate milliseconds elapsed since last call\n * \n * Use high-precision timer to calculate exact time interval\n * @return double Elapsed milliseconds\n */\ndouble GetElapsedMilliseconds(void) {\n if (!high_precision_timer_initialized) {\n if (!InitializeHighPrecisionTimer()) {\n return 0.0; // Initialization failed, return 0\n }\n }\n \n LARGE_INTEGER current_count;\n if (!QueryPerformanceCounter(¤t_count)) {\n return 0.0; // Failed to get current count\n }\n \n // Calculate time difference (convert to milliseconds)\n double elapsed = (double)(current_count.QuadPart - timer_last_count.QuadPart) * 1000.0 / (double)timer_frequency.QuadPart;\n \n // Update last timing point\n timer_last_count = current_count;\n \n return elapsed;\n}\n\n/**\n * @brief Update elapsed time for countdown/count-up\n * \n * Use high-precision timer to calculate time elapsed since last call, and update\n * countup_elapsed_time (count-up mode) or countdown_elapsed_time (countdown mode) accordingly.\n * No updates are made in pause state.\n */\nvoid UpdateElapsedTime(void) {\n if (CLOCK_IS_PAUSED) {\n return; // Do not update in pause state\n }\n \n double elapsed_ms = GetElapsedMilliseconds();\n \n if (CLOCK_COUNT_UP) {\n // Count-up mode\n countup_elapsed_time += (int)(elapsed_ms / 1000.0);\n } else {\n // Countdown mode\n countdown_elapsed_time += (int)(elapsed_ms / 1000.0);\n \n // Ensure does not exceed total time\n if (countdown_elapsed_time > CLOCK_TOTAL_TIME) {\n countdown_elapsed_time = CLOCK_TOTAL_TIME;\n }\n }\n}\n\n/**\n * @brief Format display time\n * @param remaining_time Remaining time (seconds)\n * @param[out] time_text Formatted time string output buffer\n * \n * Format time as a string according to current configuration (12/24 hour format, whether to show seconds, countdown/count-up mode).\n * Supports three display modes: current system time, countdown remaining time, count-up accumulated time.\n */\nvoid FormatTime(int remaining_time, char* time_text) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // Get local time\n SYSTEMTIME st;\n GetLocalTime(&st);\n \n // Check time continuity, prevent second jumping display\n if (last_displayed_second != -1) {\n // If not consecutive seconds, and not a cross-minute situation\n if (st.wSecond != (last_displayed_second + 1) % 60 && \n !(last_displayed_second == 59 && st.wSecond == 0)) {\n // Relax conditions, allow larger differences to sync, ensure not lagging behind for long\n if (st.wSecond != last_displayed_second) {\n // Directly use system time seconds\n last_displayed_second = st.wSecond;\n }\n } else {\n // Time is consecutive, normal update\n last_displayed_second = st.wSecond;\n }\n } else {\n // First display, initialize record\n last_displayed_second = st.wSecond;\n }\n \n int hour = st.wHour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, st.wMinute, last_displayed_second);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, st.wMinute);\n }\n return;\n }\n\n if (CLOCK_COUNT_UP) {\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n return;\n }\n\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int remaining = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining <= 0) {\n // Do not return empty string, show 0:00 instead\n sprintf(time_text, \" 0:00\");\n return;\n }\n\n int hours = remaining / 3600;\n int minutes = (remaining % 3600) / 60;\n int seconds = remaining % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n if (minutes >= 10) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n }\n } else {\n if (seconds < 10) {\n sprintf(time_text, \" %d\", seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n }\n}\n\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n */\n\n// Detailed explanation of parsing logic and boundary handling\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n * \n * Parsing process:\n * 1. First check the validity of the input\n * 2. Detect if it's a target time format (ending with 't' or 'T')\n * - If so, calculate seconds from current to target time, if time has passed set to same time tomorrow\n * 3. Otherwise, check if it contains unit identifiers (h/m/s)\n * - If it does, process according to units\n * - If not, decide processing method based on number of space-separated numbers\n * \n * Boundary handling:\n * - Invalid input returns 0\n * - Negative or zero value returns 0\n * - Value exceeding INT_MAX returns 0\n */\nint ParseInput(const char* input, int* total_seconds) {\n if (!isValidInput(input)) return 0;\n\n int total = 0;\n char input_copy[256];\n strncpy(input_copy, input, sizeof(input_copy)-1);\n input_copy[sizeof(input_copy)-1] = '\\0';\n\n // Check if it's a target time format (ending with 't' or 'T')\n int len = strlen(input_copy);\n if (len > 0 && (input_copy[len-1] == 't' || input_copy[len-1] == 'T')) {\n // Remove 't' or 'T' suffix\n input_copy[len-1] = '\\0';\n \n // Get current time\n time_t now = time(NULL);\n struct tm *tm_now = localtime(&now);\n \n // Target time, initialize to current date\n struct tm tm_target = *tm_now;\n \n // Parse target time\n int hour = -1, minute = -1, second = -1;\n int count = 0;\n char *token = strtok(input_copy, \" \");\n \n while (token && count < 3) {\n int value = atoi(token);\n if (count == 0) hour = value;\n else if (count == 1) minute = value;\n else if (count == 2) second = value;\n count++;\n token = strtok(NULL, \" \");\n }\n \n // Set target time, set according to provided values, defaults to 0 if not provided\n if (hour >= 0) {\n tm_target.tm_hour = hour;\n \n // If only hour provided, set minute and second to 0\n if (minute < 0) {\n tm_target.tm_min = 0;\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_min = minute;\n \n // If second not provided, set to 0\n if (second < 0) {\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_sec = second;\n }\n }\n }\n \n // Calculate time difference (seconds)\n time_t target_time = mktime(&tm_target);\n \n // If target time has passed, set to same time tomorrow\n if (target_time <= now) {\n tm_target.tm_mday += 1;\n target_time = mktime(&tm_target);\n }\n \n total = (int)difftime(target_time, now);\n } else {\n // Check if it contains unit identifiers\n BOOL hasUnits = FALSE;\n for (int i = 0; input_copy[i]; i++) {\n char c = tolower((unsigned char)input_copy[i]);\n if (c == 'h' || c == 'm' || c == 's') {\n hasUnits = TRUE;\n break;\n }\n }\n \n if (hasUnits) {\n // For input with units, merge all parts with unit markings\n char* parts[10] = {0}; // Store up to 10 parts\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 10) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n // Process each part\n for (int i = 0; i < part_count; i++) {\n char* part = parts[i];\n int part_len = strlen(part);\n BOOL has_unit = FALSE;\n \n // Check if this part has a unit\n for (int j = 0; j < part_len; j++) {\n char c = tolower((unsigned char)part[j]);\n if (c == 'h' || c == 'm' || c == 's') {\n has_unit = TRUE;\n break;\n }\n }\n \n if (has_unit) {\n // If it has a unit, process according to unit\n char unit = tolower((unsigned char)part[part_len-1]);\n part[part_len-1] = '\\0'; // Remove unit\n int value = atoi(part);\n \n switch (unit) {\n case 'h': total += value * 3600; break;\n case 'm': total += value * 60; break;\n case 's': total += value; break;\n }\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'h') {\n // If next item has h unit, current item is hours\n total += atoi(part) * 3600;\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'm') {\n // If next item has m unit, current item is hours\n total += atoi(part) * 3600;\n } else {\n // Default process as two-segment or three-segment format\n if (part_count == 2) {\n // Two-segment format: first segment is minutes, second segment is seconds\n if (i == 0) total += atoi(part) * 60;\n else total += atoi(part);\n } else if (part_count == 3) {\n // Three-segment format: hour:minute:second\n if (i == 0) total += atoi(part) * 3600;\n else if (i == 1) total += atoi(part) * 60;\n else total += atoi(part);\n } else {\n // Other cases treated as minutes\n total += atoi(part) * 60;\n }\n }\n }\n } else {\n // Processing without units\n char* parts[3] = {0}; // Store up to 3 parts (hour, minute, second)\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 3) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n if (part_count == 1) {\n // Single number, calculate as minutes\n total = atoi(parts[0]) * 60;\n } else if (part_count == 2) {\n // Two numbers: minute:second\n total = atoi(parts[0]) * 60 + atoi(parts[1]);\n } else if (part_count == 3) {\n // Three numbers: hour:minute:second\n total = atoi(parts[0]) * 3600 + atoi(parts[1]) * 60 + atoi(parts[2]);\n }\n }\n }\n\n *total_seconds = total;\n if (*total_seconds <= 0) return 0;\n\n if (*total_seconds > INT_MAX) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Validate if input string is legal\n * @param input Input string to validate\n * @return int Returns 1 if legal, 0 if illegal\n * \n * Valid character check rules:\n * - Only allows digits, spaces, and h/m/s/t unit identifiers at the end (case insensitive)\n * - Must contain at least one digit\n * - Maximum of two space separators\n */\nint isValidInput(const char* input) {\n if (input == NULL || *input == '\\0') {\n return 0;\n }\n\n int len = strlen(input);\n int digitCount = 0;\n\n for (int i = 0; i < len; i++) {\n if (isdigit(input[i])) {\n digitCount++;\n } else if (input[i] == ' ') {\n // Allow any number of spaces\n } else if (i == len - 1 && (input[i] == 'h' || input[i] == 'm' || input[i] == 's' || \n input[i] == 't' || input[i] == 'T' || \n input[i] == 'H' || input[i] == 'M' || input[i] == 'S')) {\n // Allow last character to be h/m/s/t or their uppercase forms\n } else {\n return 0;\n }\n }\n\n if (digitCount == 0) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Reset timer\n * \n * Reset timer state, including pause flag, elapsed time, etc.\n */\nvoid ResetTimer(void) {\n // Reset timing state\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time = 0;\n } else {\n countdown_elapsed_time = 0;\n \n // Ensure countdown total time is not zero, zero would cause timer not to display\n if (CLOCK_TOTAL_TIME <= 0) {\n // If total time is invalid, use default value\n CLOCK_TOTAL_TIME = 60; // Default set to 1 minute\n }\n }\n \n // Cancel pause state\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset message display flags\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Reinitialize high-precision timer\n InitializeHighPrecisionTimer();\n}\n\n/**\n * @brief Toggle timer pause state\n * \n * Toggle timer between pause and continue states\n */\nvoid TogglePauseTimer(void) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n // If resuming from pause state, reinitialize high-precision timer\n if (!CLOCK_IS_PAUSED) {\n InitializeHighPrecisionTimer();\n }\n}\n\n/**\n * @brief Write default startup time to configuration file\n * @param seconds Default startup time (seconds)\n * \n * Use the general path retrieval method in the configuration management module to write to INI format configuration file\n */\nvoid WriteConfigDefaultStartTime(int seconds) {\n char config_path[MAX_PATH];\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Write using INI format\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", seconds, config_path);\n}\n"], ["/Catime/src/font.c", "/**\n * @file font.c\n * @brief Font management module implementation file\n * \n * This file implements the font management functionality of the application, including font loading, preview,\n * application and configuration file management. Supports loading multiple predefined fonts from resources.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/font.h\"\n#include \"../resource/resource.h\"\n\n/// @name Global font variables\n/// @{\nchar FONT_FILE_NAME[100] = \"Hack Nerd Font.ttf\"; ///< Currently used font file name\nchar FONT_INTERNAL_NAME[100]; ///< Font internal name (without extension)\nchar PREVIEW_FONT_NAME[100] = \"\"; ///< Preview font file name\nchar PREVIEW_INTERNAL_NAME[100] = \"\"; ///< Preview font internal name\nBOOL IS_PREVIEWING = FALSE; ///< Whether font preview is active\n/// @}\n\n/**\n * @brief Font resource array\n * \n * Stores information for all built-in font resources in the application\n */\nFontResource fontResources[] = {\n {CLOCK_IDC_FONT_RECMONO, IDR_FONT_RECMONO, \"RecMonoCasual Nerd Font Mono Essence.ttf\"},\n {CLOCK_IDC_FONT_DEPARTURE, IDR_FONT_DEPARTURE, \"DepartureMono Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_TERMINESS, IDR_FONT_TERMINESS, \"Terminess Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_ARBUTUS, IDR_FONT_ARBUTUS, \"Arbutus Essence.ttf\"},\n {CLOCK_IDC_FONT_BERKSHIRE, IDR_FONT_BERKSHIRE, \"Berkshire Swash Essence.ttf\"},\n {CLOCK_IDC_FONT_CAVEAT, IDR_FONT_CAVEAT, \"Caveat Brush Essence.ttf\"},\n {CLOCK_IDC_FONT_CREEPSTER, IDR_FONT_CREEPSTER, \"Creepster Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTGOTHIC, IDR_FONT_DOTGOTHIC, \"DotGothic16 Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTO, IDR_FONT_DOTO, \"Doto ExtraBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FOLDIT, IDR_FONT_FOLDIT, \"Foldit SemiBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FREDERICKA, IDR_FONT_FREDERICKA, \"Fredericka the Great Essence.ttf\"},\n {CLOCK_IDC_FONT_FRIJOLE, IDR_FONT_FRIJOLE, \"Frijole Essence.ttf\"},\n {CLOCK_IDC_FONT_GWENDOLYN, IDR_FONT_GWENDOLYN, \"Gwendolyn Essence.ttf\"},\n {CLOCK_IDC_FONT_HANDJET, IDR_FONT_HANDJET, \"Handjet Essence.ttf\"},\n {CLOCK_IDC_FONT_INKNUT, IDR_FONT_INKNUT, \"Inknut Antiqua Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARD, IDR_FONT_JACQUARD, \"Jacquard 12 Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARDA, IDR_FONT_JACQUARDA, \"Jacquarda Bastarda 9 Essence.ttf\"},\n {CLOCK_IDC_FONT_KAVOON, IDR_FONT_KAVOON, \"Kavoon Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE, IDR_FONT_KUMAR_ONE_OUTLINE, \"Kumar One Outline Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE, IDR_FONT_KUMAR_ONE, \"Kumar One Essence.ttf\"},\n {CLOCK_IDC_FONT_LAKKI_REDDY, IDR_FONT_LAKKI_REDDY, \"Lakki Reddy Essence.ttf\"},\n {CLOCK_IDC_FONT_LICORICE, IDR_FONT_LICORICE, \"Licorice Essence.ttf\"},\n {CLOCK_IDC_FONT_MA_SHAN_ZHENG, IDR_FONT_MA_SHAN_ZHENG, \"Ma Shan Zheng Essence.ttf\"},\n {CLOCK_IDC_FONT_MOIRAI_ONE, IDR_FONT_MOIRAI_ONE, \"Moirai One Essence.ttf\"},\n {CLOCK_IDC_FONT_MYSTERY_QUEST, IDR_FONT_MYSTERY_QUEST, \"Mystery Quest Essence.ttf\"},\n {CLOCK_IDC_FONT_NOTO_NASTALIQ, IDR_FONT_NOTO_NASTALIQ, \"Noto Nastaliq Urdu Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PIEDRA, IDR_FONT_PIEDRA, \"Piedra Essence.ttf\"},\n {CLOCK_IDC_FONT_PINYON_SCRIPT, IDR_FONT_PINYON_SCRIPT, \"Pinyon Script Essence.ttf\"},\n {CLOCK_IDC_FONT_PIXELIFY, IDR_FONT_PIXELIFY, \"Pixelify Sans Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PRESS_START, IDR_FONT_PRESS_START, \"Press Start 2P Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BUBBLES, IDR_FONT_RUBIK_BUBBLES, \"Rubik Bubbles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BURNED, IDR_FONT_RUBIK_BURNED, \"Rubik Burned Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_GLITCH, IDR_FONT_RUBIK_GLITCH, \"Rubik Glitch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_MARKER_HATCH, IDR_FONT_RUBIK_MARKER_HATCH, \"Rubik Marker Hatch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_PUDDLES, IDR_FONT_RUBIK_PUDDLES, \"Rubik Puddles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_VINYL, IDR_FONT_RUBIK_VINYL, \"Rubik Vinyl Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_WET_PAINT, IDR_FONT_RUBIK_WET_PAINT, \"Rubik Wet Paint Essence.ttf\"},\n {CLOCK_IDC_FONT_RUGE_BOOGIE, IDR_FONT_RUGE_BOOGIE, \"Ruge Boogie Essence.ttf\"},\n {CLOCK_IDC_FONT_SEVILLANA, IDR_FONT_SEVILLANA, \"Sevillana Essence.ttf\"},\n {CLOCK_IDC_FONT_SILKSCREEN, IDR_FONT_SILKSCREEN, \"Silkscreen Essence.ttf\"},\n {CLOCK_IDC_FONT_STICK, IDR_FONT_STICK, \"Stick Essence.ttf\"},\n {CLOCK_IDC_FONT_UNDERDOG, IDR_FONT_UNDERDOG, \"Underdog Essence.ttf\"},\n {CLOCK_IDC_FONT_WALLPOET, IDR_FONT_WALLPOET, \"Wallpoet Essence.ttf\"},\n {CLOCK_IDC_FONT_YESTERYEAR, IDR_FONT_YESTERYEAR, \"Yesteryear Essence.ttf\"},\n {CLOCK_IDC_FONT_ZCOOL_KUAILE, IDR_FONT_ZCOOL_KUAILE, \"ZCOOL KuaiLe Essence.ttf\"},\n {CLOCK_IDC_FONT_PROFONT, IDR_FONT_PROFONT, \"ProFont IIx Nerd Font Essence.ttf\"},\n {CLOCK_IDC_FONT_DADDYTIME, IDR_FONT_DADDYTIME, \"DaddyTimeMono Nerd Font Propo Essence.ttf\"},\n};\n\n/// Number of font resources\nconst int FONT_RESOURCES_COUNT = sizeof(fontResources) / sizeof(FontResource);\n\n/// @name External variable declarations\n/// @{\nextern char CLOCK_TEXT_COLOR[]; ///< Current clock text color\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t maxLen); ///< Get configuration file path\nextern void ReadConfig(void); ///< Read configuration file\nextern int CALLBACK EnumFontFamExProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam); ///< Font enumeration callback function\n/// @}\n\nBOOL LoadFontFromResource(HINSTANCE hInstance, int resourceId) {\n // Find font resource\n HRSRC hResource = FindResource(hInstance, MAKEINTRESOURCE(resourceId), RT_FONT);\n if (hResource == NULL) {\n return FALSE;\n }\n\n // Load resource into memory\n HGLOBAL hMemory = LoadResource(hInstance, hResource);\n if (hMemory == NULL) {\n return FALSE;\n }\n\n // Lock resource\n void* fontData = LockResource(hMemory);\n if (fontData == NULL) {\n return FALSE;\n }\n\n // Get resource size and add font\n DWORD fontLength = SizeofResource(hInstance, hResource);\n DWORD nFonts = 0;\n HANDLE handle = AddFontMemResourceEx(fontData, fontLength, NULL, &nFonts);\n \n if (handle == NULL) {\n return FALSE;\n }\n \n return TRUE;\n}\n\nBOOL LoadFontByName(HINSTANCE hInstance, const char* fontName) {\n // Iterate through the font resource array to find a matching font\n for (int i = 0; i < sizeof(fontResources) / sizeof(FontResource); i++) {\n if (strcmp(fontResources[i].fontName, fontName) == 0) {\n return LoadFontFromResource(hInstance, fontResources[i].resourceId);\n }\n }\n return FALSE;\n}\n\nvoid WriteConfigFont(const char* font_file_name) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Open configuration file for reading\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n // Read the entire configuration file content\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n // Create new configuration file content\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n // Process line by line and replace font settings\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"FONT_FILE_NAME=\", 15) == 0) {\n strcat(new_config, \"FONT_FILE_NAME=\");\n strcat(new_config, font_file_name);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n // Write new configuration content\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n // Re-read configuration\n ReadConfig();\n}\n\nvoid ListAvailableFonts(void) {\n HDC hdc = GetDC(NULL);\n LOGFONT lf;\n memset(&lf, 0, sizeof(LOGFONT));\n lf.lfCharSet = DEFAULT_CHARSET;\n\n // Create temporary font and enumerate fonts\n HFONT hFont = CreateFont(12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n lf.lfCharSet, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, NULL);\n SelectObject(hdc, hFont);\n\n EnumFontFamiliesEx(hdc, &lf, (FONTENUMPROC)EnumFontFamExProc, 0, 0);\n\n // Clean up resources\n DeleteObject(hFont);\n ReleaseDC(NULL, hdc);\n}\n\nint CALLBACK EnumFontFamExProc(\n ENUMLOGFONTEX *lpelfe,\n NEWTEXTMETRICEX *lpntme,\n DWORD FontType,\n LPARAM lParam\n) {\n return 1;\n}\n\nBOOL PreviewFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Save current font name\n strncpy(PREVIEW_FONT_NAME, fontName, sizeof(PREVIEW_FONT_NAME) - 1);\n PREVIEW_FONT_NAME[sizeof(PREVIEW_FONT_NAME) - 1] = '\\0';\n \n // Get internal font name (remove .ttf extension)\n size_t name_len = strlen(PREVIEW_FONT_NAME);\n if (name_len > 4 && strcmp(PREVIEW_FONT_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(PREVIEW_INTERNAL_NAME))\n copy_len = sizeof(PREVIEW_INTERNAL_NAME) - 1;\n \n memcpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, copy_len);\n PREVIEW_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, sizeof(PREVIEW_INTERNAL_NAME) - 1);\n PREVIEW_INTERNAL_NAME[sizeof(PREVIEW_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Load preview font\n if (!LoadFontByName(hInstance, PREVIEW_FONT_NAME)) {\n return FALSE;\n }\n \n IS_PREVIEWING = TRUE;\n return TRUE;\n}\n\nvoid CancelFontPreview(void) {\n IS_PREVIEWING = FALSE;\n PREVIEW_FONT_NAME[0] = '\\0';\n PREVIEW_INTERNAL_NAME[0] = '\\0';\n}\n\nvoid ApplyFontPreview(void) {\n // Check if there is a valid preview font\n if (!IS_PREVIEWING || strlen(PREVIEW_FONT_NAME) == 0) return;\n \n // Update current font\n strncpy(FONT_FILE_NAME, PREVIEW_FONT_NAME, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n strncpy(FONT_INTERNAL_NAME, PREVIEW_INTERNAL_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n \n // Save to configuration file and cancel preview state\n WriteConfigFont(FONT_FILE_NAME);\n CancelFontPreview();\n}\n\nBOOL SwitchFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Load new font\n if (!LoadFontByName(hInstance, fontName)) {\n return FALSE;\n }\n \n // Update font name\n strncpy(FONT_FILE_NAME, fontName, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n // Update internal font name (remove .ttf extension)\n size_t name_len = strlen(FONT_FILE_NAME);\n if (name_len > 4 && strcmp(FONT_FILE_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Write to configuration file\n WriteConfigFont(FONT_FILE_NAME);\n return TRUE;\n}"], ["/Catime/src/tray_events.c", "/**\n * @file tray_events.c\n * @brief Implementation of system tray event handling module\n * \n * This module implements the event handling functionality for the application's system tray,\n * including response to various mouse events on the tray icon, menu display and control,\n * as well as tray operations related to the timer such as pause/resume and restart.\n * It provides core functionality for users to quickly control the application through the tray icon.\n */\n\n#include \n#include \n#include \"../include/tray_events.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/window_events.h\"\n#include \"../resource/resource.h\"\n\n// Declaration of function to read timeout action from configuration file\nextern void ReadTimeoutActionFromConfig(void);\n\n/**\n * @brief Handle system tray messages\n * @param hwnd Window handle\n * @param uID Tray icon ID\n * @param uMouseMsg Mouse message type\n * \n * Process mouse events for the system tray, displaying different context menus based on the event type:\n * - Left click: Display main function context menu, including timer control functions\n * - Right click: Display color selection menu for quickly changing display color\n * \n * All menu item command processing is implemented in the corresponding menu display module.\n */\nvoid HandleTrayIconMessage(HWND hwnd, UINT uID, UINT uMouseMsg) {\n // Set default cursor to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n if (uMouseMsg == WM_RBUTTONUP) {\n ShowColorMenu(hwnd);\n }\n else if (uMouseMsg == WM_LBUTTONUP) {\n ShowContextMenu(hwnd);\n }\n}\n\n/**\n * @brief Pause or resume timer\n * @param hwnd Window handle\n * \n * Toggle timer pause/resume state based on current status:\n * 1. Check if there is an active timer (countdown or count-up)\n * 2. If timer is active, toggle pause/resume state\n * 3. When paused, record current time point and stop timer\n * 4. When resumed, restart timer\n * 5. Refresh window to reflect new state\n * \n * Note: Can only operate when displaying timer (not current time) and timer is active\n */\nvoid PauseResumeTimer(HWND hwnd) {\n // Check if there is an active timer\n if (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || CLOCK_TOTAL_TIME > 0)) {\n \n // Toggle pause/resume state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n if (CLOCK_IS_PAUSED) {\n // If paused, record current time point\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n // Stop timer\n KillTimer(hwnd, 1);\n \n // Pause playing notification audio (new addition)\n extern BOOL PauseNotificationSound(void);\n PauseNotificationSound();\n } else {\n // If resumed, restart timer\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Resume notification audio (new addition)\n extern BOOL ResumeNotificationSound(void);\n ResumeNotificationSound();\n }\n \n // Update window to reflect new state\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart timer\n * @param hwnd Window handle\n * \n * Reset timer to initial state and continue running, keeping current timer type unchanged:\n * 1. Read current timeout action settings\n * 2. Reset timer progress based on current mode (countdown/count-up)\n * 3. Reset all related timer state variables\n * 4. Cancel pause state, ensure timer is running\n * 5. Refresh window and ensure window is on top after reset\n * \n * This operation does not change the timer mode or total duration, it only resets progress to initial state.\n */\nvoid RestartTimer(HWND hwnd) {\n // Stop any notification audio that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Determine operation based on current mode\n if (!CLOCK_COUNT_UP) {\n // Countdown mode\n if (CLOCK_TOTAL_TIME > 0) {\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n } else {\n // Count-up mode\n countup_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Update window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure window is on top and visible\n HandleWindowReset(hwnd);\n}\n\n/**\n * @brief Set startup mode\n * @param hwnd Window handle\n * @param mode Startup mode (\"COUNTDOWN\"/\"COUNT_UP\"/\"SHOW_TIME\"/\"NO_DISPLAY\")\n * \n * Set the application's default startup mode and save it to the configuration file:\n * 1. Save the selected mode to the configuration file\n * 2. Update menu item checked state to reflect current setting\n * 3. Refresh window display\n * \n * The startup mode determines the default behavior of the application at startup, such as whether to display current time or start timing.\n * The setting will take effect the next time the program starts.\n */\nvoid SetStartupMode(HWND hwnd, const char* mode) {\n // Save startup mode to configuration file\n WriteConfigStartupMode(mode);\n \n // Update menu item checked state\n HMENU hMenu = GetMenu(hwnd);\n if (hMenu) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Open user guide webpage\n * \n * Use ShellExecute to open Catime's user guide webpage,\n * providing detailed software instructions and help documentation for users.\n * URL: https://vladelaina.github.io/Catime/guide\n */\nvoid OpenUserGuide(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/guide\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open support page\n * \n * Use ShellExecute to open Catime's support page,\n * providing channels for users to support the developer.\n * URL: https://vladelaina.github.io/Catime/support\n */\nvoid OpenSupportPage(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open feedback page\n * \n * Open different feedback channels based on current language setting:\n * - Simplified Chinese: Open bilibili private message page\n * - Other languages: Open GitHub Issues page\n */\nvoid OpenFeedbackPage(void) {\n extern AppLanguage CURRENT_LANGUAGE; // Declare external variable\n \n // Choose different feedback links based on language\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP) {\n // Simplified Chinese users open bilibili private message\n ShellExecuteW(NULL, L\"open\", URL_FEEDBACK, NULL, NULL, SW_SHOWNORMAL);\n } else {\n // Users of other languages open GitHub Issues\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime/issues\", NULL, NULL, SW_SHOWNORMAL);\n }\n}"], ["/Catime/src/color.c", "/**\n * @file color.c\n * @brief Color processing functionality implementation\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/color.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n\nPredefinedColor* COLOR_OPTIONS = NULL;\nsize_t COLOR_OPTIONS_COUNT = 0;\nchar PREVIEW_COLOR[10] = \"\";\nBOOL IS_COLOR_PREVIEWING = FALSE;\nchar CLOCK_TEXT_COLOR[10] = \"#FFFFFF\";\n\nvoid GetConfigPath(char* path, size_t size);\nvoid CreateDefaultConfig(const char* config_path);\nvoid ReadConfig(void);\nvoid WriteConfig(const char* config_path);\nvoid replaceBlackColor(const char* color, char* output, size_t output_size);\n\nstatic const CSSColor CSS_COLORS[] = {\n {\"white\", \"#FFFFFF\"},\n {\"black\", \"#000000\"},\n {\"red\", \"#FF0000\"},\n {\"lime\", \"#00FF00\"},\n {\"blue\", \"#0000FF\"},\n {\"yellow\", \"#FFFF00\"},\n {\"cyan\", \"#00FFFF\"},\n {\"magenta\", \"#FF00FF\"},\n {\"silver\", \"#C0C0C0\"},\n {\"gray\", \"#808080\"},\n {\"maroon\", \"#800000\"},\n {\"olive\", \"#808000\"},\n {\"green\", \"#008000\"},\n {\"purple\", \"#800080\"},\n {\"teal\", \"#008080\"},\n {\"navy\", \"#000080\"},\n {\"orange\", \"#FFA500\"},\n {\"pink\", \"#FFC0CB\"},\n {\"brown\", \"#A52A2A\"},\n {\"violet\", \"#EE82EE\"},\n {\"indigo\", \"#4B0082\"},\n {\"gold\", \"#FFD700\"},\n {\"coral\", \"#FF7F50\"},\n {\"salmon\", \"#FA8072\"},\n {\"khaki\", \"#F0E68C\"},\n {\"plum\", \"#DDA0DD\"},\n {\"azure\", \"#F0FFFF\"},\n {\"ivory\", \"#FFFFF0\"},\n {\"wheat\", \"#F5DEB3\"},\n {\"snow\", \"#FFFAFA\"}\n};\n\n#define CSS_COLORS_COUNT (sizeof(CSS_COLORS) / sizeof(CSS_COLORS[0]))\n\nstatic const char* DEFAULT_COLOR_OPTIONS[] = {\n \"#FFFFFF\",\n \"#F9DB91\",\n \"#F4CAE0\",\n \"#FFB6C1\",\n \"#A8E7DF\",\n \"#A3CFB3\",\n \"#92CBFC\",\n \"#BDA5E7\",\n \"#9370DB\",\n \"#8C92CF\",\n \"#72A9A5\",\n \"#EB99A7\",\n \"#EB96BD\",\n \"#FFAE8B\",\n \"#FF7F50\",\n \"#CA6174\"\n};\n\n#define DEFAULT_COLOR_OPTIONS_COUNT (sizeof(DEFAULT_COLOR_OPTIONS) / sizeof(DEFAULT_COLOR_OPTIONS[0]))\n\nWNDPROC g_OldEditProc;\n\n#include \n\nCOLORREF ShowColorDialog(HWND hwnd) {\n CHOOSECOLOR cc = {0};\n static COLORREF acrCustClr[16] = {0};\n static DWORD rgbCurrent;\n\n int r, g, b;\n if (CLOCK_TEXT_COLOR[0] == '#') {\n sscanf(CLOCK_TEXT_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n } else {\n sscanf(CLOCK_TEXT_COLOR, \"%d,%d,%d\", &r, &g, &b);\n }\n rgbCurrent = RGB(r, g, b);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT && i < 16; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n if (hexColor[0] == '#') {\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n acrCustClr[i] = RGB(r, g, b);\n }\n }\n\n cc.lStructSize = sizeof(CHOOSECOLOR);\n cc.hwndOwner = hwnd;\n cc.lpCustColors = acrCustClr;\n cc.rgbResult = rgbCurrent;\n cc.Flags = CC_FULLOPEN | CC_RGBINIT | CC_ENABLEHOOK;\n cc.lpfnHook = ColorDialogHookProc;\n\n if (ChooseColor(&cc)) {\n COLORREF finalColor;\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n int r, g, b;\n sscanf(PREVIEW_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n finalColor = RGB(r, g, b);\n } else {\n finalColor = cc.rgbResult;\n }\n\n char tempColor[10];\n snprintf(tempColor, sizeof(tempColor), \"#%02X%02X%02X\",\n GetRValue(finalColor),\n GetGValue(finalColor),\n GetBValue(finalColor));\n\n char finalColorStr[10];\n replaceBlackColor(tempColor, finalColorStr, sizeof(finalColorStr));\n\n strncpy(CLOCK_TEXT_COLOR, finalColorStr, sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n\n IS_COLOR_PREVIEWING = FALSE;\n\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return finalColor;\n }\n\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return (COLORREF)-1;\n}\n\nUINT_PTR CALLBACK ColorDialogHookProc(HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HWND hwndParent;\n static CHOOSECOLOR* pcc;\n static BOOL isColorLocked = FALSE;\n static DWORD rgbCurrent;\n static COLORREF lastCustomColors[16] = {0};\n\n switch (msg) {\n case WM_INITDIALOG:\n pcc = (CHOOSECOLOR*)lParam;\n hwndParent = pcc->hwndOwner;\n rgbCurrent = pcc->rgbResult;\n isColorLocked = FALSE;\n \n for (int i = 0; i < 16; i++) {\n lastCustomColors[i] = pcc->lpCustColors[i];\n }\n return TRUE;\n\n case WM_LBUTTONDOWN:\n case WM_RBUTTONDOWN:\n isColorLocked = !isColorLocked;\n \n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n \n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n \n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n \n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n\n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_MOUSEMOVE:\n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n\n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n\n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n\n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n \n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n \n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_COMMAND:\n if (HIWORD(wParam) == BN_CLICKED) {\n switch (LOWORD(wParam)) {\n case IDOK: {\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n } else {\n snprintf(PREVIEW_COLOR, sizeof(PREVIEW_COLOR), \"#%02X%02X%02X\",\n GetRValue(pcc->rgbResult),\n GetGValue(pcc->rgbResult),\n GetBValue(pcc->rgbResult));\n }\n break;\n }\n \n case IDCANCEL:\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n break;\n }\n }\n break;\n\n case WM_CTLCOLORBTN:\n case WM_CTLCOLOREDIT:\n case WM_CTLCOLORSTATIC:\n if (pcc) {\n BOOL colorsChanged = FALSE;\n for (int i = 0; i < 16; i++) {\n if (lastCustomColors[i] != pcc->lpCustColors[i]) {\n colorsChanged = TRUE;\n lastCustomColors[i] = pcc->lpCustColors[i];\n \n char colorStr[20];\n snprintf(colorStr, sizeof(colorStr), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n \n }\n }\n \n if (colorsChanged) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n ClearColorOptions();\n \n for (int i = 0; i < 16; i++) {\n if (pcc->lpCustColors[i] != 0) {\n char hexColor[10];\n snprintf(hexColor, sizeof(hexColor), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n AddColorOption(hexColor);\n }\n }\n \n WriteConfig(config_path);\n }\n }\n break;\n }\n return 0;\n}\n\nvoid InitializeDefaultLanguage(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n ClearColorOptions();\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n CreateDefaultConfig(config_path);\n file = fopen(config_path, \"r\");\n }\n\n if (file) {\n char line[1024];\n BOOL found_colors = FALSE;\n\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"COLOR_OPTIONS=\", 13) == 0) {\n ClearColorOptions();\n\n char* colors = line + 13;\n while (*colors == '=' || *colors == ' ') {\n colors++;\n }\n\n char* newline = strchr(colors, '\\n');\n if (newline) *newline = '\\0';\n\n char* token = strtok(colors, \",\");\n while (token) {\n while (*token == ' ') token++;\n char* end = token + strlen(token) - 1;\n while (end > token && *end == ' ') {\n *end = '\\0';\n end--;\n }\n\n if (*token) {\n if (token[0] != '#') {\n char colorWithHash[10];\n snprintf(colorWithHash, sizeof(colorWithHash), \"#%s\", token);\n AddColorOption(colorWithHash);\n } else {\n AddColorOption(token);\n }\n }\n token = strtok(NULL, \",\");\n }\n found_colors = TRUE;\n break;\n }\n }\n fclose(file);\n\n if (!found_colors || COLOR_OPTIONS_COUNT == 0) {\n for (size_t i = 0; i < DEFAULT_COLOR_OPTIONS_COUNT; i++) {\n AddColorOption(DEFAULT_COLOR_OPTIONS[i]);\n }\n }\n }\n}\n\n/**\n * @brief Add color option\n */\nvoid AddColorOption(const char* hexColor) {\n if (!hexColor || !*hexColor) {\n return;\n }\n\n char normalizedColor[10];\n const char* hex = (hexColor[0] == '#') ? hexColor + 1 : hexColor;\n\n size_t len = strlen(hex);\n if (len != 6) {\n return;\n }\n\n for (int i = 0; i < 6; i++) {\n if (!isxdigit((unsigned char)hex[i])) {\n return;\n }\n }\n\n unsigned int color;\n if (sscanf(hex, \"%x\", &color) != 1) {\n return;\n }\n\n snprintf(normalizedColor, sizeof(normalizedColor), \"#%06X\", color);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (strcasecmp(normalizedColor, COLOR_OPTIONS[i].hexColor) == 0) {\n return;\n }\n }\n\n PredefinedColor* newArray = realloc(COLOR_OPTIONS,\n (COLOR_OPTIONS_COUNT + 1) * sizeof(PredefinedColor));\n if (newArray) {\n COLOR_OPTIONS = newArray;\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = _strdup(normalizedColor);\n COLOR_OPTIONS_COUNT++;\n }\n}\n\n/**\n * @brief Clear all color options\n */\nvoid ClearColorOptions(void) {\n if (COLOR_OPTIONS) {\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n free((void*)COLOR_OPTIONS[i].hexColor);\n }\n free(COLOR_OPTIONS);\n COLOR_OPTIONS = NULL;\n COLOR_OPTIONS_COUNT = 0;\n }\n}\n\n/**\n * @brief Write color to configuration file\n */\nvoid WriteConfigColor(const char* color_input) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"CLOCK_TEXT_COLOR=\", 17) == 0) {\n strcat(new_config, \"CLOCK_TEXT_COLOR=\");\n strcat(new_config, color_input);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n ReadConfig();\n}\n\n/**\n * @brief Normalize color format\n */\nvoid normalizeColor(const char* input, char* output, size_t output_size) {\n while (isspace(*input)) input++;\n\n char color[32];\n strncpy(color, input, sizeof(color)-1);\n color[sizeof(color)-1] = '\\0';\n for (char* p = color; *p; p++) {\n *p = tolower(*p);\n }\n\n for (size_t i = 0; i < CSS_COLORS_COUNT; i++) {\n if (strcmp(color, CSS_COLORS[i].name) == 0) {\n strncpy(output, CSS_COLORS[i].hex, output_size);\n return;\n }\n }\n\n char cleaned[32] = {0};\n int j = 0;\n for (int i = 0; color[i]; i++) {\n if (!isspace(color[i]) && color[i] != ',' && color[i] != '(' && color[i] != ')') {\n cleaned[j++] = color[i];\n }\n }\n cleaned[j] = '\\0';\n\n if (cleaned[0] == '#') {\n memmove(cleaned, cleaned + 1, strlen(cleaned));\n }\n\n if (strlen(cleaned) == 3) {\n snprintf(output, output_size, \"#%c%c%c%c%c%c\",\n cleaned[0], cleaned[0], cleaned[1], cleaned[1], cleaned[2], cleaned[2]);\n return;\n }\n\n if (strlen(cleaned) == 6 && strspn(cleaned, \"0123456789abcdefABCDEF\") == 6) {\n snprintf(output, output_size, \"#%s\", cleaned);\n return;\n }\n\n int r = -1, g = -1, b = -1;\n char* rgb_str = color;\n\n if (strncmp(rgb_str, \"rgb\", 3) == 0) {\n rgb_str += 3;\n while (*rgb_str && (*rgb_str == '(' || isspace(*rgb_str))) rgb_str++;\n }\n\n if (sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d %d %d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d|%d|%d\", &r, &g, &b) == 3) {\n\n if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) {\n snprintf(output, output_size, \"#%02X%02X%02X\", r, g, b);\n return;\n }\n }\n\n strncpy(output, input, output_size);\n}\n\n/**\n * @brief Check if color is valid\n */\nBOOL isValidColor(const char* input) {\n if (!input || !*input) return FALSE;\n\n char normalized[32];\n normalizeColor(input, normalized, sizeof(normalized));\n\n if (normalized[0] != '#' || strlen(normalized) != 7) {\n return FALSE;\n }\n\n for (int i = 1; i < 7; i++) {\n if (!isxdigit((unsigned char)normalized[i])) {\n return FALSE;\n }\n }\n\n int r, g, b;\n if (sscanf(normalized + 1, \"%02x%02x%02x\", &r, &g, &b) == 3) {\n return (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255);\n }\n\n return FALSE;\n}\n\n/**\n * @brief Color edit box subclass procedure\n */\nLRESULT CALLBACK ColorEditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_KEYDOWN:\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n case WM_COMMAND:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n return 0;\n }\n }\n break;\n\n case WM_CHAR:\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n }\n\n return result;\n\n case WM_PASTE:\n case WM_CUT: {\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n }\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n\n return result;\n }\n }\n\n return CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Color settings dialog procedure\n */\nINT_PTR CALLBACK ColorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit) {\n g_OldEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC,\n (LONG_PTR)ColorEditSubclassProc);\n\n if (CLOCK_TEXT_COLOR[0] != '\\0') {\n SetWindowTextA(hwndEdit, CLOCK_TEXT_COLOR);\n }\n }\n return TRUE;\n }\n\n case WM_COMMAND: {\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n char color[32];\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, color, sizeof(color));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; color[i]; i++) {\n if (!isspace((unsigned char)color[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (color[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n\n if (isValidColor(color)) {\n char normalized_color[10];\n normalizeColor(color, normalized_color, sizeof(normalized_color));\n strncpy(CLOCK_TEXT_COLOR, normalized_color, sizeof(CLOCK_TEXT_COLOR)-1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR)-1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n }\n return FALSE;\n}\n\n/**\n * @brief Replace pure black color with near-black\n */\nvoid replaceBlackColor(const char* color, char* output, size_t output_size) {\n if (color && (strcasecmp(color, \"#000000\") == 0)) {\n strncpy(output, \"#000001\", output_size);\n output[output_size - 1] = '\\0';\n } else {\n strncpy(output, color, output_size);\n output[output_size - 1] = '\\0';\n }\n}"], ["/Catime/src/hotkey.c", "/**\n * @file hotkey.c\n * @brief Hotkey management implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#if defined _M_IX86\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_IA64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_X64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#else\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#endif\n#include \"../include/hotkey.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../resource/resource.h\"\n\n#ifndef HOTKEYF_SHIFT\n#define HOTKEYF_SHIFT 0x01\n#define HOTKEYF_CONTROL 0x02\n#define HOTKEYF_ALT 0x04\n#endif\n\nstatic WORD g_dlgShowTimeHotkey = 0;\nstatic WORD g_dlgCountUpHotkey = 0;\nstatic WORD g_dlgCountdownHotkey = 0;\nstatic WORD g_dlgCustomCountdownHotkey = 0;\nstatic WORD g_dlgQuickCountdown1Hotkey = 0;\nstatic WORD g_dlgQuickCountdown2Hotkey = 0;\nstatic WORD g_dlgQuickCountdown3Hotkey = 0;\nstatic WORD g_dlgPomodoroHotkey = 0;\nstatic WORD g_dlgToggleVisibilityHotkey = 0;\nstatic WORD g_dlgEditModeHotkey = 0;\nstatic WORD g_dlgPauseResumeHotkey = 0;\nstatic WORD g_dlgRestartTimerHotkey = 0;\n\nstatic WNDPROC g_OldHotkeyDlgProc = NULL;\n\n/**\n * @brief Dialog subclassing procedure\n */\nLRESULT CALLBACK HotkeyDialogSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n if (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN || msg == WM_KEYUP || msg == WM_SYSKEYUP) {\n BYTE vk = (BYTE)wParam;\n if (!(vk == VK_SHIFT || vk == VK_CONTROL || vk == VK_MENU || vk == VK_LWIN || vk == VK_RWIN)) {\n BYTE currentModifiers = 0;\n if (GetKeyState(VK_SHIFT) & 0x8000) currentModifiers |= HOTKEYF_SHIFT;\n if (GetKeyState(VK_CONTROL) & 0x8000) currentModifiers |= HOTKEYF_CONTROL;\n if (msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP || (GetKeyState(VK_MENU) & 0x8000)) {\n currentModifiers |= HOTKEYF_ALT;\n }\n\n WORD currentEventKeyCombination = MAKEWORD(vk, currentModifiers);\n\n const WORD originalHotkeys[] = {\n g_dlgShowTimeHotkey, g_dlgCountUpHotkey, g_dlgCountdownHotkey,\n g_dlgQuickCountdown1Hotkey, g_dlgQuickCountdown2Hotkey, g_dlgQuickCountdown3Hotkey,\n g_dlgPomodoroHotkey, g_dlgToggleVisibilityHotkey, g_dlgEditModeHotkey,\n g_dlgPauseResumeHotkey, g_dlgRestartTimerHotkey\n };\n BOOL isAnOriginalHotkeyEvent = FALSE;\n for (size_t i = 0; i < sizeof(originalHotkeys) / sizeof(originalHotkeys[0]); ++i) {\n if (originalHotkeys[i] != 0 && originalHotkeys[i] == currentEventKeyCombination) {\n isAnOriginalHotkeyEvent = TRUE;\n break;\n }\n }\n\n if (isAnOriginalHotkeyEvent) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n }\n\n switch (msg) {\n case WM_SYSKEYDOWN:\n case WM_SYSKEYUP:\n {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (isHotkeyEditControl) {\n break;\n }\n }\n return 0;\n }\n\n case WM_KEYDOWN:\n case WM_KEYUP:\n {\n BYTE vk_code = (BYTE)wParam;\n if (vk_code == VK_SHIFT || vk_code == VK_CONTROL || vk_code == VK_LWIN || vk_code == VK_RWIN) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n break;\n\n case WM_SYSCOMMAND:\n if ((wParam & 0xFFF0) == SC_KEYMENU) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(g_OldHotkeyDlgProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Show hotkey settings dialog\n */\nvoid ShowHotkeySettingsDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_HOTKEY_DIALOG),\n hwndParent,\n HotkeySettingsDlgProc);\n}\n\n/**\n * @brief Check if a hotkey is a single key\n */\nBOOL IsSingleKey(WORD hotkey) {\n BYTE modifiers = HIBYTE(hotkey);\n\n return modifiers == 0;\n}\n\n/**\n * @brief Check if a hotkey is a standalone letter, number, or symbol\n */\nBOOL IsRestrictedSingleKey(WORD hotkey) {\n if (hotkey == 0) {\n return FALSE;\n }\n\n BYTE vk = LOBYTE(hotkey);\n BYTE modifiers = HIBYTE(hotkey);\n\n if (modifiers != 0) {\n return FALSE;\n }\n\n if (vk >= 'A' && vk <= 'Z') {\n return TRUE;\n }\n\n if (vk >= '0' && vk <= '9') {\n return TRUE;\n }\n\n if (vk >= VK_NUMPAD0 && vk <= VK_NUMPAD9) {\n return TRUE;\n }\n\n switch (vk) {\n case VK_OEM_1:\n case VK_OEM_PLUS:\n case VK_OEM_COMMA:\n case VK_OEM_MINUS:\n case VK_OEM_PERIOD:\n case VK_OEM_2:\n case VK_OEM_3:\n case VK_OEM_4:\n case VK_OEM_5:\n case VK_OEM_6:\n case VK_OEM_7:\n case VK_SPACE:\n case VK_RETURN:\n case VK_ESCAPE:\n case VK_TAB:\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey settings dialog message processing procedure\n */\nINT_PTR CALLBACK HotkeySettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL1,\n GetLocalizedString(L\"显示当前时间:\", L\"Show Current Time:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL2,\n GetLocalizedString(L\"正计时:\", L\"Count Up:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL12,\n GetLocalizedString(L\"倒计时:\", L\"Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL3,\n GetLocalizedString(L\"默认倒计时:\", L\"Default Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL9,\n GetLocalizedString(L\"快捷倒计时1:\", L\"Quick Countdown 1:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL10,\n GetLocalizedString(L\"快捷倒计时2:\", L\"Quick Countdown 2:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL11,\n GetLocalizedString(L\"快捷倒计时3:\", L\"Quick Countdown 3:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL4,\n GetLocalizedString(L\"开始番茄钟:\", L\"Start Pomodoro:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL5,\n GetLocalizedString(L\"隐藏/显示窗口:\", L\"Hide/Show Window:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL6,\n GetLocalizedString(L\"进入编辑模式:\", L\"Enter Edit Mode:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL7,\n GetLocalizedString(L\"暂停/继续计时:\", L\"Pause/Resume Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL8,\n GetLocalizedString(L\"重新开始计时:\", L\"Restart Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_NOTE,\n GetLocalizedString(L\"* 热键将全局生效\", L\"* Hotkeys will work globally\"));\n\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"确定\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"取消\", L\"Cancel\"));\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n ReadConfigHotkeys(&g_dlgShowTimeHotkey, &g_dlgCountUpHotkey, &g_dlgCountdownHotkey,\n &g_dlgQuickCountdown1Hotkey, &g_dlgQuickCountdown2Hotkey, &g_dlgQuickCountdown3Hotkey,\n &g_dlgPomodoroHotkey, &g_dlgToggleVisibilityHotkey, &g_dlgEditModeHotkey,\n &g_dlgPauseResumeHotkey, &g_dlgRestartTimerHotkey);\n\n ReadCustomCountdownHotkey(&g_dlgCustomCountdownHotkey);\n\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_SETHOTKEY, g_dlgShowTimeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_SETHOTKEY, g_dlgCountUpHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_SETHOTKEY, g_dlgCustomCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_SETHOTKEY, g_dlgCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_SETHOTKEY, g_dlgQuickCountdown1Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_SETHOTKEY, g_dlgQuickCountdown2Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_SETHOTKEY, g_dlgQuickCountdown3Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_SETHOTKEY, g_dlgPomodoroHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_SETHOTKEY, g_dlgToggleVisibilityHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_SETHOTKEY, g_dlgEditModeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_SETHOTKEY, g_dlgPauseResumeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_SETHOTKEY, g_dlgRestartTimerHotkey, 0);\n\n UnregisterGlobalHotkeys(GetParent(hwndDlg));\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n SetWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i, 0);\n }\n }\n\n g_OldHotkeyDlgProc = (WNDPROC)SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)HotkeyDialogSubclassProc);\n\n SetFocus(GetDlgItem(hwndDlg, IDCANCEL));\n\n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n \n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n \n case WM_LBUTTONDOWN: {\n POINT pt = {LOWORD(lParam), HIWORD(lParam)};\n HWND hwndHit = ChildWindowFromPoint(hwndDlg, pt);\n\n if (hwndHit != NULL && hwndHit != hwndDlg) {\n int ctrlId = GetDlgCtrlID(hwndHit);\n\n BOOL isHotkeyEdit = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) {\n isHotkeyEdit = TRUE;\n break;\n }\n }\n\n if (!isHotkeyEdit) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n }\n }\n else if (hwndHit == hwndDlg) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND: {\n WORD ctrlId = LOWORD(wParam);\n WORD notifyCode = HIWORD(wParam);\n\n if (notifyCode == EN_CHANGE &&\n (ctrlId == IDC_HOTKEY_EDIT1 || ctrlId == IDC_HOTKEY_EDIT2 ||\n ctrlId == IDC_HOTKEY_EDIT3 || ctrlId == IDC_HOTKEY_EDIT4 ||\n ctrlId == IDC_HOTKEY_EDIT5 || ctrlId == IDC_HOTKEY_EDIT6 ||\n ctrlId == IDC_HOTKEY_EDIT7 || ctrlId == IDC_HOTKEY_EDIT8 ||\n ctrlId == IDC_HOTKEY_EDIT9 || ctrlId == IDC_HOTKEY_EDIT10 ||\n ctrlId == IDC_HOTKEY_EDIT11 || ctrlId == IDC_HOTKEY_EDIT12)) {\n\n WORD newHotkey = (WORD)SendDlgItemMessage(hwndDlg, ctrlId, HKM_GETHOTKEY, 0, 0);\n\n BYTE vk = LOBYTE(newHotkey);\n BYTE modifiers = HIBYTE(newHotkey);\n\n if (vk == 0xE5 && modifiers == HOTKEYF_SHIFT) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0 && IsRestrictedSingleKey(newHotkey)) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0) {\n static const int hotkeyCtrlIds[] = {\n IDC_HOTKEY_EDIT1, IDC_HOTKEY_EDIT2, IDC_HOTKEY_EDIT3,\n IDC_HOTKEY_EDIT9, IDC_HOTKEY_EDIT10, IDC_HOTKEY_EDIT11,\n IDC_HOTKEY_EDIT4, IDC_HOTKEY_EDIT5, IDC_HOTKEY_EDIT6,\n IDC_HOTKEY_EDIT7, IDC_HOTKEY_EDIT8, IDC_HOTKEY_EDIT12\n };\n\n for (int i = 0; i < sizeof(hotkeyCtrlIds) / sizeof(hotkeyCtrlIds[0]); i++) {\n if (hotkeyCtrlIds[i] == ctrlId) {\n continue;\n }\n\n WORD otherHotkey = (WORD)SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_GETHOTKEY, 0, 0);\n\n if (otherHotkey != 0 && otherHotkey == newHotkey) {\n SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_SETHOTKEY, 0, 0);\n }\n }\n }\n\n return TRUE;\n }\n \n switch (LOWORD(wParam)) {\n case IDOK: {\n WORD showTimeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_GETHOTKEY, 0, 0);\n WORD countUpHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_GETHOTKEY, 0, 0);\n WORD customCountdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_GETHOTKEY, 0, 0);\n WORD countdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown1Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown2Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown3Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_GETHOTKEY, 0, 0);\n WORD pomodoroHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_GETHOTKEY, 0, 0);\n WORD toggleVisibilityHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_GETHOTKEY, 0, 0);\n WORD editModeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_GETHOTKEY, 0, 0);\n WORD pauseResumeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_GETHOTKEY, 0, 0);\n WORD restartTimerHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_GETHOTKEY, 0, 0);\n\n WORD* hotkeys[] = {\n &showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey, &customCountdownHotkey\n };\n\n for (int i = 0; i < sizeof(hotkeys) / sizeof(hotkeys[0]); i++) {\n if (LOBYTE(*hotkeys[i]) == 0xE5 && HIBYTE(*hotkeys[i]) == HOTKEYF_SHIFT) {\n *hotkeys[i] = 0;\n continue;\n }\n\n if (*hotkeys[i] != 0 && IsRestrictedSingleKey(*hotkeys[i])) {\n *hotkeys[i] = 0;\n }\n }\n\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n g_dlgCustomCountdownHotkey = customCountdownHotkey;\n char customCountdownStr[64] = {0};\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr);\n\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n\n case IDCANCEL:\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n \n case WM_DESTROY:\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n if (g_OldHotkeyDlgProc) {\n SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)g_OldHotkeyDlgProc);\n g_OldHotkeyDlgProc = NULL;\n }\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n RemoveWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i);\n }\n }\n break;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey control subclass procedure\n */\nLRESULT CALLBACK HotkeyControlSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam,\n LPARAM lParam, UINT_PTR uIdSubclass,\n DWORD_PTR dwRefData) {\n switch (uMsg) {\n case WM_GETDLGCODE:\n return DLGC_WANTALLKEYS | DLGC_WANTCHARS;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(hwndDlg, IDOK));\n return 0;\n }\n }\n break;\n }\n\n return DefSubclassProc(hwnd, uMsg, wParam, lParam);\n}"], ["/Catime/src/drawing.c", "/**\n * @file drawing.c\n * @brief Window drawing functionality implementation\n * \n * This file implements the drawing-related functionality of the application window,\n * including text rendering, color settings, and window content drawing.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/drawing.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n\n// Variable imported from window_procedure.c\nextern int elapsed_time;\n\n// Using window drawing related constants defined in resource.h\n\nvoid HandleWindowPaint(HWND hwnd, PAINTSTRUCT *ps) {\n static char time_text[50];\n HDC hdc = ps->hdc;\n RECT rect;\n GetClientRect(hwnd, &rect);\n\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, rect.right, rect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n\n SetGraphicsMode(memDC, GM_ADVANCED);\n SetBkMode(memDC, TRANSPARENT);\n SetStretchBltMode(memDC, HALFTONE);\n SetBrushOrgEx(memDC, 0, 0, NULL);\n\n // Generate display text based on different modes\n if (CLOCK_SHOW_CURRENT_TIME) {\n time_t now = time(NULL);\n struct tm *tm_info = localtime(&now);\n int hour = tm_info->tm_hour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, tm_info->tm_min, tm_info->tm_sec);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, tm_info->tm_min);\n }\n } else if (CLOCK_COUNT_UP) {\n // Count-up mode\n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n } else {\n // Countdown mode\n int remaining_time = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining_time <= 0) {\n // Timeout reached, decide whether to display content based on conditions\n if (CLOCK_TOTAL_TIME == 0 && countdown_elapsed_time == 0) {\n // This is the case after sleep operation, don't display anything\n time_text[0] = '\\0';\n } else if (strcmp(CLOCK_TIMEOUT_TEXT, \"0\") == 0) {\n time_text[0] = '\\0';\n } else if (strlen(CLOCK_TIMEOUT_TEXT) > 0) {\n strncpy(time_text, CLOCK_TIMEOUT_TEXT, sizeof(time_text) - 1);\n time_text[sizeof(time_text) - 1] = '\\0';\n } else {\n time_text[0] = '\\0';\n }\n } else {\n int hours = remaining_time / 3600;\n int minutes = (remaining_time % 3600) / 60;\n int seconds = remaining_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n }\n }\n\n const char* fontToUse = IS_PREVIEWING ? PREVIEW_FONT_NAME : FONT_FILE_NAME;\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE * CLOCK_FONT_SCALE_FACTOR,\n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_TT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, \n VARIABLE_PITCH | FF_SWISS,\n IS_PREVIEWING ? PREVIEW_INTERNAL_NAME : FONT_INTERNAL_NAME\n );\n HFONT oldFont = (HFONT)SelectObject(memDC, hFont);\n\n SetTextAlign(memDC, TA_LEFT | TA_TOP);\n SetTextCharacterExtra(memDC, 0);\n SetMapMode(memDC, MM_TEXT);\n\n DWORD quality = SetICMMode(memDC, ICM_ON);\n SetLayout(memDC, 0);\n\n int r = 255, g = 255, b = 255;\n const char* colorToUse = IS_COLOR_PREVIEWING ? PREVIEW_COLOR : CLOCK_TEXT_COLOR;\n \n if (strlen(colorToUse) > 0) {\n if (colorToUse[0] == '#') {\n if (strlen(colorToUse) == 7) {\n sscanf(colorToUse + 1, \"%02x%02x%02x\", &r, &g, &b);\n }\n } else {\n sscanf(colorToUse, \"%d,%d,%d\", &r, &g, &b);\n }\n }\n SetTextColor(memDC, RGB(r, g, b));\n\n if (CLOCK_EDIT_MODE) {\n HBRUSH hBrush = CreateSolidBrush(RGB(20, 20, 20)); // Dark gray background\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n } else {\n HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0));\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n }\n\n if (strlen(time_text) > 0) {\n SIZE textSize;\n GetTextExtentPoint32(memDC, time_text, strlen(time_text), &textSize);\n\n if (textSize.cx != (rect.right - rect.left) || \n textSize.cy != (rect.bottom - rect.top)) {\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left, windowRect.top,\n textSize.cx + WINDOW_HORIZONTAL_PADDING, \n textSize.cy + WINDOW_VERTICAL_PADDING, \n SWP_NOZORDER | SWP_NOACTIVATE);\n GetClientRect(hwnd, &rect);\n }\n\n \n int x = (rect.right - textSize.cx) / 2;\n int y = (rect.bottom - textSize.cy) / 2;\n\n // If in edit mode, force white text and add outline effect\n if (CLOCK_EDIT_MODE) {\n SetTextColor(memDC, RGB(255, 255, 255));\n \n // Add black outline effect\n SetTextColor(memDC, RGB(0, 0, 0));\n TextOutA(memDC, x-1, y, time_text, strlen(time_text));\n TextOutA(memDC, x+1, y, time_text, strlen(time_text));\n TextOutA(memDC, x, y-1, time_text, strlen(time_text));\n TextOutA(memDC, x, y+1, time_text, strlen(time_text));\n \n // Set back to white for drawing text\n SetTextColor(memDC, RGB(255, 255, 255));\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n } else {\n SetTextColor(memDC, RGB(r, g, b));\n \n for (int i = 0; i < 8; i++) {\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n }\n }\n }\n\n BitBlt(hdc, 0, 0, rect.right, rect.bottom, memDC, 0, 0, SRCCOPY);\n\n SelectObject(memDC, oldFont);\n DeleteObject(hFont);\n SelectObject(memDC, oldBitmap);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n}"], ["/Catime/src/audio_player.c", "/**\n * @file audio_player.c\n * @brief Audio playback functionality handler\n */\n\n#include \n#include \n#include \n#include \"../libs/miniaudio/miniaudio.h\"\n\n#include \"config.h\"\n\nextern char NOTIFICATION_SOUND_FILE[MAX_PATH];\nextern int NOTIFICATION_SOUND_VOLUME;\n\ntypedef void (*AudioPlaybackCompleteCallback)(HWND hwnd);\n\nstatic ma_engine g_audioEngine;\nstatic ma_sound g_sound;\nstatic ma_bool32 g_engineInitialized = MA_FALSE;\nstatic ma_bool32 g_soundInitialized = MA_FALSE;\n\nstatic AudioPlaybackCompleteCallback g_audioCompleteCallback = NULL;\nstatic HWND g_audioCallbackHwnd = NULL;\nstatic UINT_PTR g_audioTimerId = 0;\n\nstatic ma_bool32 g_isPlaying = MA_FALSE;\nstatic ma_bool32 g_isPaused = MA_FALSE;\n\nstatic void CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime);\n\n/**\n * @brief Initialize audio engine\n */\nstatic BOOL InitializeAudioEngine() {\n if (g_engineInitialized) {\n return TRUE;\n }\n\n ma_result result = ma_engine_init(NULL, &g_audioEngine);\n if (result != MA_SUCCESS) {\n return FALSE;\n }\n\n g_engineInitialized = MA_TRUE;\n return TRUE;\n}\n\n/**\n * @brief Clean up audio engine resources\n */\nstatic void UninitializeAudioEngine() {\n if (g_engineInitialized) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n ma_engine_uninit(&g_audioEngine);\n g_engineInitialized = MA_FALSE;\n }\n}\n\n/**\n * @brief Check if a file exists\n */\nstatic BOOL FileExists(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2);\n\n DWORD dwAttrib = GetFileAttributesW(wFilePath);\n return (dwAttrib != INVALID_FILE_ATTRIBUTES &&\n !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));\n}\n\n/**\n * @brief Show error message dialog\n */\nstatic void ShowErrorMessage(HWND hwnd, const wchar_t* errorMsg) {\n MessageBoxW(hwnd, errorMsg, L\"Audio Playback Error\", MB_ICONERROR | MB_OK);\n}\n\n/**\n * @brief Timer callback to check if audio playback is complete\n */\nstatic void CALLBACK CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n if (g_engineInitialized && g_soundInitialized) {\n if (!ma_sound_is_playing(&g_sound) && !g_isPaused) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n } else {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n}\n\n/**\n * @brief System beep playback completion callback timer function\n */\nstatic void CALLBACK SystemBeepDoneCallback(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n}\n\n/**\n * @brief Set audio playback volume\n * @param volume Volume percentage (0-100)\n */\nvoid SetAudioVolume(int volume) {\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n\n if (g_engineInitialized) {\n float volFloat = (float)volume / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volFloat);\n\n if (g_soundInitialized && g_isPlaying) {\n ma_sound_set_volume(&g_sound, volFloat);\n }\n }\n}\n\n/**\n * @brief Play audio file using miniaudio\n */\nstatic BOOL PlayAudioWithMiniaudio(HWND hwnd, const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (!g_engineInitialized) {\n if (!InitializeAudioEngine()) {\n return FALSE;\n }\n }\n\n float volume = (float)NOTIFICATION_SOUND_VOLUME / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volume);\n\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n if (MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (UTF-8->Unicode): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n wchar_t shortPath[MAX_PATH] = {0};\n DWORD shortPathLen = GetShortPathNameW(wFilePath, shortPath, MAX_PATH);\n if (shortPathLen == 0 || shortPathLen >= MAX_PATH) {\n DWORD error = GetLastError();\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Failed to get short path: %ls\\nError code: %lu\", wFilePath, error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n char asciiPath[MAX_PATH] = {0};\n if (WideCharToMultiByte(CP_ACP, 0, shortPath, -1, asciiPath, MAX_PATH, NULL, NULL) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (Short Path->ASCII): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n return FALSE;\n }\n\n ma_result result = ma_sound_init_from_file(&g_audioEngine, asciiPath, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n char utf8Path[MAX_PATH * 4] = {0};\n WideCharToMultiByte(CP_UTF8, 0, wFilePath, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n\n result = ma_sound_init_from_file(&g_audioEngine, utf8Path, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Unable to load audio file: %ls\\nError code: %d\", wFilePath, result);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n }\n\n g_soundInitialized = MA_TRUE;\n\n if (ma_sound_start(&g_sound) != MA_SUCCESS) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n ShowErrorMessage(hwnd, L\"Cannot start audio playback\");\n return FALSE;\n }\n\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1001, 500, (TIMERPROC)CheckAudioPlaybackComplete);\n\n return TRUE;\n}\n\n/**\n * @brief Validate if file path is legal\n */\nstatic BOOL IsValidFilePath(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (strchr(filePath, '=') != NULL) return FALSE;\n\n if (strlen(filePath) >= MAX_PATH) return FALSE;\n\n return TRUE;\n}\n\n/**\n * @brief Clean up audio resources\n */\nvoid CleanupAudioResources(void) {\n PlaySound(NULL, NULL, SND_PURGE);\n\n if (g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n if (g_audioTimerId != 0 && g_audioCallbackHwnd != NULL) {\n KillTimer(g_audioCallbackHwnd, g_audioTimerId);\n g_audioTimerId = 0;\n }\n\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n}\n\n/**\n * @brief Set audio playback completion callback function\n */\nvoid SetAudioPlaybackCompleteCallback(HWND hwnd, AudioPlaybackCompleteCallback callback) {\n g_audioCallbackHwnd = hwnd;\n g_audioCompleteCallback = callback;\n}\n\n/**\n * @brief Play notification audio\n */\nBOOL PlayNotificationSound(HWND hwnd) {\n CleanupAudioResources();\n\n g_audioCallbackHwnd = hwnd;\n\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (!IsValidFilePath(NOTIFICATION_SOUND_FILE)) {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Invalid audio file path:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (FileExists(NOTIFICATION_SOUND_FILE)) {\n if (PlayAudioWithMiniaudio(hwnd, NOTIFICATION_SOUND_FILE)) {\n return TRUE;\n }\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n } else {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Cannot find the configured audio file:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Pause currently playing notification audio\n */\nBOOL PauseNotificationSound(void) {\n if (g_isPlaying && !g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n g_isPaused = MA_TRUE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Resume previously paused notification audio\n */\nBOOL ResumeNotificationSound(void) {\n if (g_isPlaying && g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_start(&g_sound);\n g_isPaused = MA_FALSE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Stop playing notification audio\n */\nvoid StopNotificationSound(void) {\n CleanupAudioResources();\n}"], ["/Catime/src/dialog_language.c", "/**\n * @file dialog_language.c\n * @brief Dialog multi-language support module implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \"../include/dialog_language.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\ntypedef struct {\n int dialogID;\n wchar_t* titleKey;\n} DialogTitleEntry;\n\ntypedef struct {\n int dialogID;\n int controlID;\n wchar_t* textKey;\n wchar_t* fallbackText;\n} SpecialControlEntry;\n\ntypedef struct {\n HWND hwndDlg;\n int dialogID;\n} EnumChildWindowsData;\n\nstatic DialogTitleEntry g_dialogTitles[] = {\n {IDD_ABOUT_DIALOG, L\"About\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, L\"Notification Settings\"},\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, L\"Set Pomodoro Loop Count\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, L\"Set Pomodoro Time Combination\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, L\"Set Pomodoro Time\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, L\"Countdown Presets\"},\n {CLOCK_IDD_WEBSITE_DIALOG, L\"Open Website\"},\n {CLOCK_IDD_DIALOG1, L\"Set Countdown\"},\n {IDD_NO_UPDATE_DIALOG, L\"Update Check\"},\n {IDD_UPDATE_DIALOG, L\"Update Available\"}\n};\n\nstatic SpecialControlEntry g_specialControls[] = {\n {IDD_ABOUT_DIALOG, IDC_ABOUT_TITLE, L\"关于\", L\"About\"},\n {IDD_ABOUT_DIALOG, IDC_VERSION_TEXT, L\"Version: %hs\", L\"Version: %hs\"},\n {IDD_ABOUT_DIALOG, IDC_BUILD_DATE, L\"构建日期:\", L\"Build Date:\"},\n {IDD_ABOUT_DIALOG, IDC_COPYRIGHT, L\"COPYRIGHT_TEXT\", L\"COPYRIGHT_TEXT\"},\n {IDD_ABOUT_DIALOG, IDC_CREDITS, L\"鸣谢\", L\"Credits\"},\n\n {IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT, L\"NoUpdateRequired\", L\"You are already using the latest version!\"},\n\n {IDD_UPDATE_DIALOG, IDC_UPDATE_TEXT, L\"CurrentVersion: %s\\nNewVersion: %s\", L\"Current Version: %s\\nNew Version: %s\"},\n {IDD_UPDATE_DIALOG, IDC_UPDATE_EXIT_TEXT, L\"The application will exit now\", L\"The application will exit now\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_CONTENT_GROUP, L\"Notification Content\", L\"Notification Content\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL1, L\"Countdown timeout message:\", L\"Countdown timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL2, L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL3, L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_DISPLAY_GROUP, L\"Notification Display\", L\"Notification Display\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TIME_LABEL, L\"Notification display time:\", L\"Notification display time:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_LABEL, L\"Maximum notification opacity (1-100%):\", L\"Maximum notification opacity (1-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_DISABLE_NOTIFICATION_CHECK, L\"Disable notifications\", L\"Disable notifications\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_METHOD_GROUP, L\"Notification Method\", L\"Notification Method\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_CATIME, L\"Catime notification window\", L\"Catime notification window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_OS, L\"System notification\", L\"System notification\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, L\"System modal window\", L\"System modal window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_SOUND_LABEL, L\"Sound (supports .mp3/.wav/.flac):\", L\"Sound (supports .mp3/.wav/.flac):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_LABEL, L\"Volume (0-100%):\", L\"Volume (0-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_TEXT, L\"100%\", L\"100%\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_TEXT, L\"100%\", L\"100%\"},\n\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_STATIC,\n L\"25=25 minutes\\\\n25h=25 hours\\\\n25s=25 seconds\\\\n25 30=25 minutes 30 seconds\\\\n25 30m=25 hours 30 minutes\\\\n1 30 20=1 hour 30 minutes 20 seconds\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\"},\n\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter pomodoro time sequence, separated by spaces:\\\\n\\\\n25m = 25 minutes\\\\n30s = 30 seconds\\\\n1h30m = 1 hour 30 minutes\\\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\",\n L\"Enter pomodoro time sequence, separated by spaces:\\n\\n25m = 25 minutes\\n30s = 30 seconds\\n1h30m = 1 hour 30 minutes\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\"},\n\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter the website URL to open when the countdown ends:\\\\nExample: https://github.com/vladelaina/Catime\",\n L\"Enter the website URL to open when the countdown ends:\\nExample: https://github.com/vladelaina/Catime\"},\n\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_STATIC,\n L\"CountdownPresetDialogStaticText\",\n L\"Enter numbers (minutes), separated by spaces\\n\\n25 10 5\\n\\nThis will create options for 25 minutes, 10 minutes, and 5 minutes\"},\n\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_STATIC,\n L\"CountdownDialogStaticText\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\\n17 20t=Countdown to 17:20\\n9 9 9t=Countdown to 09:09:09\"}\n};\n\nstatic SpecialControlEntry g_specialButtons[] = {\n {IDD_UPDATE_DIALOG, IDYES, L\"Yes\", L\"Yes\"},\n {IDD_UPDATE_DIALOG, IDNO, L\"No\", L\"No\"},\n {IDD_UPDATE_DIALOG, IDOK, L\"OK\", L\"OK\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_TEST_SOUND_BUTTON, L\"Test\", L\"Test\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_OPEN_SOUND_DIR_BUTTON, L\"Audio folder\", L\"Audio folder\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDOK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDCANCEL, L\"Cancel\", L\"Cancel\"},\n\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"}\n};\n\n#define DIALOG_TITLES_COUNT (sizeof(g_dialogTitles) / sizeof(g_dialogTitles[0]))\n#define SPECIAL_CONTROLS_COUNT (sizeof(g_specialControls) / sizeof(g_specialControls[0]))\n#define SPECIAL_BUTTONS_COUNT (sizeof(g_specialButtons) / sizeof(g_specialButtons[0]))\n\n/**\n * @brief Find localized text for special controls\n */\nstatic const wchar_t* FindSpecialControlText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_CONTROLS_COUNT; i++) {\n if (g_specialControls[i].dialogID == dialogID &&\n g_specialControls[i].controlID == controlID) {\n const wchar_t* localizedText = GetLocalizedString(NULL, g_specialControls[i].textKey);\n if (localizedText) {\n return localizedText;\n } else {\n return g_specialControls[i].fallbackText;\n }\n }\n }\n return NULL;\n}\n\n/**\n * @brief Find localized text for special buttons\n */\nstatic const wchar_t* FindSpecialButtonText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_BUTTONS_COUNT; i++) {\n if (g_specialButtons[i].dialogID == dialogID &&\n g_specialButtons[i].controlID == controlID) {\n return GetLocalizedString(NULL, g_specialButtons[i].textKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get localized text for dialog title\n */\nstatic const wchar_t* GetDialogTitleText(int dialogID) {\n for (int i = 0; i < DIALOG_TITLES_COUNT; i++) {\n if (g_dialogTitles[i].dialogID == dialogID) {\n return GetLocalizedString(NULL, g_dialogTitles[i].titleKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get original text of a control for translation lookup\n */\nstatic BOOL GetControlOriginalText(HWND hwndCtl, wchar_t* buffer, int bufferSize) {\n wchar_t className[256];\n GetClassNameW(hwndCtl, className, 256);\n\n if (wcscmp(className, L\"Button\") == 0 ||\n wcscmp(className, L\"Static\") == 0 ||\n wcscmp(className, L\"ComboBox\") == 0 ||\n wcscmp(className, L\"Edit\") == 0) {\n return GetWindowTextW(hwndCtl, buffer, bufferSize) > 0;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Process special control text settings, such as line breaks\n */\nstatic BOOL ProcessSpecialControlText(HWND hwndCtl, const wchar_t* localizedText, int dialogID, int controlID) {\n if ((dialogID == CLOCK_IDD_POMODORO_COMBO_DIALOG ||\n dialogID == CLOCK_IDD_POMODORO_TIME_DIALOG ||\n dialogID == CLOCK_IDD_WEBSITE_DIALOG ||\n dialogID == CLOCK_IDD_SHORTCUT_DIALOG ||\n dialogID == CLOCK_IDD_DIALOG1) &&\n controlID == CLOCK_IDC_STATIC) {\n wchar_t processedText[1024];\n const wchar_t* src = localizedText;\n wchar_t* dst = processedText;\n\n while (*src) {\n if (src[0] == L'\\\\' && src[1] == L'n') {\n *dst++ = L'\\n';\n src += 2;\n }\n else if (src[0] == L'\\n') {\n *dst++ = L'\\n';\n src++;\n }\n else {\n *dst++ = *src++;\n }\n }\n *dst = L'\\0';\n\n SetWindowTextW(hwndCtl, processedText);\n return TRUE;\n }\n\n if (controlID == IDC_VERSION_TEXT && dialogID == IDD_ABOUT_DIALOG) {\n wchar_t versionText[256];\n const wchar_t* localizedVersionFormat = GetLocalizedString(NULL, L\"Version: %hs\");\n if (localizedVersionFormat) {\n StringCbPrintfW(versionText, sizeof(versionText), localizedVersionFormat, CATIME_VERSION);\n } else {\n StringCbPrintfW(versionText, sizeof(versionText), localizedText, CATIME_VERSION);\n }\n SetWindowTextW(hwndCtl, versionText);\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Dialog child window enumeration callback function\n */\nstatic BOOL CALLBACK EnumChildProc(HWND hwndCtl, LPARAM lParam) {\n EnumChildWindowsData* data = (EnumChildWindowsData*)lParam;\n HWND hwndDlg = data->hwndDlg;\n int dialogID = data->dialogID;\n\n int controlID = GetDlgCtrlID(hwndCtl);\n if (controlID == 0) {\n return TRUE;\n }\n\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n if (ProcessSpecialControlText(hwndCtl, specialText, dialogID, controlID)) {\n return TRUE;\n }\n SetWindowTextW(hwndCtl, specialText);\n return TRUE;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n SetWindowTextW(hwndCtl, buttonText);\n return TRUE;\n }\n\n wchar_t originalText[512] = {0};\n if (GetControlOriginalText(hwndCtl, originalText, 512) && originalText[0] != L'\\0') {\n const wchar_t* localizedText = GetLocalizedString(NULL, originalText);\n if (localizedText && wcscmp(localizedText, originalText) != 0) {\n SetWindowTextW(hwndCtl, localizedText);\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Initialize dialog multi-language support\n */\nBOOL InitDialogLanguageSupport(void) {\n return TRUE;\n}\n\n/**\n * @brief Apply multi-language support to dialog\n */\nBOOL ApplyDialogLanguage(HWND hwndDlg, int dialogID) {\n if (!hwndDlg) return FALSE;\n\n const wchar_t* titleText = GetDialogTitleText(dialogID);\n if (titleText) {\n SetWindowTextW(hwndDlg, titleText);\n }\n\n EnumChildWindowsData data = {\n .hwndDlg = hwndDlg,\n .dialogID = dialogID\n };\n\n EnumChildWindows(hwndDlg, EnumChildProc, (LPARAM)&data);\n\n return TRUE;\n}\n\n/**\n * @brief Get localized text for dialog element\n */\nconst wchar_t* GetDialogLocalizedString(int dialogID, int controlID) {\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n return specialText;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n return buttonText;\n }\n\n if (controlID == -1) {\n return GetDialogTitleText(dialogID);\n }\n\n return NULL;\n}"], ["/Catime/src/tray.c", "/**\n * @file tray.c\n * @brief System tray functionality implementation\n */\n\n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/tray.h\"\n\nNOTIFYICONDATAW nid;\nUINT WM_TASKBARCREATED = 0;\n\n/**\n * @brief Register the TaskbarCreated message\n */\nvoid RegisterTaskbarCreatedMessage() {\n WM_TASKBARCREATED = RegisterWindowMessage(TEXT(\"TaskbarCreated\"));\n}\n\n/**\n * @brief Initialize the system tray icon\n * @param hwnd Window handle\n * @param hInstance Application instance handle\n */\nvoid InitTrayIcon(HWND hwnd, HINSTANCE hInstance) {\n memset(&nid, 0, sizeof(nid));\n nid.cbSize = sizeof(nid);\n nid.uID = CLOCK_ID_TRAY_APP_ICON;\n nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;\n nid.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CATIME));\n nid.hWnd = hwnd;\n nid.uCallbackMessage = CLOCK_WM_TRAYICON;\n \n wchar_t versionText[128] = {0};\n wchar_t versionWide[64] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CATIME_VERSION, -1, versionWide, _countof(versionWide));\n swprintf_s(versionText, _countof(versionText), L\"Catime %s\", versionWide);\n wcscpy_s(nid.szTip, _countof(nid.szTip), versionText);\n \n Shell_NotifyIconW(NIM_ADD, &nid);\n if (WM_TASKBARCREATED == 0) {\n RegisterTaskbarCreatedMessage();\n }\n}\n\n/**\n * @brief Remove the system tray icon\n */\nvoid RemoveTrayIcon(void) {\n Shell_NotifyIconW(NIM_DELETE, &nid);\n}\n\n/**\n * @brief Display a notification in the system tray\n * @param hwnd Window handle\n * @param message Text message to display\n */\nvoid ShowTrayNotification(HWND hwnd, const char* message) {\n NOTIFYICONDATAW nid_notify = {0};\n nid_notify.cbSize = sizeof(NOTIFYICONDATAW);\n nid_notify.hWnd = hwnd;\n nid_notify.uID = CLOCK_ID_TRAY_APP_ICON;\n nid_notify.uFlags = NIF_INFO;\n nid_notify.dwInfoFlags = NIIF_NONE;\n nid_notify.uTimeout = 3000;\n \n MultiByteToWideChar(CP_UTF8, 0, message, -1, nid_notify.szInfo, sizeof(nid_notify.szInfo)/sizeof(WCHAR));\n nid_notify.szInfoTitle[0] = L'\\0';\n \n Shell_NotifyIconW(NIM_MODIFY, &nid_notify);\n}\n\n/**\n * @brief Recreate the taskbar icon\n * @param hwnd Window handle\n * @param hInstance Instance handle\n */\nvoid RecreateTaskbarIcon(HWND hwnd, HINSTANCE hInstance) {\n RemoveTrayIcon();\n InitTrayIcon(hwnd, hInstance);\n}\n\n/**\n * @brief Update the tray icon and menu\n * @param hwnd Window handle\n */\nvoid UpdateTrayIcon(HWND hwnd) {\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n RecreateTaskbarIcon(hwnd, hInstance);\n}"], ["/Catime/src/language.c", "/**\n * @file language.c\n * @brief Multilingual support module implementation\n * \n * This file implements the multilingual support functionality for the application, \n * including language detection and localized string handling.\n * Translation content is embedded as resources in the executable file.\n */\n\n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\n/// Global language variable, stores the current application language setting\nAppLanguage CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default to English\n\n/// Global hash table for storing translations of the current language\n#define MAX_TRANSLATIONS 200\n#define MAX_STRING_LENGTH 1024\n\n// Language resource IDs (defined in languages.rc)\n#define LANG_EN_INI 1001 // Corresponds to languages/en.ini\n#define LANG_ZH_CN_INI 1002 // Corresponds to languages/zh_CN.ini\n#define LANG_ZH_TW_INI 1003 // Corresponds to languages/zh-Hant.ini\n#define LANG_ES_INI 1004 // Corresponds to languages/es.ini\n#define LANG_FR_INI 1005 // Corresponds to languages/fr.ini\n#define LANG_DE_INI 1006 // Corresponds to languages/de.ini\n#define LANG_RU_INI 1007 // Corresponds to languages/ru.ini\n#define LANG_PT_INI 1008 // Corresponds to languages/pt.ini\n#define LANG_JA_INI 1009 // Corresponds to languages/ja.ini\n#define LANG_KO_INI 1010 // Corresponds to languages/ko.ini\n\n/**\n * @brief Define language string key-value pair structure\n */\ntypedef struct {\n wchar_t english[MAX_STRING_LENGTH]; // English key\n wchar_t translation[MAX_STRING_LENGTH]; // Translated value\n} LocalizedString;\n\nstatic LocalizedString g_translations[MAX_TRANSLATIONS];\nstatic int g_translation_count = 0;\n\n/**\n * @brief Get the resource ID corresponding to a language\n * \n * @param language Language enumeration value\n * @return UINT Corresponding resource ID\n */\nstatic UINT GetLanguageResourceID(AppLanguage language) {\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n return LANG_ZH_CN_INI;\n case APP_LANG_CHINESE_TRAD:\n return LANG_ZH_TW_INI;\n case APP_LANG_SPANISH:\n return LANG_ES_INI;\n case APP_LANG_FRENCH:\n return LANG_FR_INI;\n case APP_LANG_GERMAN:\n return LANG_DE_INI;\n case APP_LANG_RUSSIAN:\n return LANG_RU_INI;\n case APP_LANG_PORTUGUESE:\n return LANG_PT_INI;\n case APP_LANG_JAPANESE:\n return LANG_JA_INI;\n case APP_LANG_KOREAN:\n return LANG_KO_INI;\n case APP_LANG_ENGLISH:\n default:\n return LANG_EN_INI;\n }\n}\n\n/**\n * @brief Convert UTF-8 string to wide character (UTF-16) string\n * \n * @param utf8 UTF-8 string\n * @param wstr Output wide character string buffer\n * @param wstr_size Buffer size (in characters)\n * @return int Number of characters after conversion, returns -1 if failed\n */\nstatic int UTF8ToWideChar(const char* utf8, wchar_t* wstr, int wstr_size) {\n return MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, wstr_size) - 1;\n}\n\n/**\n * @brief Parse a line in an ini file\n * \n * @param line A line from the ini file\n * @return int Whether parsing was successful (1 for success, 0 for failure)\n */\nstatic int ParseIniLine(const wchar_t* line) {\n // Skip empty lines and comment lines\n if (line[0] == L'\\0' || line[0] == L';' || line[0] == L'[') {\n return 0;\n }\n\n // Find content between the first and last quotes as the key\n const wchar_t* key_start = wcschr(line, L'\"');\n if (!key_start) return 0;\n key_start++; // Skip the first quote\n\n const wchar_t* key_end = wcschr(key_start, L'\"');\n if (!key_end) return 0;\n\n // Find content between the first and last quotes after the equal sign as the value\n const wchar_t* value_start = wcschr(key_end + 1, L'=');\n if (!value_start) return 0;\n \n value_start = wcschr(value_start, L'\"');\n if (!value_start) return 0;\n value_start++; // Skip the first quote\n\n const wchar_t* value_end = wcsrchr(value_start, L'\"');\n if (!value_end) return 0;\n\n // Copy key\n size_t key_len = key_end - key_start;\n if (key_len >= MAX_STRING_LENGTH) key_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].english, key_start, key_len);\n g_translations[g_translation_count].english[key_len] = L'\\0';\n\n // Copy value\n size_t value_len = value_end - value_start;\n if (value_len >= MAX_STRING_LENGTH) value_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].translation, value_start, value_len);\n g_translations[g_translation_count].translation[value_len] = L'\\0';\n\n g_translation_count++;\n return 1;\n}\n\n/**\n * @brief Load translations for a specified language from resources\n * \n * @param language Language enumeration value\n * @return int Whether loading was successful\n */\nstatic int LoadLanguageResource(AppLanguage language) {\n UINT resourceID = GetLanguageResourceID(language);\n \n // Reset translation count\n g_translation_count = 0;\n \n // Find resource\n HRSRC hResInfo = FindResource(NULL, MAKEINTRESOURCE(resourceID), RT_RCDATA);\n if (!hResInfo) {\n // If not found, check if it's Chinese and return\n if (language == APP_LANG_CHINESE_SIMP || language == APP_LANG_CHINESE_TRAD) {\n return 0;\n }\n \n // If not Chinese, load English as fallback\n if (language != APP_LANG_ENGLISH) {\n return LoadLanguageResource(APP_LANG_ENGLISH);\n }\n \n return 0;\n }\n \n // Get resource size\n DWORD dwSize = SizeofResource(NULL, hResInfo);\n if (dwSize == 0) {\n return 0;\n }\n \n // Load resource\n HGLOBAL hResData = LoadResource(NULL, hResInfo);\n if (!hResData) {\n return 0;\n }\n \n // Lock resource to get pointer\n const char* pData = (const char*)LockResource(hResData);\n if (!pData) {\n return 0;\n }\n \n // Create memory buffer copy\n char* buffer = (char*)malloc(dwSize + 1);\n if (!buffer) {\n return 0;\n }\n \n // Copy resource data to buffer\n memcpy(buffer, pData, dwSize);\n buffer[dwSize] = '\\0';\n \n // Split by lines and parse\n char* line = strtok(buffer, \"\\r\\n\");\n wchar_t wide_buffer[MAX_STRING_LENGTH];\n \n while (line && g_translation_count < MAX_TRANSLATIONS) {\n // Skip empty lines and BOM markers\n if (line[0] == '\\0' || (line[0] == (char)0xEF && line[1] == (char)0xBB && line[2] == (char)0xBF)) {\n line = strtok(NULL, \"\\r\\n\");\n continue;\n }\n \n // Convert to wide characters\n if (UTF8ToWideChar(line, wide_buffer, MAX_STRING_LENGTH) > 0) {\n ParseIniLine(wide_buffer);\n }\n \n line = strtok(NULL, \"\\r\\n\");\n }\n \n free(buffer);\n return 1;\n}\n\n/**\n * @brief Find corresponding translation in the global translation table\n * \n * @param english English original text\n * @return const wchar_t* Found translation, returns NULL if not found\n */\nstatic const wchar_t* FindTranslation(const wchar_t* english) {\n for (int i = 0; i < g_translation_count; i++) {\n if (wcscmp(english, g_translations[i].english) == 0) {\n return g_translations[i].translation;\n }\n }\n return NULL;\n}\n\n/**\n * @brief Initialize the application language environment\n * \n * Automatically detect and set the current language of the application based on system language.\n * Supports detection of Simplified Chinese, Traditional Chinese, and other preset languages.\n */\nstatic void DetectSystemLanguage() {\n LANGID langID = GetUserDefaultUILanguage();\n switch (PRIMARYLANGID(langID)) {\n case LANG_CHINESE:\n // Distinguish between Simplified and Traditional Chinese\n if (SUBLANGID(langID) == SUBLANG_CHINESE_SIMPLIFIED) {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_SIMP;\n } else {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_TRAD;\n }\n break;\n case LANG_SPANISH:\n CURRENT_LANGUAGE = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n CURRENT_LANGUAGE = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n CURRENT_LANGUAGE = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n CURRENT_LANGUAGE = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n CURRENT_LANGUAGE = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n CURRENT_LANGUAGE = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n CURRENT_LANGUAGE = APP_LANG_KOREAN;\n break;\n default:\n CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default fallback to English\n }\n}\n\n/**\n * @brief Get localized string\n * @param chinese Simplified Chinese version of the string\n * @param english English version of the string\n * @return const wchar_t* Pointer to the string corresponding to the current language\n * \n * Returns the string in the corresponding language based on the current language setting.\n */\nconst wchar_t* GetLocalizedString(const wchar_t* chinese, const wchar_t* english) {\n // Initialize translation resources on first call, but don't automatically detect system language\n static BOOL initialized = FALSE;\n if (!initialized) {\n // No longer call DetectSystemLanguage() to automatically detect system language\n // Instead, use the currently set CURRENT_LANGUAGE value (possibly from a configuration file)\n LoadLanguageResource(CURRENT_LANGUAGE);\n initialized = TRUE;\n }\n\n const wchar_t* translation = NULL;\n\n // If Simplified Chinese and Chinese string is provided, return directly\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP && chinese) {\n return chinese;\n }\n\n // Find translation\n translation = FindTranslation(english);\n if (translation) {\n return translation;\n }\n\n // For Traditional Chinese but no translation found, return Simplified Chinese as a fallback\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD && chinese) {\n return chinese;\n }\n\n // Default to English\n return english;\n}\n\n/**\n * @brief Set application language\n * \n * @param language The language to set\n * @return BOOL Whether the setting was successful\n */\nBOOL SetLanguage(AppLanguage language) {\n if (language < 0 || language >= APP_LANG_COUNT) {\n return FALSE;\n }\n \n CURRENT_LANGUAGE = language;\n g_translation_count = 0; // Clear existing translations\n return LoadLanguageResource(language);\n}\n\n/**\n * @brief Get current application language\n * \n * @return AppLanguage Current language\n */\nAppLanguage GetCurrentLanguage() {\n return CURRENT_LANGUAGE;\n}\n\n/**\n * @brief Get the name of the current language\n * @param buffer Buffer to store the language name\n * @param bufferSize Buffer size (in characters)\n * @return Whether the language name was successfully retrieved\n */\nBOOL GetCurrentLanguageName(wchar_t* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) {\n return FALSE;\n }\n \n // Get current language\n AppLanguage language = GetCurrentLanguage();\n \n // Return corresponding name based on language enumeration\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n wcscpy_s(buffer, bufferSize, L\"zh_CN\");\n break;\n case APP_LANG_CHINESE_TRAD:\n wcscpy_s(buffer, bufferSize, L\"zh-Hant\");\n break;\n case APP_LANG_SPANISH:\n wcscpy_s(buffer, bufferSize, L\"es\");\n break;\n case APP_LANG_FRENCH:\n wcscpy_s(buffer, bufferSize, L\"fr\");\n break;\n case APP_LANG_GERMAN:\n wcscpy_s(buffer, bufferSize, L\"de\");\n break;\n case APP_LANG_RUSSIAN:\n wcscpy_s(buffer, bufferSize, L\"ru\");\n break;\n case APP_LANG_PORTUGUESE:\n wcscpy_s(buffer, bufferSize, L\"pt\");\n break;\n case APP_LANG_JAPANESE:\n wcscpy_s(buffer, bufferSize, L\"ja\");\n break;\n case APP_LANG_KOREAN:\n wcscpy_s(buffer, bufferSize, L\"ko\");\n break;\n case APP_LANG_ENGLISH:\n default:\n wcscpy_s(buffer, bufferSize, L\"en\");\n break;\n }\n \n return TRUE;\n}\n"], ["/Catime/src/window_events.c", "/**\n * @file window_events.c\n * @brief Implementation of basic window event handling\n * \n * This file implements the basic event handling functionality for the application window,\n * including window creation, destruction, resizing, and position adjustment.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/tray.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/window_events.h\"\n\n/**\n * @brief Handle window creation event\n * @param hwnd Window handle\n * @return BOOL Processing result\n */\nBOOL HandleWindowCreate(HWND hwnd) {\n HWND hwndParent = GetParent(hwnd);\n if (hwndParent != NULL) {\n EnableWindow(hwndParent, TRUE);\n }\n \n // Load window settings\n LoadWindowSettings(hwnd);\n \n // Set click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // Ensure window is in topmost state\n SetWindowTopmost(hwnd, CLOCK_WINDOW_TOPMOST);\n \n return TRUE;\n}\n\n/**\n * @brief Handle window destruction event\n * @param hwnd Window handle\n */\nvoid HandleWindowDestroy(HWND hwnd) {\n SaveWindowSettings(hwnd); // Save window settings\n KillTimer(hwnd, 1);\n RemoveTrayIcon();\n \n // Clean up update check thread\n extern void CleanupUpdateThread(void);\n CleanupUpdateThread();\n \n PostQuitMessage(0);\n}\n\n/**\n * @brief Handle window reset event\n * @param hwnd Window handle\n */\nvoid HandleWindowReset(HWND hwnd) {\n // Unconditionally apply topmost setting from configuration\n // Regardless of the current CLOCK_WINDOW_TOPMOST value, force it to TRUE and apply\n CLOCK_WINDOW_TOPMOST = TRUE;\n SetWindowTopmost(hwnd, TRUE);\n WriteConfigTopmost(\"TRUE\");\n \n // Ensure window is always visible - solves the issue of timer not being visible after reset\n ShowWindow(hwnd, SW_SHOW);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowResize(HWND hwnd, int delta) {\n return HandleScaleWindow(hwnd, delta);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowMove(HWND hwnd) {\n return HandleDragWindow(hwnd);\n}\n"], ["/Catime/src/drag_scale.c", "/**\n * @file drag_scale.c\n * @brief Window dragging and scaling functionality implementation\n * \n * This file implements the dragging and scaling functionality of the application window,\n * including mouse dragging of the window and mouse wheel scaling of the window.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n\n// Add variable to record the topmost state before edit mode\nBOOL PREVIOUS_TOPMOST_STATE = FALSE;\n\nvoid StartDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_IS_DRAGGING = TRUE;\n SetCapture(hwnd);\n GetCursorPos(&CLOCK_LAST_MOUSE_POS);\n }\n}\n\nvoid StartEditMode(HWND hwnd) {\n // Record current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If currently not in topmost state, set to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Then enable edit mode\n CLOCK_EDIT_MODE = TRUE;\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure mouse cursor is default arrow\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n}\n\nvoid EndEditMode(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_EDIT_MODE = FALSE;\n \n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // If previously not in topmost state, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n }\n}\n\nvoid EndDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n CLOCK_IS_DRAGGING = FALSE;\n ReleaseCapture();\n // In edit mode, don't force window to stay on screen, allow dragging out\n AdjustWindowPosition(hwnd, FALSE);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\nBOOL HandleDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleScaleWindow(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings\n SaveWindowSettings(hwnd);\n return TRUE;\n }\n }\n return FALSE;\n}"], ["/Catime/src/media.c", "/**\n * @file media.c\n * @brief Media control functionality implementation\n * \n * This file implements the application's media control related functions,\n * including pause, play and other media control operations.\n */\n\n#include \n#include \"../include/media.h\"\n\n/**\n * @brief Pause media playback\n * \n * Pauses currently playing media by simulating media control key press events.\n * Includes a combination of stop and pause/play operations to ensure the media is properly paused.\n */\nvoid PauseMediaPlayback(void) {\n keybd_event(VK_MEDIA_STOP, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_STOP, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(100);\n}"], ["/Catime/libs/miniaudio/miniaudio.c", "#define MINIAUDIO_IMPLEMENTATION\n#include \"miniaudio.h\"\n"]], "task_instance_info": {"created_time": "2025-08-20 17:54:33", "created_task_model": "DeepSeek-R1", "function_skeleton": "static void HandleStartupMode(HWND hwnd) {}", "code_description": "This code segment functions to: Configure application initialization parameters based on specified operational modes, including timer management settings, user interface visibility states, and execution behavior flags."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nstatic void HandleStartupMode(HWND hwnd) {\n if (strcmp(CLOCK_STARTUP_MODE, \"auto\") == 0) {\n // Start countdown immediately in auto mode\n default_countdown_time = CLOCK_DEFAULT_START_TIME;\n elapsed_time = 0;\n \n // Update time display\n int minutes = default_countdown_time / 60;\n int seconds = default_countdown_time % 60;\n char time_str[20];\n sprintf(time_str, \"%02d:%02d\", minutes, seconds);\n SetDlgItemText(hwnd, IDC_STATIC_TIME_REMAINING, time_str);\n \n // Update window title\n SetWindowText(hwnd, TEXT(\"Catime - Running\"));\n } else {\n // Manual mode - reset display\n SetDlgItemText(hwnd, IDC_STATIC_TIME_REMAINING, \"00:00\");\n SetWindowText(hwnd, TEXT(\"Catime - Stopped\"));\n }\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 17-55-21"}, "editdistance_info": {"edit_distance": 21.5768, "calculate_time": "2025-08-20 17:55:21", "true_code_clean": "static void HandleStartupMode(HWND hwnd) {\n LOG_INFO(\"Setting startup mode: %s\", CLOCK_STARTUP_MODE);\n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n LOG_INFO(\"Setting to count-up mode\");\n CLOCK_COUNT_UP = TRUE;\n elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n LOG_INFO(\"Setting to hidden mode, window will be hidden\");\n ShowWindow(hwnd, SW_HIDE);\n KillTimer(hwnd, 1);\n elapsed_time = CLOCK_TOTAL_TIME;\n CLOCK_IS_PAUSED = TRUE;\n message_shown = TRUE;\n countdown_message_shown = TRUE;\n countup_message_shown = TRUE;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n LOG_INFO(\"Setting to show current time mode\");\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_LAST_TIME_UPDATE = 0;\n } else {\n LOG_INFO(\"Using default countdown mode\");\n }\n}", "predict_code_clean": "static void HandleStartupMode(HWND hwnd) {\n if (strcmp(CLOCK_STARTUP_MODE, \"auto\") == 0) {\n default_countdown_time = CLOCK_DEFAULT_START_TIME;\n elapsed_time = 0;\n int minutes = default_countdown_time / 60;\n int seconds = default_countdown_time % 60;\n char time_str[20];\n sprintf(time_str, \"%02d:%02d\", minutes, seconds);\n SetDlgItemText(hwnd, IDC_STATIC_TIME_REMAINING, time_str);\n SetWindowText(hwnd, TEXT(\"Catime - Running\"));\n } else {\n SetDlgItemText(hwnd, IDC_STATIC_TIME_REMAINING, \"00:00\");\n SetWindowText(hwnd, TEXT(\"Catime - Stopped\"));\n }\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n}"}} {"repo_name": "Catime", "file_name": "/Catime/src/tray_menu.c", "inference_info": {"prefix_code": "/**\n * @file tray_menu.c\n * @brief Implementation of system tray menu functionality\n * \n * This file implements the system tray menu functionality for the application, including:\n * - Right-click menu and its submenus\n * - Color selection menu\n * - Font settings menu\n * - Timeout action settings\n * - Pomodoro functionality\n * - Preset time management\n * - Multi-language interface support\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/timer.h\"\n#include \"../resource/resource.h\"\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_USE_24HOUR;\nextern BOOL CLOCK_SHOW_SECONDS;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_EDIT_MODE;\nextern char CLOCK_STARTUP_MODE[20];\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\nextern int time_options[];\nextern int time_options_count;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern char CLOCK_TIMEOUT_FILE_PATH[MAX_PATH];\nextern char CLOCK_TIMEOUT_TEXT[50];\nextern BOOL CLOCK_WINDOW_TOPMOST; ///< Whether the window is always on top\n\n// Add Pomodoro related variable declarations\nextern int POMODORO_WORK_TIME; ///< Work time (seconds)\nextern int POMODORO_SHORT_BREAK; ///< Short break time (seconds)\nextern int POMODORO_LONG_BREAK; ///< Long break time (seconds)\nextern int POMODORO_LOOP_COUNT; ///< Loop count\n\n// Pomodoro time array and count variables\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Add to external variable declaration section\nextern char CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH]; ///< URL for timeout open website\nextern int current_pomodoro_time_index; // Current Pomodoro time index\nextern POMODORO_PHASE current_pomodoro_phase; // Pomodoro phase\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t size);\nextern BOOL IsAutoStartEnabled(void);\nextern void WriteConfigStartupMode(const char* mode);\nextern void ClearColorOptions(void);\nextern void AddColorOption(const char* color);\n/// @}\n\n/**\n * @brief Read timeout action settings from configuration file\n * \n * Read the timeout action settings saved in the configuration file and update the global variable CLOCK_TIMEOUT_ACTION\n */\nvoid ReadTimeoutActionFromConfig() {\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"TIMEOUT_ACTION=\", 15) == 0) {\n int action = 0;\n sscanf(line, \"TIMEOUT_ACTION=%d\", &action);\n CLOCK_TIMEOUT_ACTION = (TimeoutActionType)action;\n break;\n }\n }\n fclose(configFile);\n }\n}\n\n/**\n * @brief Recent file structure\n * \n * Store information about recently used files, including full path and display name\n */\ntypedef struct {\n char path[MAX_PATH]; ///< Full file path\n char name[MAX_PATH]; ///< File display name (may be truncated)\n} RecentFile;\n\nextern RecentFile CLOCK_RECENT_FILES[];\nextern int CLOCK_RECENT_FILES_COUNT;\n\n/**\n * @brief Format Pomodoro time to wide string\n * @param seconds Number of seconds\n * @param buffer Output buffer\n * @param bufferSize Buffer size\n */\nstatic void FormatPomodoroTime(int seconds, wchar_t* buffer, size_t bufferSize) {\n int minutes = seconds / 60;\n int secs = seconds % 60;\n int hours = minutes / 60;\n minutes %= 60;\n \n if (hours > 0) {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d:%02d\", hours, minutes, secs);\n } else {\n _snwprintf_s(buffer, bufferSize, _TRUNCATE, L\"%d:%02d\", minutes, secs);\n }\n}\n\n/**\n * @brief Truncate long file names\n * \n * @param fileName Original file name\n * @param truncated Truncated file name buffer\n * @param maxLen Maximum display length (excluding terminator)\n * \n * If the file name exceeds the specified length, it uses the format \"first 12 characters...last 12 characters.extension\" for intelligent truncation.\n * This function preserves the file extension to ensure users can identify the file type.\n */\nvoid TruncateFileName(const wchar_t* fileName, wchar_t* truncated, size_t maxLen) {\n if (!fileName || !truncated || maxLen <= 7) return; // At least need to display \"x...y\"\n \n size_t nameLen = wcslen(fileName);\n if (nameLen <= maxLen) {\n // File name does not exceed the length limit, copy directly\n wcscpy(truncated, fileName);\n return;\n }\n \n // Find the position of the last dot (extension separator)\n const wchar_t* lastDot = wcsrchr(fileName, L'.');\n const wchar_t* fileNameNoExt = fileName;\n const wchar_t* ext = L\"\";\n size_t nameNoExtLen = nameLen;\n size_t extLen = 0;\n \n if (lastDot && lastDot != fileName) {\n // Has valid extension\n ext = lastDot; // Extension including dot\n extLen = wcslen(ext);\n nameNoExtLen = lastDot - fileName; // Length of file name without extension\n }\n \n // If the pure file name length is less than or equal to 27 characters (12+3+12), use the old truncation method\n if (nameNoExtLen <= 27) {\n // Simple truncation of main file name, preserving extension\n wcsncpy(truncated, fileName, maxLen - extLen - 3);\n truncated[maxLen - extLen - 3] = L'\\0';\n wcscat(truncated, L\"...\");\n wcscat(truncated, ext);\n return;\n }\n \n // Use new truncation method: first 12 characters + ... + last 12 characters + extension\n wchar_t buffer[MAX_PATH];\n \n // Copy first 12 characters\n wcsncpy(buffer, fileName, 12);\n buffer[12] = L'\\0';\n \n // Add ellipsis\n wcscat(buffer, L\"...\");\n \n // Copy last 12 characters (excluding extension part)\n wcsncat(buffer, fileName + nameNoExtLen - 12, 12);\n \n // Add extension\n wcscat(buffer, ext);\n \n // Copy result to output buffer\n wcscpy(truncated, buffer);\n}\n\n/**\n * @brief Display color and settings menu\n * \n * @param hwnd Window handle\n * \n * Create and display the application's main settings menu, including:\n * - Edit mode toggle\n * - Timeout action settings\n * - Preset time management\n * - Startup mode settings\n * - Font selection\n * - Color settings\n * - Language selection\n * - Help and about information\n */\n", "suffix_code": "\n\n/**\n * @brief Display tray right-click menu\n * \n * @param hwnd Window handle\n * \n * Create and display the system tray right-click menu, dynamically adjusting menu items based on current application state. Includes:\n * - Timer control (pause/resume, restart)\n * - Time display settings (24-hour format, show seconds)\n * - Pomodoro clock settings\n * - Count-up and countdown mode switching\n * - Quick time preset options\n */\nvoid ShowContextMenu(HWND hwnd) {\n // Read timeout action settings from configuration file before creating the menu\n ReadTimeoutActionFromConfig();\n \n // Set mouse cursor to default arrow to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n HMENU hMenu = CreatePopupMenu();\n \n // Timer management menu - added at the top\n HMENU hTimerManageMenu = CreatePopupMenu();\n \n // Set conditions for whether submenu items should be enabled\n // Timer options should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress\n // 3. If in countdown mode, the timer hasn't ended yet (countdown elapsed time is less than total time)\n BOOL timerRunning = (!CLOCK_SHOW_CURRENT_TIME && \n (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0 && countdown_elapsed_time < CLOCK_TOTAL_TIME)));\n \n // Pause/Resume text changes based on current state\n const wchar_t* pauseResumeText = CLOCK_IS_PAUSED ? \n GetLocalizedString(L\"继续\", L\"Resume\") : \n GetLocalizedString(L\"暂停\", L\"Pause\");\n \n // Submenu items are disabled based on conditions, but parent menu item remains selectable\n AppendMenuW(hTimerManageMenu, MF_STRING | (timerRunning ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_PAUSE_RESUME, pauseResumeText);\n \n // Restart option should be available when:\n // 1. Not in show current time mode\n // 2. And either countdown or count-up is in progress (regardless of whether countdown has ended)\n BOOL canRestart = (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || \n (!CLOCK_COUNT_UP && CLOCK_TOTAL_TIME > 0)));\n \n AppendMenuW(hTimerManageMenu, MF_STRING | (canRestart ? MF_ENABLED : MF_GRAYED),\n CLOCK_IDM_TIMER_RESTART, \n GetLocalizedString(L\"重新开始\", L\"Start Over\"));\n \n // Add timer management menu to main menu - parent menu item is always enabled\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimerManageMenu,\n GetLocalizedString(L\"计时管理\", L\"Timer Control\"));\n \n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n \n // Time display menu\n HMENU hTimeMenu = CreatePopupMenu();\n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_CURRENT_TIME ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_CURRENT_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_USE_24HOUR ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_24HOUR_FORMAT,\n GetLocalizedString(L\"24小时制\", L\"24-Hour Format\"));\n \n AppendMenuW(hTimeMenu, MF_STRING | (CLOCK_SHOW_SECONDS ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHOW_SECONDS,\n GetLocalizedString(L\"显示秒数\", L\"Show Seconds\"));\n \n AppendMenuW(hMenu, MF_POPUP,\n (UINT_PTR)hTimeMenu,\n GetLocalizedString(L\"时间显示\", L\"Time Display\"));\n\n // Before Pomodoro menu, first read the latest configuration values\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\");\n POMODORO_TIMES_COUNT = 0; // Initialize to 0\n \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n char* options = line + 22;\n char* token;\n int index = 0;\n \n token = strtok(options, \",\");\n while (token && index < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[index++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Set the actual number of time options\n POMODORO_TIMES_COUNT = index;\n \n // Ensure at least one valid value\n if (index > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (index > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (index > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[2];\n }\n }\n else if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n sscanf(line, \"POMODORO_LOOP_COUNT=%d\", &POMODORO_LOOP_COUNT);\n // Ensure loop count is at least 1\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n }\n }\n fclose(configFile);\n }\n\n // Pomodoro menu\n HMENU hPomodoroMenu = CreatePopupMenu();\n \n // Add timeBuffer declaration\n wchar_t timeBuffer[64]; // For storing formatted time string\n \n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_START,\n GetLocalizedString(L\"开始\", L\"Start\"));\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Create menu items for each Pomodoro time\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n FormatPomodoroTime(POMODORO_TIMES[i], timeBuffer, sizeof(timeBuffer)/sizeof(wchar_t));\n \n // Support both old and new ID systems\n UINT menuId;\n if (i == 0) menuId = CLOCK_IDM_POMODORO_WORK;\n else if (i == 1) menuId = CLOCK_IDM_POMODORO_BREAK;\n else if (i == 2) menuId = CLOCK_IDM_POMODORO_LBREAK;\n else menuId = CLOCK_IDM_POMODORO_TIME_BASE + i;\n \n // Check if this is the active Pomodoro phase\n BOOL isCurrentPhase = (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n current_pomodoro_time_index == i &&\n !CLOCK_SHOW_CURRENT_TIME &&\n !CLOCK_COUNT_UP && // Add check for not being in count-up mode\n CLOCK_TOTAL_TIME == POMODORO_TIMES[i]);\n \n // Add check mark if it's the current phase\n AppendMenuW(hPomodoroMenu, MF_STRING | (isCurrentPhase ? MF_CHECKED : MF_UNCHECKED), \n menuId, timeBuffer);\n }\n\n // Add loop count option\n wchar_t menuText[64];\n _snwprintf(menuText, sizeof(menuText)/sizeof(wchar_t),\n GetLocalizedString(L\"循环次数: %d\", L\"Loop Count: %d\"),\n POMODORO_LOOP_COUNT);\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_LOOP_COUNT, menuText);\n\n\n // Add separator\n AppendMenuW(hPomodoroMenu, MF_SEPARATOR, 0, NULL);\n\n // Add combination option\n AppendMenuW(hPomodoroMenu, MF_STRING, CLOCK_IDM_POMODORO_COMBINATION,\n GetLocalizedString(L\"组合\", L\"Combination\"));\n \n // Add Pomodoro menu to main menu\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hPomodoroMenu,\n GetLocalizedString(L\"番茄时钟\", L\"Pomodoro\"));\n\n // Count-up menu - changed to direct click to start\n AppendMenuW(hMenu, MF_STRING | (CLOCK_COUNT_UP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_COUNT_UP_START,\n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n\n // Add \"Set Countdown\" option below Count-up\n AppendMenuW(hMenu, MF_STRING, 101, \n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Add quick time options\n for (int i = 0; i < time_options_count; i++) {\n wchar_t menu_item[20];\n _snwprintf(menu_item, sizeof(menu_item)/sizeof(wchar_t), L\"%d\", time_options[i]);\n AppendMenuW(hMenu, MF_STRING, 102 + i, menu_item);\n }\n\n // Display menu\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); // This will allow the menu to close automatically when clicking outside\n DestroyMenu(hMenu);\n}", "middle_code": "void ShowColorMenu(HWND hwnd) {\n ReadTimeoutActionFromConfig();\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n HMENU hMenu = CreatePopupMenu();\n AppendMenuW(hMenu, MF_STRING | (CLOCK_EDIT_MODE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_EDIT_MODE, \n GetLocalizedString(L\"编辑模式\", L\"Edit Mode\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n HMENU hTimeoutMenu = CreatePopupMenu();\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_SHOW_MESSAGE, \n GetLocalizedString(L\"显示消息\", L\"Show Message\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHOW_TIME ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_SHOW_TIME, \n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_COUNT_UP ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_COUNT_UP, \n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_LOCK ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LOCK_SCREEN,\n GetLocalizedString(L\"锁定屏幕\", L\"Lock Screen\"));\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n HMENU hFileMenu = CreatePopupMenu();\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n wchar_t wFileName[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[i].name, -1, wFileName, MAX_PATH);\n wchar_t truncatedName[MAX_PATH];\n TruncateFileName(wFileName, truncatedName, 25); \n BOOL isCurrentFile = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE && \n strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n strcmp(CLOCK_RECENT_FILES[i].path, CLOCK_TIMEOUT_FILE_PATH) == 0);\n AppendMenuW(hFileMenu, MF_STRING | (isCurrentFile ? MF_CHECKED : 0), \n CLOCK_IDM_RECENT_FILE_1 + i, truncatedName);\n }\n if (CLOCK_RECENT_FILES_COUNT > 0) {\n AppendMenuW(hFileMenu, MF_SEPARATOR, 0, NULL);\n }\n AppendMenuW(hFileMenu, MF_STRING, CLOCK_IDM_BROWSE_FILE,\n GetLocalizedString(L\"浏览...\", L\"Browse...\"));\n AppendMenuW(hTimeoutMenu, MF_POPUP | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE ? MF_CHECKED : MF_UNCHECKED), \n (UINT_PTR)hFileMenu, \n GetLocalizedString(L\"打开文件/软件\", L\"Open File/Software\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_WEBSITE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_OPEN_WEBSITE,\n GetLocalizedString(L\"打开网站\", L\"Open Website\"));\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hTimeoutMenu, MF_STRING | MF_GRAYED | MF_DISABLED, \n 0, \n GetLocalizedString(L\"以下超时动作为一次性\", L\"Following actions are one-time only\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHUTDOWN,\n GetLocalizedString(L\"关机\", L\"Shutdown\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RESTART,\n GetLocalizedString(L\"重启\", L\"Restart\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SLEEP,\n GetLocalizedString(L\"睡眠\", L\"Sleep\"));\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n HMENU hAdvancedMenu = CreatePopupMenu();\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RUN_COMMAND,\n GetLocalizedString(L\"运行命令\", L\"Run Command\"));\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_HTTP_REQUEST,\n GetLocalizedString(L\"HTTP 请求\", L\"HTTP Request\"));\n BOOL isAdvancedOptionSelected = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ||\n CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST);\n AppendMenuW(hTimeoutMenu, MF_POPUP | (isAdvancedOptionSelected ? MF_CHECKED : MF_UNCHECKED),\n (UINT_PTR)hAdvancedMenu,\n GetLocalizedString(L\"高级\", L\"Advanced\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeoutMenu, \n GetLocalizedString(L\"超时动作\", L\"Timeout Action\"));\n HMENU hTimeOptionsMenu = CreatePopupMenu();\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDC_MODIFY_TIME_OPTIONS,\n GetLocalizedString(L\"倒计时预设\", L\"Modify Quick Countdown Options\"));\n HMENU hStartupSettingsMenu = CreatePopupMenu();\n char currentStartupMode[20] = \"COUNTDOWN\";\n char configPath[MAX_PATH]; \n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\"); \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(configFile);\n }\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNTDOWN\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_SET_COUNTDOWN_TIME,\n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNT_UP\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_COUNT_UP,\n GetLocalizedString(L\"正计时\", L\"Stopwatch\"));\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"SHOW_TIME\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_SHOW_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"NO_DISPLAY\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_NO_DISPLAY,\n GetLocalizedString(L\"不显示\", L\"No Display\"));\n AppendMenuW(hStartupSettingsMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (IsAutoStartEnabled() ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_AUTO_START,\n GetLocalizedString(L\"开机自启动\", L\"Start with Windows\"));\n AppendMenuW(hTimeOptionsMenu, MF_POPUP, (UINT_PTR)hStartupSettingsMenu,\n GetLocalizedString(L\"启动设置\", L\"Startup Settings\"));\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDM_NOTIFICATION_SETTINGS,\n GetLocalizedString(L\"通知设置\", L\"Notification Settings\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeOptionsMenu,\n GetLocalizedString(L\"预设管理\", L\"Preset Management\"));\n AppendMenuW(hTimeOptionsMenu, MF_STRING | (CLOCK_WINDOW_TOPMOST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TOPMOST,\n GetLocalizedString(L\"置顶\", L\"Always on Top\"));\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_HOTKEY_SETTINGS,\n GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n HMENU hMoreFontsMenu = CreatePopupMenu();\n HMENU hFontSubMenu = CreatePopupMenu();\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayName[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayName, 100);\n wchar_t* dot = wcsstr(wDisplayName, L\".ttf\");\n if (dot) *dot = L'\\0';\n AppendMenuW(hFontSubMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayName);\n }\n }\n AppendMenuW(hFontSubMenu, MF_SEPARATOR, 0, NULL);\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n continue;\n }\n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayNameMore[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayNameMore, 100);\n wchar_t* dot = wcsstr(wDisplayNameMore, L\".ttf\");\n if (dot) *dot = L'\\0';\n AppendMenuW(hMoreFontsMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayNameMore);\n }\n AppendMenuW(hFontSubMenu, MF_POPUP, (UINT_PTR)hMoreFontsMenu, GetLocalizedString(L\"更多\", L\"More\"));\n HMENU hColorSubMenu = CreatePopupMenu();\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n MENUITEMINFO mii = { sizeof(MENUITEMINFO) };\n mii.fMask = MIIM_STRING | MIIM_ID | MIIM_STATE | MIIM_FTYPE;\n mii.fType = MFT_STRING | MFT_OWNERDRAW;\n mii.fState = strcmp(CLOCK_TEXT_COLOR, hexColor) == 0 ? MFS_CHECKED : MFS_UNCHECKED;\n mii.wID = 201 + i; \n mii.dwTypeData = (LPSTR)hexColor;\n InsertMenuItem(hColorSubMenu, i, TRUE, &mii);\n }\n AppendMenuW(hColorSubMenu, MF_SEPARATOR, 0, NULL);\n HMENU hCustomizeMenu = CreatePopupMenu();\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_VALUE, \n GetLocalizedString(L\"颜色值\", L\"Color Value\"));\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_PANEL, \n GetLocalizedString(L\"颜色面板\", L\"Color Panel\"));\n AppendMenuW(hColorSubMenu, MF_POPUP, (UINT_PTR)hCustomizeMenu, \n GetLocalizedString(L\"自定义\", L\"Customize\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hFontSubMenu, \n GetLocalizedString(L\"字体\", L\"Font\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hColorSubMenu, \n GetLocalizedString(L\"颜色\", L\"Color\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n HMENU hAboutMenu = CreatePopupMenu();\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_ABOUT, GetLocalizedString(L\"关于\", L\"About\"));\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_FEEDBACK, GetLocalizedString(L\"反馈\", L\"Feedback\"));\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_HELP, GetLocalizedString(L\"使用指南\", L\"User Guide\"));\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_CHECK_UPDATE, \n GetLocalizedString(L\"检查更新\", L\"Check for Updates\"));\n HMENU hLangMenu = CreatePopupMenu();\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE, L\"简体中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE_TRAD, L\"繁體中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_ENGLISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_ENGLISH, L\"English\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_SPANISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_SPANISH, L\"Español\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_FRENCH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_FRENCH, L\"Français\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_GERMAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_GERMAN, L\"Deutsch\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_RUSSIAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_RUSSIAN, L\"Русский\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_PORTUGUESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_PORTUGUESE, L\"Português\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_JAPANESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_JAPANESE, L\"日本語\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_KOREAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_KOREAN, L\"한국어\");\n AppendMenuW(hAboutMenu, MF_POPUP, (UINT_PTR)hLangMenu, GetLocalizedString(L\"语言\", L\"Language\"));\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, 200,\n GetLocalizedString(L\"重置\", L\"Reset\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hAboutMenu,\n GetLocalizedString(L\"帮助\", L\"Help\"));\n AppendMenuW(hMenu, MF_STRING, 109,\n GetLocalizedString(L\"退出\", L\"Exit\"));\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); \n DestroyMenu(hMenu);\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/Catime/src/window_procedure.c", "/**\n * @file window_procedure.c\n * @brief Window message processing implementation\n * \n * This file implements the message processing callback function for the application's main window,\n * handling all message events for the window.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\" \n#include \"../include/window.h\" \n#include \"../include/startup.h\" \n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/window_events.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/drawing.h\"\n#include \"../include/timer_events.h\"\n#include \"../include/tray_events.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/notification.h\" // Add notification header\n\n// Variables imported from main.c\nextern char inputText[256];\nextern int elapsed_time;\nextern int message_shown;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void PauseMediaPlayback(void);\n\n// Add these external variable declarations at the beginning of the file\nextern int POMODORO_TIMES[10]; // Pomodoro time array\nextern int POMODORO_TIMES_COUNT; // Number of pomodoro time options\nextern int current_pomodoro_time_index; // Current pomodoro time index\nextern int complete_pomodoro_cycles; // Completed pomodoro cycles\n\n// If ShowInputDialog function needs to be declared, add at the beginning\nextern BOOL ShowInputDialog(HWND hwnd, char* text);\n\n// Modify to match the correct function declaration in config.h\nextern void WriteConfigPomodoroTimeOptions(int* times, int count);\n\n// If the function doesn't exist, use an existing similar function\n// For example, modify calls to WriteConfigPomodoroTimeOptions to WriteConfigPomodoroTimes\n\n// Add at the beginning of the file\ntypedef struct {\n const wchar_t* title;\n const wchar_t* prompt;\n const wchar_t* defaultText;\n wchar_t* result;\n size_t maxLen;\n} INPUTBOX_PARAMS;\n\n// Add declaration for ShowPomodoroLoopDialog function at the beginning of the file\nextern void ShowPomodoroLoopDialog(HWND hwndParent);\n\n// Add declaration for OpenUserGuide function\nextern void OpenUserGuide(void);\n\n// Add declaration for OpenSupportPage function\nextern void OpenSupportPage(void);\n\n// Add declaration for OpenFeedbackPage function\nextern void OpenFeedbackPage(void);\n\n// Helper function: Check if a string contains only spaces\nstatic BOOL isAllSpacesOnly(const char* str) {\n for (int i = 0; str[i]; i++) {\n if (!isspace((unsigned char)str[i])) {\n return FALSE;\n }\n }\n return TRUE;\n}\n\n/**\n * @brief Input dialog callback function\n * @param hwndDlg Dialog handle\n * @param uMsg Message\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return Processing result\n */\nINT_PTR CALLBACK InputBoxProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {\n static wchar_t* result;\n static size_t maxLen;\n \n switch (uMsg) {\n case WM_INITDIALOG: {\n // Get passed parameters\n INPUTBOX_PARAMS* params = (INPUTBOX_PARAMS*)lParam;\n result = params->result;\n maxLen = params->maxLen;\n \n // Set dialog title\n SetWindowTextW(hwndDlg, params->title);\n \n // Set prompt message\n SetDlgItemTextW(hwndDlg, IDC_STATIC_PROMPT, params->prompt);\n \n // Set default text\n SetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, params->defaultText);\n \n // Select text\n SendDlgItemMessageW(hwndDlg, IDC_EDIT_INPUT, EM_SETSEL, 0, -1);\n \n // Set focus\n SetFocus(GetDlgItem(hwndDlg, IDC_EDIT_INPUT));\n return FALSE;\n }\n \n case WM_COMMAND:\n switch (LOWORD(wParam)) {\n case IDOK: {\n // Get input text\n GetDlgItemTextW(hwndDlg, IDC_EDIT_INPUT, result, (int)maxLen);\n EndDialog(hwndDlg, TRUE);\n return TRUE;\n }\n \n case IDCANCEL:\n // Cancel operation\n EndDialog(hwndDlg, FALSE);\n return TRUE;\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display input dialog\n * @param hwndParent Parent window handle\n * @param title Dialog title\n * @param prompt Prompt message\n * @param defaultText Default text\n * @param result Result buffer\n * @param maxLen Maximum buffer length\n * @return TRUE if successful, FALSE if canceled\n */\nBOOL InputBox(HWND hwndParent, const wchar_t* title, const wchar_t* prompt, \n const wchar_t* defaultText, wchar_t* result, size_t maxLen) {\n // Prepare parameters to pass to dialog\n INPUTBOX_PARAMS params;\n params.title = title;\n params.prompt = prompt;\n params.defaultText = defaultText;\n params.result = result;\n params.maxLen = maxLen;\n \n // Display modal dialog\n return DialogBoxParamW(GetModuleHandle(NULL), \n MAKEINTRESOURCEW(IDD_INPUTBOX), \n hwndParent, \n InputBoxProc, \n (LPARAM)¶ms) == TRUE;\n}\n\nvoid ExitProgram(HWND hwnd) {\n RemoveTrayIcon();\n\n PostQuitMessage(0);\n}\n\n#define HOTKEY_ID_SHOW_TIME 100 // Hotkey ID to show current time\n#define HOTKEY_ID_COUNT_UP 101 // Hotkey ID for count up timer\n#define HOTKEY_ID_COUNTDOWN 102 // Hotkey ID for countdown timer\n#define HOTKEY_ID_QUICK_COUNTDOWN1 103 // Hotkey ID for quick countdown 1\n#define HOTKEY_ID_QUICK_COUNTDOWN2 104 // Hotkey ID for quick countdown 2\n#define HOTKEY_ID_QUICK_COUNTDOWN3 105 // Hotkey ID for quick countdown 3\n#define HOTKEY_ID_POMODORO 106 // Hotkey ID for pomodoro timer\n#define HOTKEY_ID_TOGGLE_VISIBILITY 107 // Hotkey ID for hide/show\n#define HOTKEY_ID_EDIT_MODE 108 // Hotkey ID for edit mode\n#define HOTKEY_ID_PAUSE_RESUME 109 // Hotkey ID for pause/resume\n#define HOTKEY_ID_RESTART_TIMER 110 // Hotkey ID for restart timer\n#define HOTKEY_ID_CUSTOM_COUNTDOWN 111 // Hotkey ID for custom countdown\n\n/**\n * @brief Register global hotkeys\n * @param hwnd Window handle\n * \n * Reads and registers global hotkey settings from the configuration file for quickly switching between\n * displaying current time, count up timer, and default countdown.\n * If a hotkey is already registered, it will be unregistered before re-registering.\n * If a hotkey cannot be registered (possibly because it's being used by another program),\n * that hotkey setting will be set to none and the configuration file will be updated.\n * \n * @return BOOL Whether at least one hotkey was successfully registered\n */\nBOOL RegisterGlobalHotkeys(HWND hwnd) {\n // First unregister all previously registered hotkeys\n UnregisterGlobalHotkeys(hwnd);\n \n // Use new function to read hotkey configuration\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n BOOL success = FALSE;\n BOOL configChanged = FALSE;\n \n // Register show current time hotkey\n if (showTimeHotkey != 0) {\n BYTE vk = LOBYTE(showTimeHotkey); // Virtual key code\n BYTE mod = HIBYTE(showTimeHotkey); // Modifier keys\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n showTimeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register count up hotkey\n if (countUpHotkey != 0) {\n BYTE vk = LOBYTE(countUpHotkey);\n BYTE mod = HIBYTE(countUpHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNT_UP, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countUpHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register countdown hotkey\n if (countdownHotkey != 0) {\n BYTE vk = LOBYTE(countdownHotkey);\n BYTE mod = HIBYTE(countdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n countdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 1 hotkey\n if (quickCountdown1Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown1Hotkey);\n BYTE mod = HIBYTE(quickCountdown1Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown1Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 2 hotkey\n if (quickCountdown2Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown2Hotkey);\n BYTE mod = HIBYTE(quickCountdown2Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown2Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register quick countdown 3 hotkey\n if (quickCountdown3Hotkey != 0) {\n BYTE vk = LOBYTE(quickCountdown3Hotkey);\n BYTE mod = HIBYTE(quickCountdown3Hotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n quickCountdown3Hotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pomodoro hotkey\n if (pomodoroHotkey != 0) {\n BYTE vk = LOBYTE(pomodoroHotkey);\n BYTE mod = HIBYTE(pomodoroHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_POMODORO, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pomodoroHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register hide/show window hotkey\n if (toggleVisibilityHotkey != 0) {\n BYTE vk = LOBYTE(toggleVisibilityHotkey);\n BYTE mod = HIBYTE(toggleVisibilityHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n toggleVisibilityHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register edit mode hotkey\n if (editModeHotkey != 0) {\n BYTE vk = LOBYTE(editModeHotkey);\n BYTE mod = HIBYTE(editModeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n editModeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register pause/resume hotkey\n if (pauseResumeHotkey != 0) {\n BYTE vk = LOBYTE(pauseResumeHotkey);\n BYTE mod = HIBYTE(pauseResumeHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n pauseResumeHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // Register restart timer hotkey\n if (restartTimerHotkey != 0) {\n BYTE vk = LOBYTE(restartTimerHotkey);\n BYTE mod = HIBYTE(restartTimerHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n restartTimerHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n // If any hotkey registration failed, update config file\n if (configChanged) {\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n \n // Check if custom countdown hotkey was cleared, if so, update config\n if (customCountdownHotkey == 0) {\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", \"None\");\n }\n }\n \n // Added after reading hotkey configuration\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Added after registering countdown hotkey\n // Register custom countdown hotkey\n if (customCountdownHotkey != 0) {\n BYTE vk = LOBYTE(customCountdownHotkey);\n BYTE mod = HIBYTE(customCountdownHotkey);\n \n UINT fsModifiers = 0;\n if (mod & HOTKEYF_ALT) fsModifiers |= MOD_ALT;\n if (mod & HOTKEYF_CONTROL) fsModifiers |= MOD_CONTROL;\n if (mod & HOTKEYF_SHIFT) fsModifiers |= MOD_SHIFT;\n \n if (RegisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN, fsModifiers, vk)) {\n success = TRUE;\n } else {\n // Hotkey registration failed, clear configuration\n customCountdownHotkey = 0;\n configChanged = TRUE;\n }\n }\n \n return success;\n}\n\n/**\n * @brief Unregister global hotkeys\n * @param hwnd Window handle\n * \n * Unregister all previously registered global hotkeys.\n */\nvoid UnregisterGlobalHotkeys(HWND hwnd) {\n // Unregister all previously registered hotkeys\n UnregisterHotKey(hwnd, HOTKEY_ID_SHOW_TIME);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNT_UP);\n UnregisterHotKey(hwnd, HOTKEY_ID_COUNTDOWN);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN1);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN2);\n UnregisterHotKey(hwnd, HOTKEY_ID_QUICK_COUNTDOWN3);\n UnregisterHotKey(hwnd, HOTKEY_ID_POMODORO);\n UnregisterHotKey(hwnd, HOTKEY_ID_TOGGLE_VISIBILITY);\n UnregisterHotKey(hwnd, HOTKEY_ID_EDIT_MODE);\n UnregisterHotKey(hwnd, HOTKEY_ID_PAUSE_RESUME);\n UnregisterHotKey(hwnd, HOTKEY_ID_RESTART_TIMER);\n UnregisterHotKey(hwnd, HOTKEY_ID_CUSTOM_COUNTDOWN);\n}\n\n/**\n * @brief Main window message processing callback function\n * @param hwnd Window handle\n * @param msg Message type\n * @param wp Message parameter (specific meaning depends on message type)\n * @param lp Message parameter (specific meaning depends on message type)\n * @return LRESULT Message processing result\n * \n * Handles all message events for the main window, including:\n * - Window creation/destruction\n * - Mouse events (dragging, wheel scaling)\n * - Timer events\n * - System tray interaction\n * - Drawing events\n * - Menu command processing\n */\nLRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)\n{\n static char time_text[50];\n UINT uID;\n UINT uMouseMsg;\n\n // Check if this is a TaskbarCreated message\n // TaskbarCreated is a system message broadcasted when Windows Explorer restarts\n // At this time all tray icons are destroyed and need to be recreated by applications\n // Handling this message solves the issue of the tray icon disappearing while the program is still running\n if (msg == WM_TASKBARCREATED) {\n // Explorer has restarted, need to recreate the tray icon\n RecreateTaskbarIcon(hwnd, GetModuleHandle(NULL));\n return 0;\n }\n\n switch(msg)\n {\n case WM_CREATE: {\n // Register global hotkeys when window is created\n RegisterGlobalHotkeys(hwnd);\n HandleWindowCreate(hwnd);\n break;\n }\n\n case WM_SETCURSOR: {\n // When in edit mode, always use default arrow cursor\n if (CLOCK_EDIT_MODE && LOWORD(lp) == HTCLIENT) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE; // Indicates we've handled this message\n }\n \n // Also use default arrow cursor when handling tray icon operations\n if (LOWORD(lp) == HTCLIENT || msg == CLOCK_WM_TRAYICON) {\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n return TRUE;\n }\n break;\n }\n\n case WM_LBUTTONDOWN: {\n StartDragWindow(hwnd);\n break;\n }\n\n case WM_LBUTTONUP: {\n EndDragWindow(hwnd);\n break;\n }\n\n case WM_MOUSEWHEEL: {\n int delta = GET_WHEEL_DELTA_WPARAM(wp);\n HandleScaleWindow(hwnd, delta);\n break;\n }\n\n case WM_MOUSEMOVE: {\n if (HandleDragWindow(hwnd)) {\n return 0;\n }\n break;\n }\n\n case WM_PAINT: {\n PAINTSTRUCT ps;\n BeginPaint(hwnd, &ps);\n HandleWindowPaint(hwnd, &ps);\n EndPaint(hwnd, &ps);\n break;\n }\n case WM_TIMER: {\n if (HandleTimerEvent(hwnd, wp)) {\n break;\n }\n break;\n }\n case WM_DESTROY: {\n // Unregister global hotkeys when window is destroyed\n UnregisterGlobalHotkeys(hwnd);\n HandleWindowDestroy(hwnd);\n return 0;\n }\n case CLOCK_WM_TRAYICON: {\n HandleTrayIconMessage(hwnd, (UINT)wp, (UINT)lp);\n break;\n }\n case WM_COMMAND: {\n // Handle preset color options (ID: 201 ~ 201+COLOR_OPTIONS_COUNT-1)\n if (LOWORD(wp) >= 201 && LOWORD(wp) < 201 + COLOR_OPTIONS_COUNT) {\n int colorIndex = LOWORD(wp) - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n // Update current color\n strncpy(CLOCK_TEXT_COLOR, COLOR_OPTIONS[colorIndex].hexColor, \n sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n \n // Write to config file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n \n // Redraw window to show new color\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n WORD cmd = LOWORD(wp);\n switch (cmd) {\n case 101: { \n if (CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_LAST_TIME_UPDATE = 0;\n KillTimer(hwnd, 1);\n }\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n // Handle quick time options (102-102+MAX_TIME_OPTIONS)\n case 102: case 103: case 104: case 105: case 106:\n case 107: case 108: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n int index = cmd - 102;\n if (index >= 0 && index < time_options_count) {\n int minutes = time_options[index];\n if (minutes > 0) {\n KillTimer(hwnd, 1);\n CLOCK_TOTAL_TIME = minutes * 60; // Convert to seconds\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n CLOCK_IS_PAUSED = FALSE; \n elapsed_time = 0; \n message_shown = FALSE; \n countup_message_shown = FALSE;\n \n // If currently in Pomodoro mode, reset the Pomodoro state when switching to normal countdown\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE) {\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n ShowWindow(hwnd, SW_SHOW);\n InvalidateRect(hwnd, NULL, TRUE);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n break;\n }\n // Handle exit option\n case 109: {\n ExitProgram(hwnd);\n break;\n }\n case CLOCK_IDC_MODIFY_TIME_OPTIONS: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_SHORTCUT_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_SHORTCUT_DIALOG);\n\n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n // If input is empty or contains only spaces, exit the loop\n if (inputText[0] == '\\0' || isAllSpaces) {\n break;\n }\n\n char* token = strtok(inputText, \" \");\n char options[256] = {0};\n int valid = 1;\n int count = 0;\n \n while (token && count < MAX_TIME_OPTIONS) {\n int num = atoi(token);\n if (num <= 0) {\n valid = 0;\n break;\n }\n \n if (count > 0) {\n strcat(options, \",\");\n }\n strcat(options, token);\n count++;\n token = strtok(NULL, \" \");\n }\n\n if (valid && count > 0) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigTimeOptions(options);\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd,\n GetLocalizedString(\n L\"请输入用空格分隔的数字\\n\"\n L\"例如: 25 10 5\",\n L\"Enter numbers separated by spaces\\n\"\n L\"Example: 25 10 5\"),\n GetLocalizedString(L\"无效输入\", L\"Invalid Input\"), \n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_MODIFY_DEFAULT_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_STARTUP_DIALOG), NULL, DlgProc, (LPARAM)CLOCK_IDD_STARTUP_DIALOG);\n\n if (inputText[0] == '\\0') {\n break;\n }\n\n // Check if it's only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (isAllSpaces) {\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n ReadConfig();\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case 200: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // First, stop all timers to ensure no timer events will be processed\n KillTimer(hwnd, 1);\n \n // Unregister all global hotkeys to ensure they don't remain active after reset\n UnregisterGlobalHotkeys(hwnd);\n \n // Fully reset timer state - critical part\n // Import all timer state variables that need to be reset\n extern int elapsed_time; // from main.c\n extern int countdown_elapsed_time; // from timer.c\n extern int countup_elapsed_time; // from timer.c\n extern BOOL message_shown; // from main.c \n extern BOOL countdown_message_shown;// from timer.c\n extern BOOL countup_message_shown; // from timer.c\n \n // Import high-precision timer initialization function from timer.c\n extern BOOL InitializeHighPrecisionTimer(void);\n extern void ResetTimer(void); // Use a dedicated reset function\n extern void ReadNotificationMessagesConfig(void); // Read notification message configuration\n \n // Reset all timer state variables - order matters!\n CLOCK_TOTAL_TIME = 25 * 60; // 1. First set total time to 25 minutes\n elapsed_time = 0; // 2. Reset elapsed_time in main.c\n countdown_elapsed_time = 0; // 3. Reset countdown_elapsed_time in timer.c\n countup_elapsed_time = 0; // 4. Reset countup_elapsed_time in timer.c\n message_shown = FALSE; // 5. Reset message status\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set timer state to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Call the dedicated timer reset function - this is crucial!\n // This function reinitializes the high-precision timer and resets all timing states\n ResetTimer();\n \n // Reset UI state\n CLOCK_EDIT_MODE = FALSE;\n SetClickThrough(hwnd, TRUE);\n SendMessage(hwnd, WM_SETREDRAW, FALSE, 0);\n \n // Reset file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n \n // Default language initialization\n AppLanguage defaultLanguage;\n LANGID langId = GetUserDefaultUILanguage();\n WORD primaryLangId = PRIMARYLANGID(langId);\n WORD subLangId = SUBLANGID(langId);\n \n switch (primaryLangId) {\n case LANG_CHINESE:\n defaultLanguage = (subLangId == SUBLANG_CHINESE_SIMPLIFIED) ? \n APP_LANG_CHINESE_SIMP : APP_LANG_CHINESE_TRAD;\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n break;\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n break;\n }\n \n if (CURRENT_LANGUAGE != defaultLanguage) {\n CURRENT_LANGUAGE = defaultLanguage;\n }\n \n // Delete and recreate the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure the file is closed and deleted\n FILE* test = fopen(config_path, \"r\");\n if (test) {\n fclose(test);\n remove(config_path);\n }\n \n // Recreate default configuration\n CreateDefaultConfig(config_path);\n \n // Reread the configuration\n ReadConfig();\n \n // Ensure notification messages are reread\n ReadNotificationMessagesConfig();\n \n // Restore default font\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0) { \n LoadFontFromResource(hInstance, fontResources[i].resourceId);\n break;\n }\n }\n \n // Reset window scale\n CLOCK_WINDOW_SCALE = 1.0f;\n CLOCK_FONT_SCALE_FACTOR = 1.0f;\n \n // Recalculate window size\n HDC hdc = GetDC(hwnd);\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE, \n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, FONT_INTERNAL_NAME\n );\n HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);\n \n char time_text[50];\n FormatTime(CLOCK_TOTAL_TIME, time_text);\n SIZE textSize;\n GetTextExtentPoint32(hdc, time_text, strlen(time_text), &textSize);\n \n SelectObject(hdc, hOldFont);\n DeleteObject(hFont);\n ReleaseDC(hwnd, hdc);\n \n // Set default scale based on screen height\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n float defaultScale = (screenHeight * 0.03f) / 20.0f;\n CLOCK_WINDOW_SCALE = defaultScale;\n CLOCK_FONT_SCALE_FACTOR = defaultScale;\n \n // Reset window position\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n textSize.cx * defaultScale, textSize.cy * defaultScale,\n SWP_NOZORDER | SWP_NOACTIVATE\n );\n \n // Ensure window is visible\n ShowWindow(hwnd, SW_SHOW);\n \n // Restart the timer - ensure it's started after all states are reset\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n SendMessage(hwnd, WM_SETREDRAW, TRUE, 0);\n RedrawWindow(hwnd, NULL, NULL, \n RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);\n \n // Reregister default hotkeys\n RegisterGlobalHotkeys(hwnd);\n \n break;\n }\n case CLOCK_IDM_TIMER_PAUSE_RESUME: {\n PauseResumeTimer(hwnd);\n break;\n }\n case CLOCK_IDM_TIMER_RESTART: {\n // Close all notification windows\n CloseAllNotifications();\n RestartTimer(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE: {\n SetLanguage(APP_LANG_CHINESE_SIMP);\n WriteConfigLanguage(APP_LANG_CHINESE_SIMP);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_CHINESE_TRAD: {\n SetLanguage(APP_LANG_CHINESE_TRAD);\n WriteConfigLanguage(APP_LANG_CHINESE_TRAD);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_ENGLISH: {\n SetLanguage(APP_LANG_ENGLISH);\n WriteConfigLanguage(APP_LANG_ENGLISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_SPANISH: {\n SetLanguage(APP_LANG_SPANISH);\n WriteConfigLanguage(APP_LANG_SPANISH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_FRENCH: {\n SetLanguage(APP_LANG_FRENCH);\n WriteConfigLanguage(APP_LANG_FRENCH);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_GERMAN: {\n SetLanguage(APP_LANG_GERMAN);\n WriteConfigLanguage(APP_LANG_GERMAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_RUSSIAN: {\n SetLanguage(APP_LANG_RUSSIAN);\n WriteConfigLanguage(APP_LANG_RUSSIAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_PORTUGUESE: {\n SetLanguage(APP_LANG_PORTUGUESE);\n WriteConfigLanguage(APP_LANG_PORTUGUESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_JAPANESE: {\n SetLanguage(APP_LANG_JAPANESE);\n WriteConfigLanguage(APP_LANG_JAPANESE);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_LANG_KOREAN: {\n SetLanguage(APP_LANG_KOREAN);\n WriteConfigLanguage(APP_LANG_KOREAN);\n // Refresh window\n InvalidateRect(hwnd, NULL, TRUE);\n // Refresh tray menu\n extern void UpdateTrayIcon(HWND hwnd);\n UpdateTrayIcon(hwnd);\n break;\n }\n case CLOCK_IDM_ABOUT:\n ShowAboutDialog(hwnd);\n return 0;\n case CLOCK_IDM_TOPMOST: {\n // Toggle the topmost state in configuration\n BOOL newTopmost = !CLOCK_WINDOW_TOPMOST;\n \n // If in edit mode, just update the stored state but don't apply it yet\n if (CLOCK_EDIT_MODE) {\n // Update the configuration and saved state only\n PREVIOUS_TOPMOST_STATE = newTopmost;\n CLOCK_WINDOW_TOPMOST = newTopmost;\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n } else {\n // Not in edit mode, apply it immediately\n SetWindowTopmost(hwnd, newTopmost);\n WriteConfigTopmost(newTopmost ? \"TRUE\" : \"FALSE\");\n }\n break;\n }\n case CLOCK_IDM_COUNTDOWN_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = FALSE; // Switch to countdown mode\n }\n \n // Reset the countdown timer\n extern void ResetTimer(void);\n ResetTimer();\n \n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDC_EDIT_MODE: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n } else {\n StartEditMode(hwnd);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n case CLOCK_IDC_CUSTOMIZE_LEFT: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n char hex_color[10];\n snprintf(hex_color, sizeof(hex_color), \"#%02X%02X%02X\", \n GetRValue(color), GetGValue(color), GetBValue(color));\n WriteConfigColor(hex_color);\n ReadConfig();\n }\n break;\n }\n case CLOCK_IDC_FONT_RECMONO: {\n WriteConfigFont(\"RecMonoCasual Nerd Font Mono Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DEPARTURE: {\n WriteConfigFont(\"DepartureMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_TERMINESS: {\n WriteConfigFont(\"Terminess Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PINYON_SCRIPT: {\n WriteConfigFont(\"Pinyon Script Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ARBUTUS: {\n WriteConfigFont(\"Arbutus Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_BERKSHIRE: {\n WriteConfigFont(\"Berkshire Swash Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CAVEAT: {\n WriteConfigFont(\"Caveat Brush Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_CREEPSTER: {\n WriteConfigFont(\"Creepster Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DOTO: { \n WriteConfigFont(\"Doto ExtraBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FOLDIT: {\n WriteConfigFont(\"Foldit SemiBold Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FREDERICKA: {\n WriteConfigFont(\"Fredericka the Great Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_FRIJOLE: {\n WriteConfigFont(\"Frijole Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_GWENDOLYN: {\n WriteConfigFont(\"Gwendolyn Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_HANDJET: {\n WriteConfigFont(\"Handjet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_INKNUT: {\n WriteConfigFont(\"Inknut Antiqua Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARD: {\n WriteConfigFont(\"Jacquard 12 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_JACQUARDA: {\n WriteConfigFont(\"Jacquarda Bastarda 9 Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KAVOON: {\n WriteConfigFont(\"Kavoon Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE: {\n WriteConfigFont(\"Kumar One Outline Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_KUMAR_ONE: {\n WriteConfigFont(\"Kumar One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LAKKI_REDDY: {\n WriteConfigFont(\"Lakki Reddy Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_LICORICE: {\n WriteConfigFont(\"Licorice Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MA_SHAN_ZHENG: {\n WriteConfigFont(\"Ma Shan Zheng Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MOIRAI_ONE: {\n WriteConfigFont(\"Moirai One Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_MYSTERY_QUEST: {\n WriteConfigFont(\"Mystery Quest Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_NOTO_NASTALIQ: {\n WriteConfigFont(\"Noto Nastaliq Urdu Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIEDRA: {\n WriteConfigFont(\"Piedra Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PIXELIFY: {\n WriteConfigFont(\"Pixelify Sans Medium Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PRESS_START: {\n WriteConfigFont(\"Press Start 2P Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BUBBLES: {\n WriteConfigFont(\"Rubik Bubbles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_BURNED: {\n WriteConfigFont(\"Rubik Burned Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_GLITCH: {\n WriteConfigFont(\"Rubik Glitch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_MARKER_HATCH: {\n WriteConfigFont(\"Rubik Marker Hatch Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_PUDDLES: {\n WriteConfigFont(\"Rubik Puddles Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_VINYL: {\n WriteConfigFont(\"Rubik Vinyl Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUBIK_WET_PAINT: {\n WriteConfigFont(\"Rubik Wet Paint Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_RUGE_BOOGIE: {\n WriteConfigFont(\"Ruge Boogie Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SEVILLANA: {\n WriteConfigFont(\"Sevillana Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_SILKSCREEN: {\n WriteConfigFont(\"Silkscreen Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_STICK: {\n WriteConfigFont(\"Stick Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_UNDERDOG: {\n WriteConfigFont(\"Underdog Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_WALLPOET: {\n WriteConfigFont(\"Wallpoet Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_YESTERYEAR: {\n WriteConfigFont(\"Yesteryear Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_ZCOOL_KUAILE: {\n WriteConfigFont(\"ZCOOL KuaiLe Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_PROFONT: {\n WriteConfigFont(\"ProFont IIx Nerd Font Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDC_FONT_DADDYTIME: {\n WriteConfigFont(\"DaddyTimeMono Nerd Font Propo Essence.ttf\");\n goto refresh_window;\n }\n case CLOCK_IDM_SHOW_CURRENT_TIME: { \n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_SHOW_CURRENT_TIME = !CLOCK_SHOW_CURRENT_TIME;\n if (CLOCK_SHOW_CURRENT_TIME) {\n ShowWindow(hwnd, SW_SHOW); \n \n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1); \n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0; // Ensure total time is reset\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n SetTimer(hwnd, 1, 100, NULL); // Reduce interval to 100ms for higher refresh rate\n } else {\n KillTimer(hwnd, 1); \n // When canceling showing current time, fully reset state instead of restoring previous state\n elapsed_time = 0;\n countdown_elapsed_time = 0;\n CLOCK_TOTAL_TIME = 0;\n message_shown = 0; // Reset message shown state\n // Set timer with longer interval because second-level updates are no longer needed\n SetTimer(hwnd, 1, 1000, NULL); \n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_24HOUR_FORMAT: { \n CLOCK_USE_24HOUR = !CLOCK_USE_24HOUR;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_SHOW_SECONDS: { \n CLOCK_SHOW_SECONDS = !CLOCK_SHOW_SECONDS;\n {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n char currentStartupMode[20];\n FILE *fp = fopen(config_path, \"r\");\n if (fp) {\n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(fp);\n \n WriteConfig(config_path);\n \n WriteConfigStartupMode(currentStartupMode);\n } else {\n WriteConfig(config_path);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_RECENT_FILE_1:\n case CLOCK_IDM_RECENT_FILE_2:\n case CLOCK_IDM_RECENT_FILE_3:\n case CLOCK_IDM_RECENT_FILE_4:\n case CLOCK_IDM_RECENT_FILE_5: {\n int index = cmd - CLOCK_IDM_RECENT_FILE_1;\n if (index < CLOCK_RECENT_FILES_COUNT) {\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[index].path, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(CLOCK_RECENT_FILES[index].path);\n \n // Step 2: Update the recent files list (move this file to the top)\n SaveRecentFile(CLOCK_RECENT_FILES[index].path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n \n // Clear invalid file path\n memset(CLOCK_TIMEOUT_FILE_PATH, 0, sizeof(CLOCK_TIMEOUT_FILE_PATH));\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n \n // Remove this file from the recent files list\n for (int i = index; i < CLOCK_RECENT_FILES_COUNT - 1; i++) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i + 1];\n }\n CLOCK_RECENT_FILES_COUNT--;\n \n // Update recent files list in the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n }\n }\n break;\n }\n case CLOCK_IDM_BROWSE_FILE: {\n wchar_t szFile[MAX_PATH] = {0};\n \n OPENFILENAMEW ofn = {0};\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile) / sizeof(wchar_t);\n ofn.lpstrFilter = L\"所有文件\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n \n if (GetOpenFileNameW(&ofn)) {\n // Convert wide character path to UTF-8 to save in the configuration file\n char utf8Path[MAX_PATH * 3] = {0}; // Larger buffer to accommodate UTF-8 encoding\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n \n if (GetFileAttributesW(szFile) != INVALID_FILE_ATTRIBUTES) {\n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"所选文件不存在\", L\"Selected file does not exist\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case CLOCK_IDC_TIMEOUT_BROWSE: {\n OPENFILENAMEW ofn;\n wchar_t szFile[MAX_PATH] = L\"\";\n \n ZeroMemory(&ofn, sizeof(ofn));\n ofn.lStructSize = sizeof(ofn);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFile = szFile;\n ofn.nMaxFile = sizeof(szFile);\n ofn.lpstrFilter = L\"All Files (*.*)\\0*.*\\0\";\n ofn.nFilterIndex = 1;\n ofn.lpstrFileTitle = NULL;\n ofn.nMaxFileTitle = 0;\n ofn.lpstrInitialDir = NULL;\n ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;\n\n if (GetOpenFileNameW(&ofn)) {\n char utf8Path[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, szFile, -1, \n utf8Path, \n sizeof(utf8Path), \n NULL, NULL);\n \n // Step 1: Set as the current file to open on timeout\n WriteConfigTimeoutFile(utf8Path);\n \n // Step 2: Update the recent files list\n SaveRecentFile(utf8Path);\n }\n break;\n }\n case CLOCK_IDM_COUNT_UP: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n CLOCK_COUNT_UP = !CLOCK_COUNT_UP;\n if (CLOCK_COUNT_UP) {\n ShowWindow(hwnd, SW_SHOW);\n \n elapsed_time = 0;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n if (!CLOCK_COUNT_UP) {\n CLOCK_COUNT_UP = TRUE;\n \n // Ensure the timer starts from 0 every time it switches to count-up mode\n countup_elapsed_time = 0;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n } else {\n // Already in count-up mode, so toggle pause/run state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_COUNT_UP_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n\n // Reset the count-up counter\n extern void ResetTimer(void);\n ResetTimer();\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDC_SET_COUNTDOWN_TIME: {\n while (1) {\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), NULL, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n\n if (inputText[0] == '\\0') {\n \n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n \n WriteConfigDefaultStartTime(total_seconds);\n WriteConfigStartupMode(\"COUNTDOWN\");\n \n \n \n CLOCK_DEFAULT_START_TIME = total_seconds;\n \n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n } else {\n MessageBoxW(hwnd, \n GetLocalizedString(\n L\"25 = 25分钟\\n\"\n L\"25h = 25小时\\n\"\n L\"25s = 25秒\\n\"\n L\"25 30 = 25分钟30秒\\n\"\n L\"25 30m = 25小时30分钟\\n\"\n L\"1 30 20 = 1小时30分钟20秒\",\n \n L\"25 = 25 minutes\\n\"\n L\"25h = 25 hours\\n\"\n L\"25s = 25 seconds\\n\"\n L\"25 30 = 25 minutes 30 seconds\\n\"\n L\"25 30m = 25 hours 30 minutes\\n\"\n L\"1 30 20 = 1 hour 30 minutes 20 seconds\"),\n GetLocalizedString(L\"输入格式\", L\"Input Format\"),\n MB_OK);\n }\n }\n break;\n }\n case CLOCK_IDC_START_SHOW_TIME: {\n WriteConfigStartupMode(\"SHOW_TIME\");\n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_CHECKED);\n break;\n }\n case CLOCK_IDC_START_COUNT_UP: {\n WriteConfigStartupMode(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDC_START_NO_DISPLAY: {\n WriteConfigStartupMode(\"NO_DISPLAY\");\n \n HMENU hMenu = GetMenu(hwnd);\n HMENU hTimeOptionsMenu = GetSubMenu(hMenu, GetMenuItemCount(hMenu) - 2);\n HMENU hStartupSettingsMenu = GetSubMenu(hTimeOptionsMenu, 0);\n \n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_SET_COUNTDOWN_TIME, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_COUNT_UP, MF_UNCHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_NO_DISPLAY, MF_CHECKED);\n CheckMenuItem(hStartupSettingsMenu, CLOCK_IDC_START_SHOW_TIME, MF_UNCHECKED);\n break;\n }\n case CLOCK_IDC_AUTO_START: {\n BOOL isEnabled = IsAutoStartEnabled();\n if (isEnabled) {\n if (RemoveShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_UNCHECKED);\n }\n } else {\n if (CreateShortcut()) {\n CheckMenuItem(GetMenu(hwnd), CLOCK_IDC_AUTO_START, MF_CHECKED);\n }\n }\n break;\n }\n case CLOCK_IDC_COLOR_VALUE: {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_COLOR_DIALOG), \n hwnd, \n (DLGPROC)ColorDlgProc);\n break;\n }\n case CLOCK_IDC_COLOR_PANEL: {\n COLORREF color = ShowColorDialog(hwnd);\n if (color != (COLORREF)-1) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case CLOCK_IDM_POMODORO_START: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n if (!IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_SHOW);\n }\n \n // Reset timer state\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // Set work time\n CLOCK_TOTAL_TIME = POMODORO_WORK_TIME;\n \n // Initialize Pomodoro phase\n extern void InitializePomodoro(void);\n InitializePomodoro();\n \n // Save original timeout action\n TimeoutActionType originalAction = CLOCK_TIMEOUT_ACTION;\n \n // Force set to show message\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n \n // Start the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Reset message state\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case CLOCK_IDM_POMODORO_WORK:\n case CLOCK_IDM_POMODORO_BREAK:\n case CLOCK_IDM_POMODORO_LBREAK:\n // Keep original menu item ID handling\n {\n int selectedIndex = 0;\n if (LOWORD(wp) == CLOCK_IDM_POMODORO_WORK) {\n selectedIndex = 0;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_BREAK) {\n selectedIndex = 1;\n } else if (LOWORD(wp) == CLOCK_IDM_POMODORO_LBREAK) {\n selectedIndex = 2;\n }\n \n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n break;\n\n // Also handle new dynamic ID range\n case 600: case 601: case 602: case 603: case 604:\n case 605: case 606: case 607: case 608: case 609:\n // Handle Pomodoro time setting options (dynamic ID range)\n {\n // Calculate the selected option index\n int selectedIndex = LOWORD(wp) - CLOCK_IDM_POMODORO_TIME_BASE;\n \n if (selectedIndex >= 0 && selectedIndex < POMODORO_TIMES_COUNT) {\n // Use a common dialog to modify Pomodoro time\n memset(inputText, 0, sizeof(inputText));\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_TIME_DIALOG),\n hwnd, DlgProc, (LPARAM)CLOCK_IDD_POMODORO_TIME_DIALOG);\n \n // Process input result\n if (inputText[0] && !isAllSpacesOnly(inputText)) {\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Update selected time\n POMODORO_TIMES[selectedIndex] = total_seconds;\n \n // Use existing function to update configuration\n // IMPORTANT: Add config write for dynamic IDs\n WriteConfigPomodoroTimeOptions(POMODORO_TIMES, POMODORO_TIMES_COUNT);\n \n // Update core variables\n if (selectedIndex == 0) POMODORO_WORK_TIME = total_seconds;\n else if (selectedIndex == 1) POMODORO_SHORT_BREAK = total_seconds;\n else if (selectedIndex == 2) POMODORO_LONG_BREAK = total_seconds;\n }\n }\n }\n }\n break;\n case CLOCK_IDM_POMODORO_LOOP_COUNT:\n ShowPomodoroLoopDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_RESET: {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Call ResetTimer to reset the timer state\n extern void ResetTimer(void);\n ResetTimer();\n \n // If currently in Pomodoro mode, reset related states\n if (CLOCK_TOTAL_TIME == POMODORO_WORK_TIME || \n CLOCK_TOTAL_TIME == POMODORO_SHORT_BREAK || \n CLOCK_TOTAL_TIME == POMODORO_LONG_BREAK) {\n // Restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Force redraw of the window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure the window is on top and visible after reset\n HandleWindowReset(hwnd);\n break;\n }\n case CLOCK_IDM_TIMEOUT_SHOW_TIME: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n WriteConfigTimeoutAction(\"SHOW_TIME\");\n break;\n }\n case CLOCK_IDM_TIMEOUT_COUNT_UP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n WriteConfigTimeoutAction(\"COUNT_UP\");\n break;\n }\n case CLOCK_IDM_SHOW_MESSAGE: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n WriteConfigTimeoutAction(\"MESSAGE\");\n break;\n }\n case CLOCK_IDM_LOCK_SCREEN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n WriteConfigTimeoutAction(\"LOCK\");\n break;\n }\n case CLOCK_IDM_SHUTDOWN: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHUTDOWN;\n WriteConfigTimeoutAction(\"SHUTDOWN\");\n break;\n }\n case CLOCK_IDM_RESTART: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RESTART;\n WriteConfigTimeoutAction(\"RESTART\");\n break;\n }\n case CLOCK_IDM_SLEEP: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n WriteConfigTimeoutAction(\"SLEEP\");\n break;\n }\n case CLOCK_IDM_RUN_COMMAND: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n WriteConfigTimeoutAction(\"RUN_COMMAND\");\n break;\n }\n case CLOCK_IDM_HTTP_REQUEST: {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n WriteConfigTimeoutAction(\"HTTP_REQUEST\");\n break;\n }\n case CLOCK_IDM_CHECK_UPDATE: {\n // Call async update check function - non-silent mode\n CheckForUpdateAsync(hwnd, FALSE);\n break;\n }\n case CLOCK_IDM_OPEN_WEBSITE:\n // Don't set action type immediately, wait for dialog result\n ShowWebsiteDialog(hwnd);\n break;\n \n case CLOCK_IDM_CURRENT_WEBSITE:\n ShowWebsiteDialog(hwnd);\n break;\n case CLOCK_IDM_POMODORO_COMBINATION:\n ShowPomodoroComboDialog(hwnd);\n break;\n case CLOCK_IDM_NOTIFICATION_CONTENT: {\n ShowNotificationMessagesDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_DISPLAY: {\n ShowNotificationDisplayDialog(hwnd);\n break;\n }\n case CLOCK_IDM_NOTIFICATION_SETTINGS: {\n ShowNotificationSettingsDialog(hwnd);\n break;\n }\n case CLOCK_IDM_HOTKEY_SETTINGS: {\n ShowHotkeySettingsDialog(hwnd);\n // Register/reregister global hotkeys\n RegisterGlobalHotkeys(hwnd);\n break;\n }\n case CLOCK_IDM_HELP: {\n OpenUserGuide();\n break;\n }\n case CLOCK_IDM_SUPPORT: {\n OpenSupportPage();\n break;\n }\n case CLOCK_IDM_FEEDBACK: {\n OpenFeedbackPage();\n break;\n }\n }\n break;\n\nrefresh_window:\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n }\n case WM_WINDOWPOSCHANGED: {\n if (CLOCK_EDIT_MODE) {\n SaveWindowSettings(hwnd);\n }\n break;\n }\n case WM_RBUTTONUP: {\n if (CLOCK_EDIT_MODE) {\n EndEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_MEASUREITEM:\n {\n LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT)lp;\n if (lpmis->CtlType == ODT_MENU) {\n lpmis->itemHeight = 25;\n lpmis->itemWidth = 100;\n return TRUE;\n }\n return FALSE;\n }\n case WM_DRAWITEM:\n {\n LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT)lp;\n if (lpdis->CtlType == ODT_MENU) {\n int colorIndex = lpdis->itemID - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n const char* hexColor = COLOR_OPTIONS[colorIndex].hexColor;\n int r, g, b;\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n \n HBRUSH hBrush = CreateSolidBrush(RGB(r, g, b));\n HPEN hPen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n \n HGDIOBJ oldBrush = SelectObject(lpdis->hDC, hBrush);\n HGDIOBJ oldPen = SelectObject(lpdis->hDC, hPen);\n \n Rectangle(lpdis->hDC, lpdis->rcItem.left, lpdis->rcItem.top,\n lpdis->rcItem.right, lpdis->rcItem.bottom);\n \n SelectObject(lpdis->hDC, oldPen);\n SelectObject(lpdis->hDC, oldBrush);\n DeleteObject(hPen);\n DeleteObject(hBrush);\n \n if (lpdis->itemState & ODS_SELECTED) {\n DrawFocusRect(lpdis->hDC, &lpdis->rcItem);\n }\n \n return TRUE;\n }\n }\n return FALSE;\n }\n case WM_MENUSELECT: {\n UINT menuItem = LOWORD(wp);\n UINT flags = HIWORD(wp);\n HMENU hMenu = (HMENU)lp;\n\n if (!(flags & MF_POPUP) && hMenu != NULL) {\n int colorIndex = menuItem - 201;\n if (colorIndex >= 0 && colorIndex < COLOR_OPTIONS_COUNT) {\n strncpy(PREVIEW_COLOR, COLOR_OPTIONS[colorIndex].hexColor, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (fontResources[i].menuId == menuItem) {\n strncpy(PREVIEW_FONT_NAME, fontResources[i].fontName, 99);\n PREVIEW_FONT_NAME[99] = '\\0';\n \n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, 99);\n PREVIEW_INTERNAL_NAME[99] = '\\0';\n char* dot = strrchr(PREVIEW_INTERNAL_NAME, '.');\n if (dot) *dot = '\\0';\n \n LoadFontByName((HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), \n fontResources[i].fontName);\n \n IS_PREVIEWING = TRUE;\n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n }\n \n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n } else if (flags & MF_POPUP) {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n break;\n }\n case WM_EXITMENULOOP: {\n if (IS_PREVIEWING || IS_COLOR_PREVIEWING) {\n IS_PREVIEWING = FALSE;\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n break;\n }\n case WM_RBUTTONDOWN: {\n if (GetKeyState(VK_CONTROL) & 0x8000) {\n // Toggle edit mode\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Entering edit mode\n SetClickThrough(hwnd, FALSE);\n } else {\n // Exiting edit mode\n SetClickThrough(hwnd, TRUE);\n SaveWindowSettings(hwnd); // Save settings when exiting edit mode\n WriteConfigColor(CLOCK_TEXT_COLOR); // Save the current color to config\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n return 0;\n }\n break;\n }\n case WM_CLOSE: {\n SaveWindowSettings(hwnd); // Save window settings before closing\n DestroyWindow(hwnd); // Close the window\n break;\n }\n case WM_LBUTTONDBLCLK: {\n if (!CLOCK_EDIT_MODE) {\n // Enter edit mode\n StartEditMode(hwnd);\n return 0;\n }\n break;\n }\n case WM_HOTKEY: {\n // WM_HOTKEY message's lp contains key information\n if (wp == HOTKEY_ID_SHOW_TIME) {\n ToggleShowTimeMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNT_UP) {\n StartCountUp(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_COUNTDOWN) {\n StartDefaultCountDown(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_CUSTOM_COUNTDOWN) {\n // Check if the input dialog already exists\n if (g_hwndInputDialog != NULL && IsWindow(g_hwndInputDialog)) {\n // The dialog already exists, close it\n SendMessage(g_hwndInputDialog, WM_CLOSE, 0, 0);\n return 0;\n }\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Show input dialog to set countdown\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Clear input text\n memset(inputText, 0, sizeof(inputText));\n \n // Show input dialog\n INT_PTR result = DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_DIALOG1), \n hwnd, DlgProc, (LPARAM)CLOCK_IDD_DIALOG1);\n \n // If the dialog has input and was confirmed\n if (inputText[0] != '\\0') {\n // Check if input is valid\n int total_seconds = 0;\n if (ParseInput(inputText, &total_seconds)) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Set countdown state\n CLOCK_TOTAL_TIME = total_seconds;\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n \n // Switch to countdown mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // Stop and restart the timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Refresh window display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN1) {\n // Start quick countdown 1\n StartQuickCountdown1(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN2) {\n // Start quick countdown 2\n StartQuickCountdown2(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_QUICK_COUNTDOWN3) {\n // Start quick countdown 3\n StartQuickCountdown3(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_POMODORO) {\n // Start Pomodoro timer\n StartPomodoroTimer(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_TOGGLE_VISIBILITY) {\n // Hide/show window\n if (IsWindowVisible(hwnd)) {\n ShowWindow(hwnd, SW_HIDE);\n } else {\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n }\n return 0;\n } else if (wp == HOTKEY_ID_EDIT_MODE) {\n // Enter edit mode\n ToggleEditMode(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_PAUSE_RESUME) {\n // Pause/resume timer\n TogglePauseResume(hwnd);\n return 0;\n } else if (wp == HOTKEY_ID_RESTART_TIMER) {\n // Close all notification windows\n CloseAllNotifications();\n // Restart current timer\n RestartCurrentTimer(hwnd);\n return 0;\n }\n break;\n }\n // Handle reregistration message after hotkey settings change\n case WM_APP+1: {\n // Only reregister hotkeys, do not open dialog\n RegisterGlobalHotkeys(hwnd);\n return 0;\n }\n default:\n return DefWindowProc(hwnd, msg, wp, lp);\n }\n return 0;\n}\n\n// External variable declarations\nextern int CLOCK_DEFAULT_START_TIME;\nextern int countdown_elapsed_time;\nextern BOOL CLOCK_IS_PAUSED;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern int CLOCK_TOTAL_TIME;\n\n// Remove menu items\nvoid RemoveMenuItems(HMENU hMenu, int count);\n\n// Add menu item\nvoid AddMenuItem(HMENU hMenu, UINT id, const char* text, BOOL isEnabled);\n\n// Modify menu item text\nvoid ModifyMenuItemText(HMENU hMenu, UINT id, const char* text);\n\n/**\n * @brief Toggle show current time mode\n * @param hwnd Window handle\n */\nvoid ToggleShowTimeMode(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // If not currently in show current time mode, then enable it\n // If already in show current time mode, do nothing (don't turn it off)\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Switch to show current time mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n \n // Reset the timer to ensure the update frequency is correct\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 100, NULL); // Use 100ms update frequency to keep the time display smooth\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n }\n // Already in show current time mode, do nothing\n}\n\n/**\n * @brief Start count up timer\n * @param hwnd Window handle\n */\nvoid StartCountUp(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Declare external variables\n extern int countup_elapsed_time;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Reset count up counter\n countup_elapsed_time = 0;\n \n // Set to count up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start default countdown\n * @param hwnd Window handle\n */\nvoid StartDefaultCountDown(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // Set mode\n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n if (CLOCK_DEFAULT_START_TIME > 0) {\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n } else {\n // If no default countdown is set, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, 101, 0);\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Start Pomodoro timer\n * @param hwnd Window handle\n */\nvoid StartPomodoroTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n // If it was previously in show current time mode, stop the old timer\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n }\n \n // Use the Pomodoro menu item command to start the Pomodoro timer\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDM_POMODORO_START, 0);\n}\n\n/**\n * @brief Toggle edit mode\n * @param hwnd Window handle\n */\nvoid ToggleEditMode(HWND hwnd) {\n CLOCK_EDIT_MODE = !CLOCK_EDIT_MODE;\n \n if (CLOCK_EDIT_MODE) {\n // Record the current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If not currently topmost, set it to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure the window is visible and in the foreground\n ShowWindow(hwnd, SW_SHOW);\n SetForegroundWindow(hwnd);\n } else {\n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, TRUE);\n \n // If it was not topmost before, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Save window settings and color settings\n SaveWindowSettings(hwnd);\n WriteConfigColor(CLOCK_TEXT_COLOR);\n }\n \n // Refresh the window\n InvalidateRect(hwnd, NULL, TRUE);\n}\n\n/**\n * @brief Pause/resume timer\n * @param hwnd Window handle\n */\nvoid TogglePauseResume(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart the current timer\n * @param hwnd Window handle\n */\nvoid RestartCurrentTimer(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Only effective when not in show time mode\n if (!CLOCK_SHOW_CURRENT_TIME) {\n // Variables imported from main.c\n extern int elapsed_time;\n extern BOOL message_shown;\n \n // Reset message shown state to allow notification and sound to be played again when timer ends\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n if (CLOCK_COUNT_UP) {\n // Reset count up timer\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else {\n // Reset countdown timer\n countdown_elapsed_time = 0;\n elapsed_time = 0;\n }\n CLOCK_IS_PAUSED = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Start quick countdown 1\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown1(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there is at least one preset time option\n if (time_options_count > 0) {\n CLOCK_TOTAL_TIME = time_options[0] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are no preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 2\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown2(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least two preset time options\n if (time_options_count > 1) {\n CLOCK_TOTAL_TIME = time_options[1] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n\n/**\n * @brief Start quick countdown 3\n * @param hwnd Window handle\n */\nvoid StartQuickCountdown3(HWND hwnd) {\n // Stop any notification sound that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Close all notification windows\n CloseAllNotifications();\n \n // Reset notification flag to ensure notification can be shown when countdown ends\n extern BOOL countdown_message_shown;\n countdown_message_shown = FALSE;\n \n // Ensure latest notification configuration is read\n extern void ReadNotificationTypeConfig(void);\n ReadNotificationTypeConfig();\n \n extern int time_options[];\n extern int time_options_count;\n \n // Save previous state to determine if timer needs to be reset\n BOOL wasShowingTime = CLOCK_SHOW_CURRENT_TIME;\n \n CLOCK_COUNT_UP = FALSE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Check if there are at least three preset time options\n if (time_options_count > 2) {\n CLOCK_TOTAL_TIME = time_options[2] * 60; // Convert minutes to seconds\n countdown_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n \n // If it was previously in show current time mode, stop the old timer and start a new one\n if (wasShowingTime) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL); // Set to update once per second\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // If there are not enough preset time options, show the settings dialog\n PostMessage(hwnd, WM_COMMAND, CLOCK_IDC_MODIFY_TIME_OPTIONS, 0);\n }\n}\n"], ["/Catime/src/dialog_procedure.c", "/**\n * @file dialog_procedure.c\n * @brief Implementation of dialog message handling procedures\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/audio_player.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/hotkey.h\"\n#include \"../include/dialog_language.h\"\n\nstatic void DrawColorSelectButton(HDC hdc, HWND hwnd);\n\nextern char inputText[256];\n\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES];\nextern int POMODORO_TIMES_COUNT;\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nWNDPROC wpOrigEditProc;\n\nstatic HWND g_hwndAboutDlg = NULL;\nstatic HWND g_hwndErrorDlg = NULL;\nHWND g_hwndInputDialog = NULL;\nstatic WNDPROC wpOrigLoopEditProc;\n\n#define URL_GITHUB_REPO L\"https://github.com/vladelaina/Catime\"\n\nLRESULT APIENTRY EditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n static BOOL firstKeyProcessed = FALSE;\n\n switch (msg) {\n case WM_SETFOCUS:\n PostMessage(hwnd, EM_SETSEL, 0, -1);\n firstKeyProcessed = FALSE;\n break;\n\n case WM_KEYDOWN:\n if (!firstKeyProcessed) {\n firstKeyProcessed = TRUE;\n }\n\n if (wParam == VK_RETURN) {\n HWND hwndOkButton = GetDlgItem(GetParent(hwnd), CLOCK_IDC_BUTTON_OK);\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwndOkButton);\n return 0;\n }\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n\n case WM_CHAR:\n if (wParam == 1 || (wParam == 'a' || wParam == 'A') && GetKeyState(VK_CONTROL) < 0) {\n return 0;\n }\n if (wParam == VK_RETURN) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(wpOrigEditProc, hwnd, msg, wParam, lParam);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\nvoid ShowErrorDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDD_ERROR_DIALOG),\n hwndParent,\n ErrorDlgProc);\n}\n\nINT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG:\n SetDlgItemTextW(hwndDlg, IDC_ERROR_TEXT,\n GetLocalizedString(L\"输入格式无效,请重新输入。\", L\"Invalid input format, please try again.\"));\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"错误\", L\"Error\"));\n return TRUE;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Input dialog procedure\n */\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n\n g_hwndInputDialog = hwndDlg;\n\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n DWORD dlgId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n\n ApplyDialogLanguage(hwndDlg, (int)dlgId);\n\n if (dlgId == CLOCK_IDD_SHORTCUT_DIALOG) {\n }\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n\n SetFocus(hwndEdit);\n\n PostMessage(hwndDlg, WM_APP+100, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+101, 0, (LPARAM)hwndEdit);\n PostMessage(hwndDlg, WM_APP+102, 0, (LPARAM)hwndEdit);\n\n SendDlgItemMessage(hwndDlg, CLOCK_IDC_EDIT, EM_SETSEL, 0, -1);\n\n SendMessage(hwndDlg, DM_SETDEFID, CLOCK_IDC_BUTTON_OK, 0);\n\n SetTimer(hwndDlg, 9999, 50, NULL);\n\n PostMessage(hwndDlg, WM_APP+103, 0, 0);\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return FALSE;\n }\n\n case WM_CLOSE: {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n\n case WM_CTLCOLOREDIT: {\n HDC hdcEdit = (HDC)wParam;\n SetBkColor(hdcEdit, RGB(0xFF, 0xFF, 0xFF));\n if (!hEditBrush) {\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n }\n return (INT_PTR)hEditBrush;\n }\n\n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, inputText, sizeof(inputText));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; inputText[i]; i++) {\n if (!isspace((unsigned char)inputText[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (inputText[0] == '\\0' || isAllSpaces) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, 0);\n return TRUE;\n }\n\n int total_seconds;\n if (ParseInput(inputText, &total_seconds)) {\n int dialogId = GetWindowLongPtr(hwndDlg, GWLP_USERDATA);\n if (dialogId == CLOCK_IDD_POMODORO_TIME_DIALOG) {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_POMODORO_LOOP_DIALOG) {\n WriteConfigPomodoroLoopCount(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_STARTUP_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else if (dialogId == CLOCK_IDD_SHORTCUT_DIALOG) {\n WriteConfigDefaultStartTime(total_seconds);\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n } else {\n g_hwndInputDialog = NULL;\n EndDialog(hwndDlg, IDOK);\n }\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n return TRUE;\n }\n break;\n\n case WM_TIMER:\n if (wParam == 9999) {\n KillTimer(hwndDlg, 9999);\n\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit && IsWindow(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n return TRUE;\n }\n break;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n int dlgId = GetDlgCtrlID((HWND)lParam);\n if (dlgId == CLOCK_IDD_COLOR_DIALOG) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n } else {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n }\n return TRUE;\n }\n break;\n\n case WM_APP+100:\n case WM_APP+101:\n case WM_APP+102:\n if (lParam) {\n HWND hwndEdit = (HWND)lParam;\n if (IsWindow(hwndEdit) && IsWindowVisible(hwndEdit)) {\n SetForegroundWindow(hwndDlg);\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n }\n }\n return TRUE;\n\n case WM_APP+103:\n {\n INPUT inputs[8] = {0};\n int inputCount = 0;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RSHIFT;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RCONTROL;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RMENU;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_LWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n inputs[inputCount].type = INPUT_KEYBOARD;\n inputs[inputCount].ki.wVk = VK_RWIN;\n inputs[inputCount].ki.dwFlags = KEYEVENTF_KEYUP;\n inputCount++;\n\n SendInput(inputCount, inputs, sizeof(INPUT));\n }\n return TRUE;\n\n case WM_DESTROY:\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n g_hwndInputDialog = NULL;\n }\n break;\n }\n return FALSE;\n}\n\nINT_PTR CALLBACK AboutDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HICON hLargeIcon = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n hLargeIcon = (HICON)LoadImage(GetModuleHandle(NULL),\n MAKEINTRESOURCE(IDI_CATIME),\n IMAGE_ICON,\n ABOUT_ICON_SIZE,\n ABOUT_ICON_SIZE,\n LR_DEFAULTCOLOR);\n\n if (hLargeIcon) {\n SendDlgItemMessage(hwndDlg, IDC_ABOUT_ICON, STM_SETICON, (WPARAM)hLargeIcon, 0);\n }\n\n ApplyDialogLanguage(hwndDlg, IDD_ABOUT_DIALOG);\n\n const wchar_t* versionFormat = GetDialogLocalizedString(IDD_ABOUT_DIALOG, IDC_VERSION_TEXT);\n if (versionFormat) {\n wchar_t versionText[256];\n StringCbPrintfW(versionText, sizeof(versionText), versionFormat, CATIME_VERSION);\n SetDlgItemTextW(hwndDlg, IDC_VERSION_TEXT, versionText);\n }\n\n SetDlgItemTextW(hwndDlg, IDC_CREDIT_LINK, GetLocalizedString(L\"特别感谢猫屋敷梨梨Official提供的图标\", L\"Special thanks to Neko House Lili Official for the icon\"));\n SetDlgItemTextW(hwndDlg, IDC_CREDITS, GetLocalizedString(L\"鸣谢\", L\"Credits\"));\n SetDlgItemTextW(hwndDlg, IDC_BILIBILI_LINK, GetLocalizedString(L\"BiliBili\", L\"BiliBili\"));\n SetDlgItemTextW(hwndDlg, IDC_GITHUB_LINK, GetLocalizedString(L\"GitHub\", L\"GitHub\"));\n SetDlgItemTextW(hwndDlg, IDC_COPYRIGHT_LINK, GetLocalizedString(L\"版权声明\", L\"Copyright Notice\"));\n SetDlgItemTextW(hwndDlg, IDC_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n\n char month[4];\n int day, year, hour, min, sec;\n\n sscanf(__DATE__, \"%3s %d %d\", month, &day, &year);\n sscanf(__TIME__, \"%d:%d:%d\", &hour, &min, &sec);\n\n const char* months[] = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n \"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n int month_num = 0;\n while (++month_num <= 12 && strcmp(month, months[month_num-1]));\n\n const wchar_t* dateFormat = GetLocalizedString(L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\",\n L\"Build Date: %04d/%02d/%02d %02d:%02d:%02d (UTC+8)\");\n\n wchar_t timeStr[60];\n StringCbPrintfW(timeStr, sizeof(timeStr), dateFormat,\n year, month_num, day, hour, min, sec);\n\n SetDlgItemTextW(hwndDlg, IDC_BUILD_DATE, timeStr);\n\n return TRUE;\n }\n\n case WM_DESTROY:\n if (hLargeIcon) {\n DestroyIcon(hLargeIcon);\n hLargeIcon = NULL;\n }\n g_hwndAboutDlg = NULL;\n break;\n\n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, LOWORD(wParam));\n g_hwndAboutDlg = NULL;\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDIT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://space.bilibili.com/26087398\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_BILIBILI_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_BILIBILI_SPACE, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_GITHUB_LINK) {\n ShellExecuteW(NULL, L\"open\", URL_GITHUB_REPO, NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_CREDITS) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/#thanks\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_SUPPORT) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support.html\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n if (LOWORD(wParam) == IDC_COPYRIGHT_LINK) {\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime#️copyright-notice\", NULL, NULL, SW_SHOWNORMAL);\n return TRUE;\n }\n break;\n\n case WM_CLOSE:\n // Close all child dialogs\n EndDialog(hwndDlg, 0);\n g_hwndAboutDlg = NULL; // Clear dialog handle\n return TRUE;\n\n case WM_CTLCOLORSTATIC:\n {\n HDC hdc = (HDC)wParam;\n HWND hwndCtl = (HWND)lParam;\n \n if (GetDlgCtrlID(hwndCtl) == IDC_CREDIT_LINK || \n GetDlgCtrlID(hwndCtl) == IDC_BILIBILI_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_GITHUB_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_CREDITS ||\n GetDlgCtrlID(hwndCtl) == IDC_COPYRIGHT_LINK ||\n GetDlgCtrlID(hwndCtl) == IDC_SUPPORT) {\n SetTextColor(hdc, 0x00D26919); // Keep the same orange color (BGR format)\n SetBkMode(hdc, TRANSPARENT);\n return (INT_PTR)GetStockObject(NULL_BRUSH);\n }\n break;\n }\n }\n return FALSE;\n}\n\n// Add DPI awareness related type definitions (if not provided by the compiler)\n#ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n// DPI_AWARENESS_CONTEXT is a HANDLE\ntypedef HANDLE DPI_AWARENESS_CONTEXT;\n// Related DPI context constants definition\n#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n#endif\n\n// Show the About dialog\nvoid ShowAboutDialog(HWND hwndParent) {\n // If an About dialog already exists, close it first\n if (g_hwndAboutDlg != NULL && IsWindow(g_hwndAboutDlg)) {\n EndDialog(g_hwndAboutDlg, 0);\n g_hwndAboutDlg = NULL;\n }\n \n // Save current DPI awareness context\n HANDLE hOldDpiContext = NULL;\n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n // Function pointer type definitions\n typedef HANDLE (WINAPI* GetThreadDpiAwarenessContextFunc)(void);\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n \n GetThreadDpiAwarenessContextFunc getThreadDpiAwarenessContextFunc = \n (GetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"GetThreadDpiAwarenessContext\");\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (getThreadDpiAwarenessContextFunc && setThreadDpiAwarenessContextFunc) {\n // Save current DPI context\n hOldDpiContext = getThreadDpiAwarenessContextFunc();\n // Set to per-monitor DPI awareness V2 mode\n setThreadDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n }\n }\n \n // Create new About dialog\n g_hwndAboutDlg = CreateDialog(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_ABOUT_DIALOG), \n hwndParent, \n AboutDlgProc);\n \n // Restore original DPI awareness context\n if (hUser32 && hOldDpiContext) {\n typedef HANDLE (WINAPI* SetThreadDpiAwarenessContextFunc)(HANDLE);\n SetThreadDpiAwarenessContextFunc setThreadDpiAwarenessContextFunc = \n (SetThreadDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetThreadDpiAwarenessContext\");\n \n if (setThreadDpiAwarenessContextFunc) {\n setThreadDpiAwarenessContextFunc(hOldDpiContext);\n }\n }\n \n ShowWindow(g_hwndAboutDlg, SW_SHOW);\n}\n\n// Add global variable to track pomodoro loop count setting dialog handle\nstatic HWND g_hwndPomodoroLoopDialog = NULL;\n\nvoid ShowPomodoroLoopDialog(HWND hwndParent) {\n if (!g_hwndPomodoroLoopDialog) {\n g_hwndPomodoroLoopDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_LOOP_DIALOG),\n hwndParent,\n PomodoroLoopDlgProc\n );\n if (g_hwndPomodoroLoopDialog) {\n ShowWindow(g_hwndPomodoroLoopDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroLoopDialog);\n }\n}\n\n// Add subclassing procedure for loop count edit box\nLRESULT APIENTRY LoopEditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n switch (uMsg) {\n case WM_KEYDOWN: {\n if (wParam == VK_RETURN) {\n // Send BM_CLICK message to the parent window (dialog)\n SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(CLOCK_IDC_BUTTON_OK, BN_CLICKED), (LPARAM)hwnd);\n return 0;\n }\n // Handle Ctrl+A select all\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n break;\n }\n case WM_CHAR: {\n // Handle Ctrl+A character message to prevent alert sound\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n // Prevent Enter key from generating character messages for further processing to avoid alert sound\n if (wParam == VK_RETURN) { // VK_RETURN (0x0D) is the char code for Enter\n return 0;\n }\n break;\n }\n }\n return CallWindowProc(wpOrigLoopEditProc, hwnd, uMsg, wParam, lParam);\n}\n\n// Modify helper function to handle numeric input with spaces\nBOOL IsValidNumberInput(const wchar_t* str) {\n // Check if empty\n if (!str || !*str) {\n return FALSE;\n }\n \n BOOL hasDigit = FALSE; // Used to track if at least one digit is found\n wchar_t cleanStr[16] = {0}; // Used to store cleaned string\n int cleanIndex = 0;\n \n // Traverse string, ignore spaces, only keep digits\n for (int i = 0; str[i]; i++) {\n if (iswdigit(str[i])) {\n cleanStr[cleanIndex++] = str[i];\n hasDigit = TRUE;\n } else if (!iswspace(str[i])) { // If not a space and not a digit, then invalid\n return FALSE;\n }\n }\n \n return hasDigit; // Return TRUE as long as there is at least one digit\n}\n\n// Modify PomodoroLoopDlgProc function\nINT_PTR CALLBACK PomodoroLoopDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_LOOP_DIALOG);\n \n // Set static text\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_STATIC, GetLocalizedString(L\"请输入循环次数(1-100):\", L\"Please enter loop count (1-100):\"));\n \n // Set focus to edit box\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetFocus(hwndEdit);\n \n // Subclass edit control\n wpOrigLoopEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, \n (LONG_PTR)LoopEditSubclassProc);\n \n return FALSE;\n }\n\n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n wchar_t input_str[16];\n GetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, input_str, sizeof(input_str)/sizeof(wchar_t));\n \n // Check if input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; input_str[i]; i++) {\n if (!iswspace(input_str[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (input_str[0] == L'\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n \n // Validate input and handle spaces\n if (!IsValidNumberInput(input_str)) {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n \n // Extract digits (ignoring spaces)\n wchar_t cleanStr[16] = {0};\n int cleanIndex = 0;\n for (int i = 0; input_str[i]; i++) {\n if (iswdigit(input_str[i])) {\n cleanStr[cleanIndex++] = input_str[i];\n }\n }\n \n int new_loop_count = _wtoi(cleanStr);\n if (new_loop_count >= 1 && new_loop_count <= 100) {\n // Update configuration file and global variables\n WriteConfigPomodoroLoopCount(new_loop_count);\n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroLoopDialog = NULL;\n } else {\n ShowErrorDialog(hwndDlg);\n SetDlgItemTextW(hwndDlg, CLOCK_IDC_EDIT, L\"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n break;\n\n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigLoopEditProc);\n }\n break;\n\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroLoopDialog = NULL;\n return TRUE;\n }\n return FALSE;\n}\n\n// Add global variable to track website URL dialog handle\nstatic HWND g_hwndWebsiteDialog = NULL;\n\n// Website URL input dialog procedure\nINT_PTR CALLBACK WebsiteDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n // Set dialog as modal\n SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);\n \n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // If URL already exists, prefill the edit box\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, CLOCK_TIMEOUT_WEBSITE_URL);\n }\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_WEBSITE_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || HIWORD(wParam) == BN_CLICKED) {\n char url[MAX_PATH] = {0};\n GetDlgItemText(hwndDlg, CLOCK_IDC_EDIT, url, sizeof(url));\n \n // Check if the input is empty or contains only spaces\n BOOL isAllSpaces = TRUE;\n for (int i = 0; url[i]; i++) {\n if (!isspace((unsigned char)url[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n \n if (url[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n // Validate URL format - simple check, should at least contain http:// or https://\n if (strncmp(url, \"http://\", 7) != 0 && strncmp(url, \"https://\", 8) != 0) {\n // Add https:// prefix\n char tempUrl[MAX_PATH] = \"https://\";\n StringCbCatA(tempUrl, sizeof(tempUrl), url);\n StringCbCopyA(url, sizeof(url), tempUrl);\n }\n \n // Update configuration\n WriteConfigTimeoutWebsite(url);\n EndDialog(hwndDlg, IDOK);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // User cancelled, don't change timeout action\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndWebsiteDialog = NULL;\n return TRUE;\n }\n \n return FALSE;\n}\n\n// Show website URL input dialog\nvoid ShowWebsiteDialog(HWND hwndParent) {\n // Use modal dialog instead of modeless dialog, so we can know whether the user confirmed or cancelled\n INT_PTR result = DialogBox(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_WEBSITE_DIALOG),\n hwndParent,\n WebsiteDialogProc\n );\n \n // Only when the user clicks OK and inputs a valid URL will IDOK be returned, at which point WebsiteDialogProc has already set CLOCK_TIMEOUT_ACTION\n // If the user cancels or closes the dialog, the timeout action won't be changed\n}\n\n// Set global variable to track the Pomodoro combination dialog handle\nstatic HWND g_hwndPomodoroComboDialog = NULL;\n\n// Add Pomodoro combination dialog procedure\nINT_PTR CALLBACK PomodoroComboDialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set background and control colors\n hBackgroundBrush = CreateSolidBrush(RGB(240, 240, 240));\n hEditBrush = CreateSolidBrush(RGB(255, 255, 255));\n hButtonBrush = CreateSolidBrush(RGB(240, 240, 240));\n \n // Subclass the edit control to support Enter key submission\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Read current pomodoro time options from configuration and format for display\n char currentOptions[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char timeStr[32];\n int seconds = POMODORO_TIMES[i];\n \n // Format time into human-readable format\n if (seconds >= 3600) {\n int hours = seconds / 3600;\n int mins = (seconds % 3600) / 60;\n int secs = seconds % 60;\n if (mins == 0 && secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh \", hours);\n else if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm \", hours, mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dh%dm%ds \", hours, mins, secs);\n } else if (seconds >= 60) {\n int mins = seconds / 60;\n int secs = seconds % 60;\n if (secs == 0)\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm \", mins);\n else\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%dm%ds \", mins, secs);\n } else {\n StringCbPrintfA(timeStr, sizeof(timeStr), \"%ds \", seconds);\n }\n \n StringCbCatA(currentOptions, sizeof(currentOptions), timeStr);\n }\n \n // Remove trailing space\n if (strlen(currentOptions) > 0 && currentOptions[strlen(currentOptions) - 1] == ' ') {\n currentOptions[strlen(currentOptions) - 1] = '\\0';\n }\n \n // Set edit box text\n SetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, currentOptions);\n \n // Apply multilingual support - moved here to ensure all default text is covered\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_POMODORO_COMBO_DIALOG);\n \n // Set focus to edit box and select all text\n SetFocus(hwndEdit);\n SendMessage(hwndEdit, EM_SETSEL, 0, -1);\n \n return FALSE; // Because we manually set the focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(240, 240, 240));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(255, 255, 255));\n return (INT_PTR)hEditBrush;\n \n case WM_CTLCOLORBTN:\n return (INT_PTR)hButtonBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK || LOWORD(wParam) == IDOK) {\n char input[256] = {0};\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, input, sizeof(input));\n \n // Parse input time format and convert to seconds array\n char *token, *saveptr;\n char input_copy[256];\n StringCbCopyA(input_copy, sizeof(input_copy), input);\n \n int times[MAX_POMODORO_TIMES] = {0};\n int times_count = 0;\n \n token = strtok_r(input_copy, \" \", &saveptr);\n while (token && times_count < MAX_POMODORO_TIMES) {\n int seconds = 0;\n if (ParseTimeInput(token, &seconds)) {\n times[times_count++] = seconds;\n }\n token = strtok_r(NULL, \" \", &saveptr);\n }\n \n if (times_count > 0) {\n // Update global variables\n POMODORO_TIMES_COUNT = times_count;\n for (int i = 0; i < times_count; i++) {\n POMODORO_TIMES[i] = times[i];\n }\n \n // Update basic pomodoro times\n if (times_count > 0) POMODORO_WORK_TIME = times[0];\n if (times_count > 1) POMODORO_SHORT_BREAK = times[1];\n if (times_count > 2) POMODORO_LONG_BREAK = times[2];\n \n // Write to configuration file\n WriteConfigPomodoroTimeOptions(times, times_count);\n }\n \n EndDialog(hwndDlg, IDOK);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndPomodoroComboDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original edit control procedure\n {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n SetWindowLongPtr(hwndEdit, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n \n // Release resources\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hEditBrush) {\n DeleteObject(hEditBrush);\n hEditBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n }\n break;\n }\n \n return FALSE;\n}\n\nvoid ShowPomodoroComboDialog(HWND hwndParent) {\n if (!g_hwndPomodoroComboDialog) {\n g_hwndPomodoroComboDialog = CreateDialog(\n GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_POMODORO_COMBO_DIALOG),\n hwndParent,\n PomodoroComboDialogProc\n );\n if (g_hwndPomodoroComboDialog) {\n ShowWindow(g_hwndPomodoroComboDialog, SW_SHOW);\n }\n } else {\n SetForegroundWindow(g_hwndPomodoroComboDialog);\n }\n}\n\nBOOL ParseTimeInput(const char* input, int* seconds) {\n if (!input || !seconds) return FALSE;\n\n *seconds = 0;\n char* buffer = _strdup(input);\n if (!buffer) return FALSE;\n\n int len = strlen(buffer);\n char* pos = buffer;\n int value = 0;\n int tempSeconds = 0;\n\n while (*pos) {\n if (isdigit((unsigned char)*pos)) {\n value = 0;\n while (isdigit((unsigned char)*pos)) {\n value = value * 10 + (*pos - '0');\n pos++;\n }\n\n if (*pos == 'h' || *pos == 'H') {\n tempSeconds += value * 3600;\n pos++;\n } else if (*pos == 'm' || *pos == 'M') {\n tempSeconds += value * 60;\n pos++;\n } else if (*pos == 's' || *pos == 'S') {\n tempSeconds += value;\n pos++;\n } else if (*pos == '\\0') {\n tempSeconds += value * 60;\n } else {\n free(buffer);\n return FALSE;\n }\n } else {\n pos++;\n }\n }\n\n free(buffer);\n *seconds = tempSeconds;\n return TRUE;\n}\n\nstatic HWND g_hwndNotificationMessagesDialog = NULL;\n\nINT_PTR CALLBACK NotificationMessagesDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n\n ReadNotificationMessagesConfig();\n \n // For handling UTF-8 Chinese characters, we need to convert to Unicode\n wchar_t wideText[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT)];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL1, \n GetLocalizedString(L\"Countdown timeout message:\", L\"Countdown timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL2, \n GetLocalizedString(L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_LABEL3,\n GetLocalizedString(L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"));\n \n // Localize button text\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"OK\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"Cancel\", L\"Cancel\"));\n \n // Subclass edit boxes to support Ctrl+A for select all\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n // Save original window procedure\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Apply the same subclassing process to other edit boxes\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Select all text in the first edit box\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_EDIT1, EM_SETSEL, 0, -1);\n \n // Set focus to the first edit box\n SetFocus(GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1));\n \n return FALSE; // Return FALSE because we manually set focus\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n // Get text from edit boxes (Unicode method)\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Save to configuration file and update global variables\n WriteConfigNotificationMessages(timeout_msg, pomodoro_msg, cycle_complete_msg);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationMessagesDialog = NULL;\n return TRUE;\n }\n break;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEdit1 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT1);\n HWND hEdit2 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT2);\n HWND hEdit3 = GetDlgItem(hwndDlg, IDC_NOTIFICATION_EDIT3);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEdit1, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit2, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEdit3, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification message settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification message settings dialog for modifying various notification prompt texts.\n */\nvoid ShowNotificationMessagesDialog(HWND hwndParent) {\n if (!g_hwndNotificationMessagesDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationMessagesConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_MESSAGES_DIALOG), \n hwndParent, \n NotificationMessagesDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationMessagesDialog);\n }\n}\n\n// Add global variable to track notification display settings dialog handle\nstatic HWND g_hwndNotificationDisplayDialog = NULL;\n\n// Add notification display settings dialog procedure\nINT_PTR CALLBACK NotificationDisplayDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hEditBrush = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Set window to topmost\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n \n // Create brushes\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hEditBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));\n \n // Read latest configuration\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n // Set current values to edit boxes\n char buffer[32];\n \n // Display time (seconds, support decimal) - convert milliseconds to seconds\n StringCbPrintfA(buffer, sizeof(buffer), \"%.1f\", (float)NOTIFICATION_TIMEOUT_MS / 1000.0f);\n // Remove trailing .0\n if (strlen(buffer) > 2 && buffer[strlen(buffer)-2] == '.' && buffer[strlen(buffer)-1] == '0') {\n buffer[strlen(buffer)-2] = '\\0';\n }\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, buffer);\n \n // Opacity (percentage)\n StringCbPrintfA(buffer, sizeof(buffer), \"%d\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, buffer);\n \n // Localize label text\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_LABEL, \n GetLocalizedString(L\"Notification display time (sec):\", L\"Notification display time (sec):\"));\n \n // Modify edit box style, remove ES_NUMBER to allow decimal point\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n LONG style = GetWindowLong(hEditTime, GWL_STYLE);\n SetWindowLong(hEditTime, GWL_STYLE, style & ~ES_NUMBER);\n \n // Subclass edit boxes to support Enter key submission and input restrictions\n wpOrigEditProc = (WNDPROC)SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);\n \n // Set focus to time edit box\n SetFocus(hEditTime);\n \n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLORSTATIC:\n SetBkColor((HDC)wParam, RGB(0xF3, 0xF3, 0xF3));\n return (INT_PTR)hBackgroundBrush;\n \n case WM_CTLCOLOREDIT:\n SetBkColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF));\n return (INT_PTR)hEditBrush;\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n char timeStr[32] = {0};\n char opacityStr[32] = {0};\n \n // Get user input values\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, timeStr, sizeof(timeStr));\n GetDlgItemTextA(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT, opacityStr, sizeof(opacityStr));\n \n // Use more robust method to replace Chinese period\n // First get the text in Unicode format\n wchar_t wTimeStr[32] = {0};\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, wTimeStr, sizeof(wTimeStr)/sizeof(wchar_t));\n \n // Replace Chinese punctuation marks in Unicode text\n for (int i = 0; wTimeStr[i] != L'\\0'; i++) {\n // Recognize various punctuation marks as decimal point\n if (wTimeStr[i] == L'。' || // Chinese period\n wTimeStr[i] == L',' || // Chinese comma\n wTimeStr[i] == L',' || // English comma\n wTimeStr[i] == L'·' || // Chinese middle dot\n wTimeStr[i] == L'`' || // Backtick\n wTimeStr[i] == L':' || // Chinese colon\n wTimeStr[i] == L':' || // English colon\n wTimeStr[i] == L';' || // Chinese semicolon\n wTimeStr[i] == L';' || // English semicolon\n wTimeStr[i] == L'/' || // Forward slash\n wTimeStr[i] == L'\\\\' || // Backslash\n wTimeStr[i] == L'~' || // Tilde\n wTimeStr[i] == L'~' || // Full-width tilde\n wTimeStr[i] == L'、' || // Chinese enumeration comma\n wTimeStr[i] == L'.') { // Full-width period\n wTimeStr[i] = L'.'; // Replace with English decimal point\n }\n }\n \n // Convert processed Unicode text back to ASCII\n WideCharToMultiByte(CP_ACP, 0, wTimeStr, -1, \n timeStr, sizeof(timeStr), NULL, NULL);\n \n // Parse time (seconds) and convert to milliseconds\n float timeInSeconds = atof(timeStr);\n int timeInMs = (int)(timeInSeconds * 1000.0f);\n \n // Allow time to be set to 0 (no notification) or at least 100 milliseconds\n if (timeInMs > 0 && timeInMs < 100) timeInMs = 100;\n \n // Parse opacity\n int opacity = atoi(opacityStr);\n \n // Ensure opacity is in range 1-100\n if (opacity < 1) opacity = 1;\n if (opacity > 100) opacity = 100;\n \n // Write to configuration\n WriteConfigNotificationTimeout(timeInMs);\n WriteConfigNotificationOpacity(opacity);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n }\n break;\n \n // Add handling for WM_CLOSE message\n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationDisplayDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Restore original window procedure\n {\n HWND hEditTime = GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT);\n HWND hEditOpacity = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n \n if (wpOrigEditProc) {\n SetWindowLongPtr(hEditTime, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n SetWindowLongPtr(hEditOpacity, GWLP_WNDPROC, (LONG_PTR)wpOrigEditProc);\n }\n \n if (hBackgroundBrush) DeleteObject(hBackgroundBrush);\n if (hEditBrush) DeleteObject(hEditBrush);\n }\n break;\n }\n \n return FALSE;\n}\n\n/**\n * @brief Display notification display settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays the notification display settings dialog for modifying notification display time and opacity.\n */\nvoid ShowNotificationDisplayDialog(HWND hwndParent) {\n if (!g_hwndNotificationDisplayDialog) {\n // Ensure latest configuration values are read first\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_DISPLAY_DIALOG), \n hwndParent, \n NotificationDisplayDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationDisplayDialog);\n }\n}\n\n// Add global variable to track the integrated notification settings dialog handle\nstatic HWND g_hwndNotificationSettingsDialog = NULL;\n\n/**\n * @brief Audio playback completion callback function\n * @param hwnd Window handle\n * \n * When audio playback completes, changes \"Stop\" button back to \"Test\" button\n */\nstatic void OnAudioPlaybackComplete(HWND hwnd) {\n if (hwnd && IsWindow(hwnd)) {\n const wchar_t* testText = GetLocalizedString(L\"Test\", L\"Test\");\n SetDlgItemTextW(hwnd, IDC_TEST_SOUND_BUTTON, testText);\n \n // Get dialog data\n HWND hwndTestButton = GetDlgItem(hwnd, IDC_TEST_SOUND_BUTTON);\n \n // Send WM_SETTEXT message to update button text\n if (hwndTestButton && IsWindow(hwndTestButton)) {\n SendMessageW(hwndTestButton, WM_SETTEXT, 0, (LPARAM)testText);\n }\n \n // Update global playback state\n if (g_hwndNotificationSettingsDialog == hwnd) {\n // Send message to dialog to notify state change\n SendMessage(hwnd, WM_APP + 100, 0, 0);\n }\n }\n}\n\n/**\n * @brief Populate audio dropdown box\n * @param hwndDlg Dialog handle\n */\nstatic void PopulateSoundComboBox(HWND hwndDlg) {\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n if (!hwndCombo) return;\n\n // Clear dropdown list\n SendMessage(hwndCombo, CB_RESETCONTENT, 0, 0);\n\n // Add \"None\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"None\", L\"None\"));\n \n // Add \"System Beep\" option\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)GetLocalizedString(L\"System Beep\", L\"System Beep\"));\n\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to wide character path\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n\n // Build search path\n wchar_t wSearchPath[MAX_PATH];\n StringCbPrintfW(wSearchPath, sizeof(wSearchPath), L\"%s\\\\*.*\", wAudioPath);\n\n // Find audio files - using Unicode version of API\n WIN32_FIND_DATAW find_data;\n HANDLE hFind = FindFirstFileW(wSearchPath, &find_data);\n if (hFind != INVALID_HANDLE_VALUE) {\n do {\n // Check file extension\n wchar_t* ext = wcsrchr(find_data.cFileName, L'.');\n if (ext && (\n _wcsicmp(ext, L\".flac\") == 0 ||\n _wcsicmp(ext, L\".mp3\") == 0 ||\n _wcsicmp(ext, L\".wav\") == 0\n )) {\n // Add Unicode filename directly to dropdown\n SendMessageW(hwndCombo, CB_ADDSTRING, 0, (LPARAM)find_data.cFileName);\n }\n } while (FindNextFileW(hFind, &find_data));\n FindClose(hFind);\n }\n\n // Set currently selected audio file\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n // Check if it's the special system beep marker\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n // Select \"System Beep\" option (index 1)\n SendMessage(hwndCombo, CB_SETCURSEL, 1, 0);\n } else {\n wchar_t wSoundFile[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, NOTIFICATION_SOUND_FILE, -1, wSoundFile, MAX_PATH);\n \n // Get filename part\n wchar_t* fileName = wcsrchr(wSoundFile, L'\\\\');\n if (fileName) fileName++;\n else fileName = wSoundFile;\n \n // Find and select the file in dropdown\n int index = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)fileName);\n if (index != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, index, 0);\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n }\n } else {\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0); // Select \"None\"\n }\n}\n\n/**\n * @brief Integrated notification settings dialog procedure\n * @param hwndDlg Dialog handle\n * @param msg Message type\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return INT_PTR Message processing result\n * \n * Integrates notification content and notification display settings in a unified interface\n */\nINT_PTR CALLBACK NotificationSettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static BOOL isPlaying = FALSE; // Add a static variable to track playback status\n static int originalVolume = 0; // Add a static variable to store original volume\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Read latest configuration to global variables\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n // Save original volume value for restoration when canceling\n originalVolume = NOTIFICATION_SOUND_VOLUME;\n \n // Apply multilingual support\n ApplyDialogLanguage(hwndDlg, CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG);\n \n // Set notification message text - using Unicode functions\n wchar_t wideText[256];\n \n // First edit box - Countdown timeout message\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wideText);\n \n // Second edit box - Pomodoro timeout message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_TIMEOUT_MESSAGE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wideText);\n \n // Third edit box - Pomodoro cycle completion message\n MultiByteToWideChar(CP_UTF8, 0, POMODORO_CYCLE_COMPLETE_TEXT, -1, \n wideText, sizeof(wideText)/sizeof(wchar_t));\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wideText);\n \n // Set notification display time\n SYSTEMTIME st = {0};\n GetLocalTime(&st);\n \n // Read notification disabled setting\n ReadNotificationDisabledConfig();\n \n // Set checkbox based on disabled state\n CheckDlgButton(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK, NOTIFICATION_DISABLED ? BST_CHECKED : BST_UNCHECKED);\n \n // Enable/disable time control based on state\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !NOTIFICATION_DISABLED);\n \n // Set time control value - display actual configured time regardless of disabled state\n int totalSeconds = NOTIFICATION_TIMEOUT_MS / 1000;\n st.wHour = totalSeconds / 3600;\n st.wMinute = (totalSeconds % 3600) / 60;\n st.wSecond = totalSeconds % 60;\n \n // Set time control's initial value\n SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_SETSYSTEMTIME, \n GDT_VALID, (LPARAM)&st);\n\n // Set notification opacity slider\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n SendMessage(hwndOpacitySlider, TBM_SETRANGE, TRUE, MAKELONG(1, 100));\n SendMessage(hwndOpacitySlider, TBM_SETPOS, TRUE, NOTIFICATION_MAX_OPACITY);\n \n // Update opacity text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", NOTIFICATION_MAX_OPACITY);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n // Set notification type radio buttons\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_OS:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_OS, BST_CHECKED);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n CheckDlgButton(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, BST_CHECKED);\n break;\n }\n \n // Populate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Set volume slider\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n SendMessage(hwndSlider, TBM_SETRANGE, TRUE, MAKELONG(0, 100));\n SendMessage(hwndSlider, TBM_SETPOS, TRUE, NOTIFICATION_SOUND_VOLUME);\n \n // Update volume text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", NOTIFICATION_SOUND_VOLUME);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Reset playback state on initialization\n isPlaying = FALSE;\n \n // Set audio playback completion callback\n SetAudioPlaybackCompleteCallback(hwndDlg, OnAudioPlaybackComplete);\n \n // Save dialog handle\n g_hwndNotificationSettingsDialog = hwndDlg;\n \n return TRUE;\n }\n \n case WM_HSCROLL: {\n // Handle slider drag events\n if (GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER) == (HWND)lParam) {\n // Get slider's current position\n int volume = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update volume percentage text\n wchar_t volumeText[16];\n StringCbPrintfW(volumeText, sizeof(volumeText), L\"%d%%\", volume);\n SetDlgItemTextW(hwndDlg, IDC_VOLUME_TEXT, volumeText);\n \n // Apply volume setting in real-time\n SetAudioVolume(volume);\n \n return TRUE;\n }\n else if (GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT) == (HWND)lParam) {\n // Get slider's current position\n int opacity = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0);\n \n // Update opacity percentage text\n wchar_t opacityText[16];\n StringCbPrintfW(opacityText, sizeof(opacityText), L\"%d%%\", opacity);\n SetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_OPACITY_TEXT, opacityText);\n \n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND:\n // Handle notification disable checkbox state change\n if (LOWORD(wParam) == IDC_DISABLE_NOTIFICATION_CHECK && HIWORD(wParam) == BN_CLICKED) {\n BOOL isChecked = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n EnableWindow(GetDlgItem(hwndDlg, IDC_NOTIFICATION_TIME_EDIT), !isChecked);\n return TRUE;\n }\n else if (LOWORD(wParam) == IDOK) {\n // Get notification message text - using Unicode functions\n wchar_t wTimeout[256] = {0};\n wchar_t wPomodoro[256] = {0};\n wchar_t wCycle[256] = {0};\n \n // Get Unicode text\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT1, wTimeout, sizeof(wTimeout)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT2, wPomodoro, sizeof(wPomodoro)/sizeof(wchar_t));\n GetDlgItemTextW(hwndDlg, IDC_NOTIFICATION_EDIT3, wCycle, sizeof(wCycle)/sizeof(wchar_t));\n \n // Convert to UTF-8\n char timeout_msg[256] = {0};\n char pomodoro_msg[256] = {0};\n char cycle_complete_msg[256] = {0};\n \n WideCharToMultiByte(CP_UTF8, 0, wTimeout, -1, \n timeout_msg, sizeof(timeout_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wPomodoro, -1, \n pomodoro_msg, sizeof(pomodoro_msg), NULL, NULL);\n WideCharToMultiByte(CP_UTF8, 0, wCycle, -1, \n cycle_complete_msg, sizeof(cycle_complete_msg), NULL, NULL);\n \n // Get notification display time\n SYSTEMTIME st = {0};\n \n // Check if notification disable checkbox is checked\n BOOL isDisabled = (IsDlgButtonChecked(hwndDlg, IDC_DISABLE_NOTIFICATION_CHECK) == BST_CHECKED);\n \n // Save disabled state\n NOTIFICATION_DISABLED = isDisabled;\n WriteConfigNotificationDisabled(isDisabled);\n \n // Get notification time settings\n // Get notification time settings\n if (SendDlgItemMessage(hwndDlg, IDC_NOTIFICATION_TIME_EDIT, DTM_GETSYSTEMTIME, 0, (LPARAM)&st) == GDT_VALID) {\n // Calculate total seconds: hours*3600 + minutes*60 + seconds\n int totalSeconds = st.wHour * 3600 + st.wMinute * 60 + st.wSecond;\n \n if (totalSeconds == 0) {\n // If time is 00:00:00, set to 0 (meaning disable notifications)\n NOTIFICATION_TIMEOUT_MS = 0;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n \n } else if (!isDisabled) {\n // Only update non-zero notification time if not disabled\n NOTIFICATION_TIMEOUT_MS = totalSeconds * 1000;\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n }\n }\n // If notifications are disabled, don't modify notification time configuration\n \n // Get notification opacity (from slider)\n HWND hwndOpacitySlider = GetDlgItem(hwndDlg, IDC_NOTIFICATION_OPACITY_EDIT);\n int opacity = (int)SendMessage(hwndOpacitySlider, TBM_GETPOS, 0, 0);\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n \n // Get notification type\n if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_CATIME)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_OS)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else if (IsDlgButtonChecked(hwndDlg, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL)) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n }\n \n // Get selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n if (index > 0) { // 0 is \"None\" option\n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Check if \"System Beep\" is selected\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker to represent system beep\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n } else {\n NOTIFICATION_SOUND_FILE[0] = '\\0';\n }\n \n // Get volume slider position\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n NOTIFICATION_SOUND_VOLUME = volume;\n \n // Save all settings\n WriteConfigNotificationMessages(\n timeout_msg,\n pomodoro_msg,\n cycle_complete_msg\n );\n WriteConfigNotificationTimeout(NOTIFICATION_TIMEOUT_MS);\n WriteConfigNotificationOpacity(NOTIFICATION_MAX_OPACITY);\n WriteConfigNotificationType(NOTIFICATION_TYPE);\n WriteConfigNotificationSound(NOTIFICATION_SOUND_FILE);\n WriteConfigNotificationVolume(NOTIFICATION_SOUND_VOLUME);\n \n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDOK);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDCANCEL) {\n // Ensure any playing audio is stopped\n if (isPlaying) {\n StopNotificationSound();\n isPlaying = FALSE;\n }\n \n // Restore original volume setting\n NOTIFICATION_SOUND_VOLUME = originalVolume;\n \n // Reapply original volume\n SetAudioVolume(originalVolume);\n \n // Clean up callback before closing dialog\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n } else if (LOWORD(wParam) == IDC_TEST_SOUND_BUTTON) {\n if (!isPlaying) {\n // Currently not playing, start playback and change button text to \"Stop\"\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int index = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n \n if (index > 0) { // 0 is the \"None\" option\n // Get current slider volume and apply it\n HWND hwndSlider = GetDlgItem(hwndDlg, IDC_VOLUME_SLIDER);\n int volume = (int)SendMessage(hwndSlider, TBM_GETPOS, 0, 0);\n SetAudioVolume(volume);\n \n wchar_t wFileName[MAX_PATH];\n SendMessageW(hwndCombo, CB_GETLBTEXT, index, (LPARAM)wFileName);\n \n // Temporarily save current audio settings\n char tempSoundFile[MAX_PATH];\n StringCbCopyA(tempSoundFile, sizeof(tempSoundFile), NOTIFICATION_SOUND_FILE);\n \n // Temporarily set audio file\n const wchar_t* sysBeepText = GetLocalizedString(L\"System Beep\", L\"System Beep\");\n if (wcscmp(wFileName, sysBeepText) == 0) {\n // Use special marker\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), \"SYSTEM_BEEP\");\n } else {\n // Get audio folder path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Convert to UTF-8 path\n char fileName[MAX_PATH];\n WideCharToMultiByte(CP_UTF8, 0, wFileName, -1, fileName, MAX_PATH, NULL, NULL);\n \n // Build complete file path\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n StringCbPrintfA(NOTIFICATION_SOUND_FILE, MAX_PATH, \"%s\\\\%s\", audio_path, fileName);\n }\n \n // Play audio\n if (PlayNotificationSound(hwndDlg)) {\n // Playback successful, change button text to \"Stop\"\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Stop\", L\"Stop\"));\n isPlaying = TRUE;\n }\n \n // Restore previous settings\n StringCbCopyA(NOTIFICATION_SOUND_FILE, sizeof(NOTIFICATION_SOUND_FILE), tempSoundFile);\n }\n } else {\n // Currently playing, stop playback and restore button text\n StopNotificationSound();\n SetDlgItemTextW(hwndDlg, IDC_TEST_SOUND_BUTTON, GetLocalizedString(L\"Test\", L\"Test\"));\n isPlaying = FALSE;\n }\n return TRUE;\n } else if (LOWORD(wParam) == IDC_OPEN_SOUND_DIR_BUTTON) {\n // Get audio directory path\n char audio_path[MAX_PATH];\n GetAudioFolderPath(audio_path, MAX_PATH);\n \n // Ensure directory exists\n wchar_t wAudioPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, audio_path, -1, wAudioPath, MAX_PATH);\n \n // Open directory\n ShellExecuteW(hwndDlg, L\"open\", wAudioPath, NULL, NULL, SW_SHOWNORMAL);\n \n // Record currently selected audio file\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate audio dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Try to restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n } else {\n // If previous selection not found, default to \"None\"\n SendMessage(hwndCombo, CB_SETCURSEL, 0, 0);\n }\n }\n \n return TRUE;\n } else if (LOWORD(wParam) == IDC_NOTIFICATION_SOUND_COMBO && HIWORD(wParam) == CBN_DROPDOWN) {\n // When dropdown is about to open, reload file list\n HWND hwndCombo = GetDlgItem(hwndDlg, IDC_NOTIFICATION_SOUND_COMBO);\n \n // Record currently selected file\n int selectedIndex = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);\n wchar_t selectedFile[MAX_PATH] = {0};\n if (selectedIndex > 0) {\n SendMessageW(hwndCombo, CB_GETLBTEXT, selectedIndex, (LPARAM)selectedFile);\n }\n \n // Repopulate dropdown\n PopulateSoundComboBox(hwndDlg);\n \n // Restore previous selection\n if (selectedFile[0] != L'\\0') {\n int newIndex = SendMessageW(hwndCombo, CB_FINDSTRINGEXACT, -1, (LPARAM)selectedFile);\n if (newIndex != CB_ERR) {\n SendMessage(hwndCombo, CB_SETCURSEL, newIndex, 0);\n }\n }\n \n return TRUE;\n }\n break;\n \n // Add custom message handling for audio playback completion notification\n case WM_APP + 100:\n // Audio playback is complete, update button state\n isPlaying = FALSE;\n return TRUE;\n \n case WM_CLOSE:\n // Make sure to stop playback when closing dialog\n if (isPlaying) {\n StopNotificationSound();\n }\n \n // Clean up callback\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n \n EndDialog(hwndDlg, IDCANCEL);\n g_hwndNotificationSettingsDialog = NULL;\n return TRUE;\n \n case WM_DESTROY:\n // Clean up callback when dialog is destroyed\n SetAudioPlaybackCompleteCallback(NULL, NULL);\n g_hwndNotificationSettingsDialog = NULL;\n break;\n }\n return FALSE;\n}\n\n/**\n * @brief Display integrated notification settings dialog\n * @param hwndParent Parent window handle\n * \n * Displays a unified dialog that includes both notification content and display settings\n */\nvoid ShowNotificationSettingsDialog(HWND hwndParent) {\n if (!g_hwndNotificationSettingsDialog) {\n // Ensure the latest configuration values are read first\n ReadNotificationMessagesConfig();\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationTypeConfig();\n ReadNotificationSoundConfig();\n ReadNotificationVolumeConfig();\n \n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG), \n hwndParent, \n NotificationSettingsDlgProc);\n } else {\n SetForegroundWindow(g_hwndNotificationSettingsDialog);\n }\n}"], ["/Catime/src/config.c", "/**\n * @file config.c\n * @brief Configuration file management module implementation\n */\n\n#include \"../include/config.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define MAX_POMODORO_TIMES 10\n\nextern int POMODORO_WORK_TIME;\nextern int POMODORO_SHORT_BREAK;\nextern int POMODORO_LONG_BREAK;\nextern int POMODORO_LOOP_COUNT;\n\nint POMODORO_TIMES[MAX_POMODORO_TIMES] = {1500, 300, 1500, 600};\nint POMODORO_TIMES_COUNT = 4;\n\nchar CLOCK_TIMEOUT_MESSAGE_TEXT[100] = \"时间到啦!\";\nchar POMODORO_TIMEOUT_MESSAGE_TEXT[100] = \"番茄钟时间到!\";\nchar POMODORO_CYCLE_COMPLETE_TEXT[100] = \"所有番茄钟循环完成!\";\n\nint NOTIFICATION_TIMEOUT_MS = 3000;\nint NOTIFICATION_MAX_OPACITY = 95;\nNotificationType NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\nBOOL NOTIFICATION_DISABLED = FALSE;\n\nchar NOTIFICATION_SOUND_FILE[MAX_PATH] = \"\";\nint NOTIFICATION_SOUND_VOLUME = 100;\n\n/** @brief Read string value from INI file */\nDWORD ReadIniString(const char* section, const char* key, const char* defaultValue,\n char* returnValue, DWORD returnSize, const char* filePath) {\n return GetPrivateProfileStringA(section, key, defaultValue, returnValue, returnSize, filePath);\n}\n\n/** @brief Write string value to INI file */\nBOOL WriteIniString(const char* section, const char* key, const char* value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value, filePath);\n}\n\n/** @brief Read integer value from INI */\nint ReadIniInt(const char* section, const char* key, int defaultValue, \n const char* filePath) {\n return GetPrivateProfileIntA(section, key, defaultValue, filePath);\n}\n\n/** @brief Write integer value to INI file */\nBOOL WriteIniInt(const char* section, const char* key, int value,\n const char* filePath) {\n char valueStr[32];\n snprintf(valueStr, sizeof(valueStr), \"%d\", value);\n return WritePrivateProfileStringA(section, key, valueStr, filePath);\n}\n\n/** @brief Write boolean value to INI file */\nBOOL WriteIniBool(const char* section, const char* key, BOOL value,\n const char* filePath) {\n return WritePrivateProfileStringA(section, key, value ? \"TRUE\" : \"FALSE\", filePath);\n}\n\n/** @brief Read boolean value from INI */\nBOOL ReadIniBool(const char* section, const char* key, BOOL defaultValue, \n const char* filePath) {\n char value[8];\n GetPrivateProfileStringA(section, key, defaultValue ? \"TRUE\" : \"FALSE\", \n value, sizeof(value), filePath);\n return _stricmp(value, \"TRUE\") == 0;\n}\n\n/** @brief Check if configuration file exists */\nBOOL FileExists(const char* filePath) {\n return GetFileAttributesA(filePath) != INVALID_FILE_ATTRIBUTES;\n}\n\n/** @brief Get configuration file path */\nvoid GetConfigPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\config.ini\", appdata_path) >= size) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\asset\\\\config.ini\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Create default configuration file */\nvoid CreateDefaultConfig(const char* config_path) {\n // Get system default language ID\n LANGID systemLangID = GetUserDefaultUILanguage();\n int defaultLanguage = APP_LANG_ENGLISH; // Default to English\n const char* langName = \"English\"; // Default language name\n \n // Set default language based on system language ID\n switch (PRIMARYLANGID(systemLangID)) {\n case LANG_CHINESE:\n if (SUBLANGID(systemLangID) == SUBLANG_CHINESE_SIMPLIFIED) {\n defaultLanguage = APP_LANG_CHINESE_SIMP;\n langName = \"Chinese_Simplified\";\n } else {\n defaultLanguage = APP_LANG_CHINESE_TRAD;\n langName = \"Chinese_Traditional\";\n }\n break;\n case LANG_SPANISH:\n defaultLanguage = APP_LANG_SPANISH;\n langName = \"Spanish\";\n break;\n case LANG_FRENCH:\n defaultLanguage = APP_LANG_FRENCH;\n langName = \"French\";\n break;\n case LANG_GERMAN:\n defaultLanguage = APP_LANG_GERMAN;\n langName = \"German\";\n break;\n case LANG_RUSSIAN:\n defaultLanguage = APP_LANG_RUSSIAN;\n langName = \"Russian\";\n break;\n case LANG_PORTUGUESE:\n defaultLanguage = APP_LANG_PORTUGUESE;\n langName = \"Portuguese\";\n break;\n case LANG_JAPANESE:\n defaultLanguage = APP_LANG_JAPANESE;\n langName = \"Japanese\";\n break;\n case LANG_KOREAN:\n defaultLanguage = APP_LANG_KOREAN;\n langName = \"Korean\";\n break;\n case LANG_ENGLISH:\n default:\n defaultLanguage = APP_LANG_ENGLISH;\n langName = \"English\";\n break;\n }\n \n // Choose default settings based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", \"TRUE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 1; i <= 5; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n config_path);\n}\n\n/** @brief Extract filename from file path */\nvoid ExtractFileName(const char* path, char* name, size_t nameSize) {\n if (!path || !name || nameSize == 0) return;\n \n // First convert to wide characters to properly handle Unicode paths\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, wPath, MAX_PATH);\n \n // Look for the last backslash or forward slash\n wchar_t* lastSlash = wcsrchr(wPath, L'\\\\');\n if (!lastSlash) lastSlash = wcsrchr(wPath, L'/');\n \n wchar_t wName[MAX_PATH] = {0};\n if (lastSlash) {\n wcscpy(wName, lastSlash + 1);\n } else {\n wcscpy(wName, wPath);\n }\n \n // Convert back to UTF-8\n WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, nameSize, NULL, NULL);\n}\n\n/** @brief Check and create resource folders */\nvoid CheckAndCreateResourceFolders() {\n char config_path[MAX_PATH];\n char base_path[MAX_PATH];\n char resource_path[MAX_PATH];\n char *last_slash;\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Copy configuration file path\n strncpy(base_path, config_path, MAX_PATH - 1);\n base_path[MAX_PATH - 1] = '\\0';\n \n // Find the last slash or backslash, which marks the beginning of the filename\n last_slash = strrchr(base_path, '\\\\');\n if (!last_slash) {\n last_slash = strrchr(base_path, '/');\n }\n \n if (last_slash) {\n // Truncate path to directory part\n *(last_slash + 1) = '\\0';\n \n // Create resources main directory\n snprintf(resource_path, MAX_PATH, \"%sresources\", base_path);\n DWORD attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create resources folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n return;\n }\n }\n \n // Create audio subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\audio\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create audio folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create images subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\images\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create images folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create animations subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\animations\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create animations folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create themes subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\themes\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create themes folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n \n // Create plug-in subdirectory\n snprintf(resource_path, MAX_PATH, \"%sresources\\\\plug-in\", base_path);\n attrs = GetFileAttributesA(resource_path);\n if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {\n if (!CreateDirectoryA(resource_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n fprintf(stderr, \"Failed to create plug-in folder: %s (Error: %lu)\\n\", resource_path, GetLastError());\n }\n }\n }\n}\n\n/** @brief Read and parse configuration file */\nvoid ReadConfig() {\n // Check and create resource folders\n CheckAndCreateResourceFolders();\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Check if configuration file exists, create default configuration if it doesn't\n if (!FileExists(config_path)) {\n CreateDefaultConfig(config_path);\n }\n \n // Check configuration file version\n char version[32] = {0};\n BOOL versionMatched = FALSE;\n \n // Read current version information\n ReadIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", \"\", version, sizeof(version), config_path);\n \n // Compare if version matches\n if (strcmp(version, CATIME_VERSION) == 0) {\n versionMatched = TRUE;\n }\n \n // If version doesn't match, recreate the configuration file\n if (!versionMatched) {\n CreateDefaultConfig(config_path);\n }\n\n // Reset time options\n time_options_count = 0;\n memset(time_options, 0, sizeof(time_options));\n \n // Reset recent files count\n CLOCK_RECENT_FILES_COUNT = 0;\n \n // Read basic settings\n // ======== [General] Section ========\n char language[32] = {0};\n ReadIniString(INI_SECTION_GENERAL, \"LANGUAGE\", \"English\", language, sizeof(language), config_path);\n \n // Convert language name to enum value\n int languageSetting = APP_LANG_ENGLISH; // Default to English\n \n if (strcmp(language, \"Chinese_Simplified\") == 0) {\n languageSetting = APP_LANG_CHINESE_SIMP;\n } else if (strcmp(language, \"Chinese_Traditional\") == 0) {\n languageSetting = APP_LANG_CHINESE_TRAD;\n } else if (strcmp(language, \"English\") == 0) {\n languageSetting = APP_LANG_ENGLISH;\n } else if (strcmp(language, \"Spanish\") == 0) {\n languageSetting = APP_LANG_SPANISH;\n } else if (strcmp(language, \"French\") == 0) {\n languageSetting = APP_LANG_FRENCH;\n } else if (strcmp(language, \"German\") == 0) {\n languageSetting = APP_LANG_GERMAN;\n } else if (strcmp(language, \"Russian\") == 0) {\n languageSetting = APP_LANG_RUSSIAN;\n } else if (strcmp(language, \"Portuguese\") == 0) {\n languageSetting = APP_LANG_PORTUGUESE;\n } else if (strcmp(language, \"Japanese\") == 0) {\n languageSetting = APP_LANG_JAPANESE;\n } else if (strcmp(language, \"Korean\") == 0) {\n languageSetting = APP_LANG_KOREAN;\n } else {\n // Try to parse as number (for backward compatibility)\n int langValue = atoi(language);\n if (langValue >= 0 && langValue < APP_LANG_COUNT) {\n languageSetting = langValue;\n } else {\n languageSetting = APP_LANG_ENGLISH; // Default to English\n }\n }\n \n // ======== [Display] Section ========\n ReadIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", \"#FFB6C1\", CLOCK_TEXT_COLOR, sizeof(CLOCK_TEXT_COLOR), config_path);\n CLOCK_BASE_FONT_SIZE = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", 20, config_path);\n ReadIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", \"Wallpoet Essence.ttf\", FONT_FILE_NAME, sizeof(FONT_FILE_NAME), config_path);\n \n // Extract internal name from font filename\n size_t font_name_len = strlen(FONT_FILE_NAME);\n if (font_name_len > 4 && strcmp(FONT_FILE_NAME + font_name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = font_name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n CLOCK_WINDOW_POS_X = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", 960, config_path);\n CLOCK_WINDOW_POS_Y = ReadIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", -1, config_path);\n \n char scaleStr[16] = {0};\n ReadIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", \"1.62\", scaleStr, sizeof(scaleStr), config_path);\n CLOCK_WINDOW_SCALE = atof(scaleStr);\n \n CLOCK_WINDOW_TOPMOST = ReadIniBool(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", TRUE, config_path);\n \n // Check and replace pure black color\n if (strcasecmp(CLOCK_TEXT_COLOR, \"#000000\") == 0) {\n strncpy(CLOCK_TEXT_COLOR, \"#000001\", sizeof(CLOCK_TEXT_COLOR) - 1);\n }\n \n // ======== [Timer] Section ========\n CLOCK_DEFAULT_START_TIME = ReadIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", 1500, config_path);\n CLOCK_USE_24HOUR = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", FALSE, config_path);\n CLOCK_SHOW_SECONDS = ReadIniBool(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", FALSE, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", \"0\", CLOCK_TIMEOUT_TEXT, sizeof(CLOCK_TIMEOUT_TEXT), config_path);\n \n // Read timeout action\n char timeoutAction[32] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", \"MESSAGE\", timeoutAction, sizeof(timeoutAction), config_path);\n \n if (strcmp(timeoutAction, \"MESSAGE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"LOCK\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_LOCK;\n } else if (strcmp(timeoutAction, \"SHUTDOWN\") == 0) {\n // Even if SHUTDOWN exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"RESTART\") == 0) {\n // Even if RESTART exists in the config file, treat it as a one-time operation, default to MESSAGE\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE;\n } else if (strcmp(timeoutAction, \"OPEN_FILE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n } else if (strcmp(timeoutAction, \"SHOW_TIME\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SHOW_TIME;\n } else if (strcmp(timeoutAction, \"COUNT_UP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_COUNT_UP;\n } else if (strcmp(timeoutAction, \"OPEN_WEBSITE\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n } else if (strcmp(timeoutAction, \"SLEEP\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_SLEEP;\n } else if (strcmp(timeoutAction, \"RUN_COMMAND\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_RUN_COMMAND;\n } else if (strcmp(timeoutAction, \"HTTP_REQUEST\") == 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_HTTP_REQUEST;\n }\n \n // Read timeout file and website settings\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", \"\", CLOCK_TIMEOUT_FILE_PATH, MAX_PATH, config_path);\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", \"\", CLOCK_TIMEOUT_WEBSITE_URL, MAX_PATH, config_path);\n \n // If file path is valid, ensure timeout action is set to open file\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n GetFileAttributesA(CLOCK_TIMEOUT_FILE_PATH) != INVALID_FILE_ATTRIBUTES) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n }\n \n // If URL is valid, ensure timeout action is set to open website\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n }\n \n // Read time options\n char timeOptions[256] = {0};\n ReadIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", \"25,10,5\", timeOptions, sizeof(timeOptions), config_path);\n \n char *token = strtok(timeOptions, \",\");\n while (token && time_options_count < MAX_TIME_OPTIONS) {\n while (*token == ' ') token++;\n time_options[time_options_count++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Read startup mode\n ReadIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", \"COUNTDOWN\", CLOCK_STARTUP_MODE, sizeof(CLOCK_STARTUP_MODE), config_path);\n \n // ======== [Pomodoro] Section ========\n char pomodoroTimeOptions[256] = {0};\n ReadIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", \"1500,300,1500,600\", pomodoroTimeOptions, sizeof(pomodoroTimeOptions), config_path);\n \n // Reset pomodoro time count\n POMODORO_TIMES_COUNT = 0;\n \n // Parse all pomodoro time values\n token = strtok(pomodoroTimeOptions, \",\");\n while (token && POMODORO_TIMES_COUNT < MAX_POMODORO_TIMES) {\n POMODORO_TIMES[POMODORO_TIMES_COUNT++] = atoi(token);\n token = strtok(NULL, \",\");\n }\n \n // Even though we now use a new array to store all times,\n // keep these three variables for backward compatibility\n if (POMODORO_TIMES_COUNT > 0) {\n POMODORO_WORK_TIME = POMODORO_TIMES[0];\n if (POMODORO_TIMES_COUNT > 1) POMODORO_SHORT_BREAK = POMODORO_TIMES[1];\n if (POMODORO_TIMES_COUNT > 2) POMODORO_LONG_BREAK = POMODORO_TIMES[3]; // Note this is the 4th value\n }\n \n // Read pomodoro loop count\n POMODORO_LOOP_COUNT = ReadIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", 1, config_path);\n if (POMODORO_LOOP_COUNT < 1) POMODORO_LOOP_COUNT = 1;\n \n // ======== [Notification] Section ========\n ReadIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", \"时间到啦!\", \n CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", \"番茄钟时间到!\", \n POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT), config_path);\n \n ReadIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", \"所有番茄钟循环完成!\", \n POMODORO_CYCLE_COMPLETE_TEXT, sizeof(POMODORO_CYCLE_COMPLETE_TEXT), config_path);\n \n NOTIFICATION_TIMEOUT_MS = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", 3000, config_path);\n NOTIFICATION_MAX_OPACITY = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", 95, config_path);\n \n // Ensure opacity is within valid range (1-100)\n if (NOTIFICATION_MAX_OPACITY < 1) NOTIFICATION_MAX_OPACITY = 1;\n if (NOTIFICATION_MAX_OPACITY > 100) NOTIFICATION_MAX_OPACITY = 100;\n \n char notificationType[32] = {0};\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", \"CATIME\", notificationType, sizeof(notificationType), config_path);\n \n // Set notification type\n if (strcmp(notificationType, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(notificationType, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(notificationType, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Read notification audio file path\n ReadIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", \"\", \n NOTIFICATION_SOUND_FILE, MAX_PATH, config_path);\n \n // Read notification audio volume\n NOTIFICATION_SOUND_VOLUME = ReadIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", 100, config_path);\n \n // Read whether to disable notification window\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n \n // Ensure volume is within valid range (0-100)\n if (NOTIFICATION_SOUND_VOLUME < 0) NOTIFICATION_SOUND_VOLUME = 0;\n if (NOTIFICATION_SOUND_VOLUME > 100) NOTIFICATION_SOUND_VOLUME = 100;\n \n // ======== [Colors] Section ========\n char colorOptions[1024] = {0};\n ReadIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", \n \"#FFFFFF,#F9DB91,#F4CAE0,#FFB6C1,#A8E7DF,#A3CFB3,#92CBFC,#BDA5E7,#9370DB,#8C92CF,#72A9A5,#EB99A7,#EB96BD,#FFAE8B,#FF7F50,#CA6174\", \n colorOptions, sizeof(colorOptions), config_path);\n \n // Parse color options\n token = strtok(colorOptions, \",\");\n COLOR_OPTIONS_COUNT = 0;\n while (token) {\n COLOR_OPTIONS = realloc(COLOR_OPTIONS, sizeof(PredefinedColor) * (COLOR_OPTIONS_COUNT + 1));\n if (COLOR_OPTIONS) {\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = strdup(token);\n COLOR_OPTIONS_COUNT++;\n }\n token = strtok(NULL, \",\");\n }\n \n // ======== [RecentFiles] Section ========\n // Read recent file records\n for (int i = 1; i <= MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i);\n \n char filePath[MAX_PATH] = {0};\n ReadIniString(INI_SECTION_RECENTFILES, key, \"\", filePath, MAX_PATH, config_path);\n \n if (strlen(filePath) > 0) {\n // Convert to wide characters to properly check if the file exists\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, widePath, MAX_PATH);\n \n // Check if file exists\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n ExtractFileName(filePath, CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, MAX_PATH);\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n \n // ======== [Hotkeys] Section ========\n // Read hotkey configurations from INI file\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n // Read hotkey settings\n char hotkeyStr[32] = {0};\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n showTimeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countUpHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n countdownHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown1Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown2Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n quickCountdown3Hotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pomodoroHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n toggleVisibilityHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n editModeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n pauseResumeHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n restartTimerHotkey = StringToHotkey(hotkeyStr);\n \n ReadIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", \"None\", hotkeyStr, sizeof(hotkeyStr), config_path);\n customCountdownHotkey = StringToHotkey(hotkeyStr);\n \n last_config_time = time(NULL);\n\n // Apply window position\n HWND hwnd = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwnd) {\n SetWindowPos(hwnd, NULL, CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n\n // Apply language settings\n SetLanguage((AppLanguage)languageSetting);\n}\n\n/** @brief Write timeout action configuration */\nvoid WriteConfigTimeoutAction(const char* action) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n // For shutdown or restart actions, don't write them to the config file, write \"MESSAGE\" instead\n const char* actual_action = action;\n if (strcmp(action, \"RESTART\") == 0 || strcmp(action, \"SHUTDOWN\") == 0 || strcmp(action, \"SLEEP\") == 0) {\n actual_action = \"MESSAGE\";\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=%s\\n\", actual_action);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write time options configuration */\nvoid WriteConfigTimeOptions(const char* options) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIME_OPTIONS=\", 19) == 0) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"CLOCK_TIME_OPTIONS=%s\\n\", options);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Load recently used file records */\nvoid LoadRecentFiles(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) return;\n\n char line[MAX_PATH];\n CLOCK_RECENT_FILES_COUNT = 0;\n\n while (fgets(line, sizeof(line), file)) {\n // Support for the CLOCK_RECENT_FILE_N=path format\n if (strncmp(line, \"CLOCK_RECENT_FILE_\", 18) == 0) {\n char *path = strchr(line + 18, '=');\n if (path) {\n path++; // Skip the equals sign\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n // Also update the old format for compatibility\n else if (strncmp(line, \"CLOCK_RECENT_FILE=\", 18) == 0) {\n char *path = line + 18;\n char *newline = strchr(path, '\\n');\n if (newline) *newline = '\\0';\n\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n // Convert to wide characters for proper file existence check\n wchar_t widePath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, MAX_PATH);\n \n // Check if file exists using wide character function\n if (GetFileAttributesW(widePath) != INVALID_FILE_ATTRIBUTES) {\n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, path, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path[MAX_PATH - 1] = '\\0';\n\n char *filename = strrchr(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path, '\\\\');\n if (filename) filename++;\n else filename = CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].path;\n \n strncpy(CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name, filename, MAX_PATH - 1);\n CLOCK_RECENT_FILES[CLOCK_RECENT_FILES_COUNT].name[MAX_PATH - 1] = '\\0';\n\n CLOCK_RECENT_FILES_COUNT++;\n }\n }\n }\n }\n\n fclose(file);\n}\n\n/** @brief Save recently used file record */\nvoid SaveRecentFile(const char* filePath) {\n // Check if the file path is valid\n if (!filePath || strlen(filePath) == 0) return;\n \n // Convert to wide characters to check if the file exists\n wchar_t wPath[MAX_PATH] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wPath, MAX_PATH);\n \n if (GetFileAttributesW(wPath) == INVALID_FILE_ATTRIBUTES) {\n // File doesn't exist, don't add it\n return;\n }\n \n // Check if the file is already in the list\n int existingIndex = -1;\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n if (strcmp(CLOCK_RECENT_FILES[i].path, filePath) == 0) {\n existingIndex = i;\n break;\n }\n }\n \n if (existingIndex == 0) {\n // File is already at the top of the list, no action needed\n return;\n }\n \n if (existingIndex > 0) {\n // File is in the list, but not at the top, need to move it\n RecentFile temp = CLOCK_RECENT_FILES[existingIndex];\n \n // Move elements backward\n for (int i = existingIndex; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Put it at the first position\n CLOCK_RECENT_FILES[0] = temp;\n } else {\n // File is not in the list, need to add it\n // First ensure the list doesn't exceed 5 items\n if (CLOCK_RECENT_FILES_COUNT < MAX_RECENT_FILES) {\n CLOCK_RECENT_FILES_COUNT++;\n }\n \n // Move elements backward\n for (int i = CLOCK_RECENT_FILES_COUNT - 1; i > 0; i--) {\n CLOCK_RECENT_FILES[i] = CLOCK_RECENT_FILES[i - 1];\n }\n \n // Add new file to the first position\n strncpy(CLOCK_RECENT_FILES[0].path, filePath, MAX_PATH - 1);\n CLOCK_RECENT_FILES[0].path[MAX_PATH - 1] = '\\0';\n \n // Extract filename\n ExtractFileName(filePath, CLOCK_RECENT_FILES[0].name, MAX_PATH);\n }\n \n // Update configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n WriteConfig(configPath);\n}\n\n/** @brief Convert UTF8 to ANSI encoding */\nchar* UTF8ToANSI(const char* utf8Str) {\n int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, NULL, 0);\n if (wlen == 0) {\n return _strdup(utf8Str);\n }\n\n wchar_t* wstr = (wchar_t*)malloc(sizeof(wchar_t) * wlen);\n if (!wstr) {\n return _strdup(utf8Str);\n }\n\n if (MultiByteToWideChar(CP_UTF8, 0, utf8Str, -1, wstr, wlen) == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n int len = WideCharToMultiByte(936, 0, wstr, -1, NULL, 0, NULL, NULL);\n if (len == 0) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n char* str = (char*)malloc(len);\n if (!str) {\n free(wstr);\n return _strdup(utf8Str);\n }\n\n if (WideCharToMultiByte(936, 0, wstr, -1, str, len, NULL, NULL) == 0) {\n free(wstr);\n free(str);\n return _strdup(utf8Str);\n }\n\n free(wstr);\n return str;\n}\n\n/** @brief Write pomodoro time settings */\nvoid WriteConfigPomodoroTimes(int work, int short_break, int long_break) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n // Update global variables\n // Maintain backward compatibility, while updating the POMODORO_TIMES array\n POMODORO_WORK_TIME = work;\n POMODORO_SHORT_BREAK = short_break;\n POMODORO_LONG_BREAK = long_break;\n \n // Ensure at least these three time values exist\n POMODORO_TIMES[0] = work;\n if (POMODORO_TIMES_COUNT < 1) POMODORO_TIMES_COUNT = 1;\n \n if (POMODORO_TIMES_COUNT > 1) {\n POMODORO_TIMES[1] = short_break;\n } else if (short_break > 0) {\n POMODORO_TIMES[1] = short_break;\n POMODORO_TIMES_COUNT = 2;\n }\n \n if (POMODORO_TIMES_COUNT > 2) {\n POMODORO_TIMES[2] = long_break;\n } else if (long_break > 0) {\n POMODORO_TIMES[2] = long_break;\n POMODORO_TIMES_COUNT = 3;\n }\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n // Look for POMODORO_TIME_OPTIONS line\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write all pomodoro times\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If POMODORO_TIME_OPTIONS was not found, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n if (i > 0) fprintf(temp_file, \",\");\n fprintf(temp_file, \"%d\", POMODORO_TIMES[i]);\n }\n fprintf(temp_file, \"\\n\");\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro loop count configuration */\nvoid WriteConfigPomodoroLoopCount(int loop_count) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_LOOP_COUNT=\", 20) == 0) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n // If the key was not found in the configuration file, add it\n if (!found) {\n fprintf(temp_file, \"POMODORO_LOOP_COUNT=%d\\n\", loop_count);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n POMODORO_LOOP_COUNT = loop_count;\n}\n\n/** @brief Write window topmost status configuration */\nvoid WriteConfigTopmost(const char* topmost) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"WINDOW_TOPMOST=\", 15) == 0) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"WINDOW_TOPMOST=%s\\n\", topmost);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write timeout open file path */\nvoid WriteConfigTimeoutFile(const char* filePath) {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_FILE;\n strncpy(CLOCK_TIMEOUT_FILE_PATH, filePath, MAX_PATH - 1);\n CLOCK_TIMEOUT_FILE_PATH[MAX_PATH - 1] = '\\0';\n \n // Use WriteConfig to completely rewrite the configuration file, maintaining structural consistency\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n WriteConfig(config_path);\n}\n\n/** @brief Write all configuration settings to file */\nvoid WriteConfig(const char* config_path) {\n // Get the name of the current language\n AppLanguage currentLang = GetCurrentLanguage();\n const char* langName;\n \n switch (currentLang) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n case APP_LANG_ENGLISH:\n default:\n langName = \"English\";\n break;\n }\n \n // Choose string representation based on notification type\n const char* typeStr;\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Read hotkey settings\n WORD showTimeHotkey = 0;\n WORD countUpHotkey = 0;\n WORD countdownHotkey = 0;\n WORD quickCountdown1Hotkey = 0;\n WORD quickCountdown2Hotkey = 0;\n WORD quickCountdown3Hotkey = 0;\n WORD pomodoroHotkey = 0;\n WORD toggleVisibilityHotkey = 0;\n WORD editModeHotkey = 0;\n WORD pauseResumeHotkey = 0;\n WORD restartTimerHotkey = 0;\n WORD customCountdownHotkey = 0;\n \n ReadConfigHotkeys(&showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey);\n \n ReadCustomCountdownHotkey(&customCountdownHotkey);\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0};\n \n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Prepare time options string\n char timeOptionsStr[256] = {0};\n for (int i = 0; i < time_options_count; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", time_options[i]);\n \n if (i > 0) {\n strcat(timeOptionsStr, \",\");\n }\n strcat(timeOptionsStr, buffer);\n }\n \n // Prepare pomodoro time options string\n char pomodoroTimesStr[256] = {0};\n for (int i = 0; i < POMODORO_TIMES_COUNT; i++) {\n char buffer[16];\n snprintf(buffer, sizeof(buffer), \"%d\", POMODORO_TIMES[i]);\n \n if (i > 0) {\n strcat(pomodoroTimesStr, \",\");\n }\n strcat(pomodoroTimesStr, buffer);\n }\n \n // Prepare color options string\n char colorOptionsStr[1024] = {0};\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (i > 0) {\n strcat(colorOptionsStr, \",\");\n }\n strcat(colorOptionsStr, COLOR_OPTIONS[i].hexColor);\n }\n \n // Determine timeout action string\n const char* timeoutActionStr;\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_LOCK:\n timeoutActionStr = \"LOCK\";\n break;\n case TIMEOUT_ACTION_SHUTDOWN:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RESTART:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_OPEN_FILE:\n timeoutActionStr = \"OPEN_FILE\";\n break;\n case TIMEOUT_ACTION_SHOW_TIME:\n timeoutActionStr = \"SHOW_TIME\";\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n timeoutActionStr = \"COUNT_UP\";\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n timeoutActionStr = \"OPEN_WEBSITE\";\n break;\n case TIMEOUT_ACTION_SLEEP:\n // Don't save one-time operations, revert to MESSAGE\n timeoutActionStr = \"MESSAGE\";\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n timeoutActionStr = \"RUN_COMMAND\";\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n timeoutActionStr = \"HTTP_REQUEST\";\n break;\n default:\n timeoutActionStr = \"MESSAGE\";\n }\n \n // ======== [General] Section ========\n WriteIniString(INI_SECTION_GENERAL, \"CONFIG_VERSION\", CATIME_VERSION, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"LANGUAGE\", langName, config_path);\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", IsShortcutCheckDone() ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Display] Section ========\n WriteIniString(INI_SECTION_DISPLAY, \"CLOCK_TEXT_COLOR\", CLOCK_TEXT_COLOR, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_BASE_FONT_SIZE\", CLOCK_BASE_FONT_SIZE, config_path);\n WriteIniString(INI_SECTION_DISPLAY, \"FONT_FILE_NAME\", FONT_FILE_NAME, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_X\", CLOCK_WINDOW_POS_X, config_path);\n WriteIniInt(INI_SECTION_DISPLAY, \"CLOCK_WINDOW_POS_Y\", CLOCK_WINDOW_POS_Y, config_path);\n \n char scaleStr[16];\n snprintf(scaleStr, sizeof(scaleStr), \"%.2f\", CLOCK_WINDOW_SCALE);\n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_SCALE\", scaleStr, config_path);\n \n WriteIniString(INI_SECTION_DISPLAY, \"WINDOW_TOPMOST\", CLOCK_WINDOW_TOPMOST ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Timer] Section ========\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", CLOCK_DEFAULT_START_TIME, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_USE_24HOUR\", CLOCK_USE_24HOUR ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_SHOW_SECONDS\", CLOCK_SHOW_SECONDS ? \"TRUE\" : \"FALSE\", config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_TEXT\", CLOCK_TIMEOUT_TEXT, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_ACTION\", timeoutActionStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_FILE\", CLOCK_TIMEOUT_FILE_PATH, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIMEOUT_WEBSITE\", CLOCK_TIMEOUT_WEBSITE_URL, config_path);\n WriteIniString(INI_SECTION_TIMER, \"CLOCK_TIME_OPTIONS\", timeOptionsStr, config_path);\n WriteIniString(INI_SECTION_TIMER, \"STARTUP_MODE\", CLOCK_STARTUP_MODE, config_path);\n \n // ======== [Pomodoro] Section ========\n WriteIniString(INI_SECTION_POMODORO, \"POMODORO_TIME_OPTIONS\", pomodoroTimesStr, config_path);\n WriteIniInt(INI_SECTION_POMODORO, \"POMODORO_LOOP_COUNT\", POMODORO_LOOP_COUNT, config_path);\n \n // ======== [Notification] Section ========\n WriteIniString(INI_SECTION_NOTIFICATION, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", CLOCK_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_TIMEOUT_MESSAGE_TEXT\", POMODORO_TIMEOUT_MESSAGE_TEXT, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"POMODORO_CYCLE_COMPLETE_TEXT\", POMODORO_CYCLE_COMPLETE_TEXT, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TIMEOUT_MS\", NOTIFICATION_TIMEOUT_MS, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_MAX_OPACITY\", NOTIFICATION_MAX_OPACITY, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_TYPE\", typeStr, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_FILE\", NOTIFICATION_SOUND_FILE, config_path);\n WriteIniInt(INI_SECTION_NOTIFICATION, \"NOTIFICATION_SOUND_VOLUME\", NOTIFICATION_SOUND_VOLUME, config_path);\n WriteIniString(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", NOTIFICATION_DISABLED ? \"TRUE\" : \"FALSE\", config_path);\n \n // ======== [Hotkeys] Section ========\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_SHOW_TIME\", showTimeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNT_UP\", countUpStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_COUNTDOWN\", countdownStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN1\", quickCountdown1Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN2\", quickCountdown2Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_QUICK_COUNTDOWN3\", quickCountdown3Str, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_POMODORO\", pomodoroStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_TOGGLE_VISIBILITY\", toggleVisibilityStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_EDIT_MODE\", editModeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_PAUSE_RESUME\", pauseResumeStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_RESTART_TIMER\", restartTimerStr, config_path);\n WriteIniString(INI_SECTION_HOTKEYS, \"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr, config_path);\n \n // ======== [RecentFiles] Section ========\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, CLOCK_RECENT_FILES[i].path, config_path);\n }\n \n // Clear unused file records\n for (int i = CLOCK_RECENT_FILES_COUNT; i < MAX_RECENT_FILES; i++) {\n char key[32];\n snprintf(key, sizeof(key), \"CLOCK_RECENT_FILE_%d\", i + 1);\n WriteIniString(INI_SECTION_RECENTFILES, key, \"\", config_path);\n }\n \n // ======== [Colors] Section ========\n WriteIniString(INI_SECTION_COLORS, \"COLOR_OPTIONS\", colorOptionsStr, config_path);\n}\n\n/** @brief Write timeout open website URL */\nvoid WriteConfigTimeoutWebsite(const char* url) {\n // Only set timeout action to open website if a valid URL is provided\n if (url && url[0] != '\\0') {\n // First update global variables\n CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_OPEN_WEBSITE;\n strncpy(CLOCK_TIMEOUT_WEBSITE_URL, url, MAX_PATH - 1);\n CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH - 1] = '\\0';\n \n // Then update the configuration file\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL actionFound = FALSE;\n BOOL urlFound = FALSE;\n \n // Read original configuration file, update timeout action and URL\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"CLOCK_TIMEOUT_ACTION=\", 21) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n actionFound = TRUE;\n } else if (strncmp(line, \"CLOCK_TIMEOUT_WEBSITE=\", 22) == 0) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n urlFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If these items are not in the configuration, add them\n if (!actionFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_ACTION=OPEN_WEBSITE\\n\");\n }\n if (!urlFound) {\n fprintf(temp, \"CLOCK_TIMEOUT_WEBSITE=%s\\n\", url);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n }\n}\n\n/** @brief Write startup mode configuration */\nvoid WriteConfigStartupMode(const char* mode) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *file, *temp_file;\n char line[256];\n int found = 0;\n \n file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!file || !temp_file) {\n if (file) fclose(file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n // Update global variable\n strncpy(CLOCK_STARTUP_MODE, mode, sizeof(CLOCK_STARTUP_MODE) - 1);\n CLOCK_STARTUP_MODE[sizeof(CLOCK_STARTUP_MODE) - 1] = '\\0';\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n found = 1;\n } else {\n fputs(line, temp_file);\n }\n }\n \n if (!found) {\n fprintf(temp_file, \"STARTUP_MODE=%s\\n\", mode);\n }\n \n fclose(file);\n fclose(temp_file);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write pomodoro time options */\nvoid WriteConfigPomodoroTimeOptions(int* times, int count) {\n if (!times || count <= 0) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[MAX_PATH];\n BOOL optionsFound = FALSE;\n \n // Read original configuration file, update pomodoro time options\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"POMODORO_TIME_OPTIONS=\", 22) == 0) {\n // Write new time options\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n optionsFound = TRUE;\n } else {\n // Preserve all other configurations\n fputs(line, temp);\n }\n }\n \n // If this item is not in the configuration, add it\n if (!optionsFound) {\n fprintf(temp, \"POMODORO_TIME_OPTIONS=\");\n for (int i = 0; i < count; i++) {\n fprintf(temp, \"%d\", times[i]);\n if (i < count - 1) fprintf(temp, \",\");\n }\n fprintf(temp, \"\\n\");\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Write notification message configuration */\nvoid WriteConfigNotificationMessages(const char* timeout_msg, const char* pomodoro_msg, const char* cycle_complete_msg) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n // Use standard C file operations instead of Windows API\n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL timeoutFound = FALSE;\n BOOL pomodoroFound = FALSE;\n BOOL cycleFound = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n timeoutFound = TRUE;\n } else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n pomodoroFound = TRUE;\n } else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n cycleFound = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If corresponding items are not found in the configuration, add them\n if (!timeoutFound) {\n fprintf(temp_file, \"CLOCK_TIMEOUT_MESSAGE_TEXT=%s\\n\", timeout_msg);\n }\n \n if (!pomodoroFound) {\n fprintf(temp_file, \"POMODORO_TIMEOUT_MESSAGE_TEXT=%s\\n\", pomodoro_msg);\n }\n \n if (!cycleFound) {\n fprintf(temp_file, \"POMODORO_CYCLE_COMPLETE_TEXT=%s\\n\", cycle_complete_msg);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variables\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, timeout_msg, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, pomodoro_msg, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n \n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, cycle_complete_msg, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n}\n\n/** @brief Read notification message text from configuration file */\nvoid ReadNotificationMessagesConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current values in memory or default values\n return;\n }\n\n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[1024];\n BOOL timeoutMsgFound = FALSE;\n BOOL pomodoroTimeoutMsgFound = FALSE;\n BOOL cycleCompleteMsgFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n // Process this line\n if (strncmp(line, \"CLOCK_TIMEOUT_MESSAGE_TEXT=\", 27) == 0) {\n strncpy(CLOCK_TIMEOUT_MESSAGE_TEXT, line + 27, sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1);\n CLOCK_TIMEOUT_MESSAGE_TEXT[sizeof(CLOCK_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n timeoutMsgFound = TRUE;\n } \n else if (strncmp(line, \"POMODORO_TIMEOUT_MESSAGE_TEXT=\", 30) == 0) {\n strncpy(POMODORO_TIMEOUT_MESSAGE_TEXT, line + 30, sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1);\n POMODORO_TIMEOUT_MESSAGE_TEXT[sizeof(POMODORO_TIMEOUT_MESSAGE_TEXT) - 1] = '\\0';\n pomodoroTimeoutMsgFound = TRUE;\n }\n else if (strncmp(line, \"POMODORO_CYCLE_COMPLETE_TEXT=\", 29) == 0) {\n strncpy(POMODORO_CYCLE_COMPLETE_TEXT, line + 29, sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1);\n POMODORO_CYCLE_COMPLETE_TEXT[sizeof(POMODORO_CYCLE_COMPLETE_TEXT) - 1] = '\\0';\n cycleCompleteMsgFound = TRUE;\n }\n \n // If all messages have been found, can exit loop early\n if (timeoutMsgFound && pomodoroTimeoutMsgFound && cycleCompleteMsgFound) {\n break;\n }\n }\n \n CloseHandle(hFile);\n \n // If corresponding configuration items are not found in the file, ensure variables have default values\n if (!timeoutMsgFound) {\n strcpy(CLOCK_TIMEOUT_MESSAGE_TEXT, \"时间到啦!\"); // Default value\n }\n if (!pomodoroTimeoutMsgFound) {\n strcpy(POMODORO_TIMEOUT_MESSAGE_TEXT, \"番茄钟时间到!\"); // Default value\n }\n if (!cycleCompleteMsgFound) {\n strcpy(POMODORO_CYCLE_COMPLETE_TEXT, \"所有番茄钟循环完成!\"); // Default value\n }\n}\n\n/** @brief Read notification display time from configuration file */\nvoid ReadNotificationTimeoutConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL timeoutFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n int timeout = atoi(line + 24);\n if (timeout > 0) {\n NOTIFICATION_TIMEOUT_MS = timeout;\n }\n timeoutFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!timeoutFound) {\n NOTIFICATION_TIMEOUT_MS = 3000; // Ensure there's a default value\n }\n}\n\n/** @brief Write notification display time configuration */\nvoid WriteConfigNotificationTimeout(int timeout_ms) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_TIMEOUT_MS=\", 24) == 0) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_TIMEOUT_MS=%d\\n\", timeout_ms);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_TIMEOUT_MS = timeout_ms;\n}\n\n/** @brief Read maximum notification opacity from configuration file */\nvoid ReadNotificationOpacityConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n HANDLE hFile = CreateFileA(\n config_path,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n );\n \n if (hFile == INVALID_HANDLE_VALUE) {\n // File cannot be opened, keep current default value\n return;\n }\n \n // Skip UTF-8 BOM marker (if present)\n char bom[3];\n DWORD bytesRead;\n ReadFile(hFile, bom, 3, &bytesRead, NULL);\n \n if (bytesRead != 3 || bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF) {\n // Not a BOM, need to rewind file pointer\n SetFilePointer(hFile, 0, NULL, FILE_BEGIN);\n }\n \n char line[256];\n BOOL opacityFound = FALSE;\n \n // Read file content line by line\n BOOL readingLine = TRUE;\n int pos = 0;\n \n while (readingLine) {\n // Read byte by byte, build line\n bytesRead = 0;\n pos = 0;\n memset(line, 0, sizeof(line));\n \n while (TRUE) {\n char ch;\n ReadFile(hFile, &ch, 1, &bytesRead, NULL);\n \n if (bytesRead == 0) { // End of file\n readingLine = FALSE;\n break;\n }\n \n if (ch == '\\n') { // End of line\n break;\n }\n \n if (ch != '\\r') { // Ignore carriage return\n line[pos++] = ch;\n if (pos >= sizeof(line) - 1) break; // Prevent buffer overflow\n }\n }\n \n line[pos] = '\\0'; // Ensure string termination\n \n // If no content and file has ended, exit loop\n if (pos == 0 && !readingLine) {\n break;\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n int opacity = atoi(line + 25);\n // Ensure opacity is within valid range (1-100)\n if (opacity >= 1 && opacity <= 100) {\n NOTIFICATION_MAX_OPACITY = opacity;\n }\n opacityFound = TRUE;\n break; // Found what we're looking for, can exit the loop\n }\n }\n \n CloseHandle(hFile);\n \n // If not found in configuration, keep default value\n if (!opacityFound) {\n NOTIFICATION_MAX_OPACITY = 95; // Ensure there's a default value\n }\n}\n\n/** @brief Write maximum notification opacity configuration */\nvoid WriteConfigNotificationOpacity(int opacity) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read file content line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_MAX_OPACITY=\", 25) == 0) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If not found in configuration, add new line\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_MAX_OPACITY=%d\\n\", opacity);\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_MAX_OPACITY = opacity;\n}\n\n/** @brief Read notification type setting from configuration file */\nvoid ReadNotificationTypeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *file = fopen(config_path, \"r\");\n if (file) {\n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n char typeStr[32] = {0};\n sscanf(line + 18, \"%31s\", typeStr);\n \n // Set notification type based on the string\n if (strcmp(typeStr, \"CATIME\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n } else if (strcmp(typeStr, \"SYSTEM_MODAL\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_SYSTEM_MODAL;\n } else if (strcmp(typeStr, \"OS\") == 0) {\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_OS;\n } else {\n // Use default value for invalid type\n NOTIFICATION_TYPE = NOTIFICATION_TYPE_CATIME;\n }\n break;\n }\n }\n fclose(file);\n }\n}\n\n/** @brief Write notification type configuration */\nvoid WriteConfigNotificationType(NotificationType type) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Ensure type value is within valid range\n if (type < NOTIFICATION_TYPE_CATIME || type > NOTIFICATION_TYPE_OS) {\n type = NOTIFICATION_TYPE_CATIME; // Default value\n }\n \n // Update global variable\n NOTIFICATION_TYPE = type;\n \n // Convert enum to string\n const char* typeStr;\n switch (type) {\n case NOTIFICATION_TYPE_CATIME:\n typeStr = \"CATIME\";\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n typeStr = \"SYSTEM_MODAL\";\n break;\n case NOTIFICATION_TYPE_OS:\n typeStr = \"OS\";\n break;\n default:\n typeStr = \"CATIME\"; // Default value\n break;\n }\n \n // Create temporary file path\n char temp_path[MAX_PATH];\n strncpy(temp_path, config_path, MAX_PATH - 5);\n strcat(temp_path, \".tmp\");\n \n FILE *source = fopen(config_path, \"r\");\n FILE *target = fopen(temp_path, \"w\");\n \n if (source && target) {\n char line[256];\n BOOL found = FALSE;\n \n // Copy file content, replace target configuration line\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_TYPE=\", 18) == 0) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n found = TRUE;\n } else {\n fputs(line, target);\n }\n }\n \n // If configuration item not found, add it to the end of file\n if (!found) {\n fprintf(target, \"NOTIFICATION_TYPE=%s\\n\", typeStr);\n }\n \n fclose(source);\n fclose(target);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n } else {\n // Clean up potentially open files\n if (source) fclose(source);\n if (target) fclose(target);\n }\n}\n\n/** @brief Get audio folder path */\nvoid GetAudioFolderPath(char* path, size_t size) {\n if (!path || size == 0) return;\n\n char* appdata_path = getenv(\"LOCALAPPDATA\");\n if (appdata_path) {\n if (snprintf(path, size, \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) >= size) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n return;\n }\n \n char dir_path[MAX_PATH];\n if (snprintf(dir_path, sizeof(dir_path), \"%s\\\\Catime\\\\resources\\\\audio\", appdata_path) < sizeof(dir_path)) {\n if (!CreateDirectoryA(dir_path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n }\n } else {\n strncpy(path, \".\\\\resources\\\\audio\", size - 1);\n path[size - 1] = '\\0';\n }\n}\n\n/** @brief Read notification audio settings from configuration file */\nvoid ReadNotificationSoundConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[1024];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n char* value = line + 23; // Correct offset, skip \"NOTIFICATION_SOUND_FILE=\"\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Ensure path doesn't contain equals sign\n if (value[0] == '=') {\n value++; // If first character is equals sign, skip it\n }\n \n // Copy to global variable, ensure cleared\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, value, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio configuration */\nvoid WriteConfigNotificationSound(const char* sound_file) {\n if (!sound_file) return;\n \n // Check if the path contains equals sign, remove if present\n char clean_path[MAX_PATH] = {0};\n const char* src = sound_file;\n char* dst = clean_path;\n \n while (*src && (dst - clean_path) < (MAX_PATH - 1)) {\n if (*src != '=') {\n *dst++ = *src;\n }\n src++;\n }\n *dst = '\\0';\n \n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Create temporary file path\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE* source = fopen(config_path, \"r\");\n if (!source) return;\n \n FILE* dest = fopen(temp_path, \"w\");\n if (!dest) {\n fclose(source);\n return;\n }\n \n char line[1024];\n int found = 0;\n \n // Copy file content, replace or add notification audio settings\n while (fgets(line, sizeof(line), source)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_FILE=\", 23) == 0) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n found = 1;\n } else {\n fputs(line, dest);\n }\n }\n \n // If configuration item not found, add to end of file\n if (!found) {\n fprintf(dest, \"NOTIFICATION_SOUND_FILE=%s\\n\", clean_path);\n }\n \n fclose(source);\n fclose(dest);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n memset(NOTIFICATION_SOUND_FILE, 0, MAX_PATH);\n strncpy(NOTIFICATION_SOUND_FILE, clean_path, MAX_PATH - 1);\n NOTIFICATION_SOUND_FILE[MAX_PATH - 1] = '\\0';\n}\n\n/** @brief Read notification audio volume from configuration file */\nvoid ReadNotificationVolumeConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n int volume = atoi(line + 26);\n if (volume >= 0 && volume <= 100) {\n NOTIFICATION_SOUND_VOLUME = volume;\n }\n break;\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write notification audio volume configuration */\nvoid WriteConfigNotificationVolume(int volume) {\n // Validate volume range\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n \n // Update global variable\n NOTIFICATION_SOUND_VOLUME = volume;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char temp_path[MAX_PATH];\n strcpy(temp_path, config_path);\n strcat(temp_path, \".tmp\");\n \n FILE* temp = fopen(temp_path, \"w\");\n if (!temp) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL found = FALSE;\n \n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"NOTIFICATION_SOUND_VOLUME=\", 26) == 0) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n found = TRUE;\n } else {\n fputs(line, temp);\n }\n }\n \n if (!found) {\n fprintf(temp, \"NOTIFICATION_SOUND_VOLUME=%d\\n\", volume);\n }\n \n fclose(file);\n fclose(temp);\n \n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Read hotkey settings from configuration file */\nvoid ReadConfigHotkeys(WORD* showTimeHotkey, WORD* countUpHotkey, WORD* countdownHotkey,\n WORD* quickCountdown1Hotkey, WORD* quickCountdown2Hotkey, WORD* quickCountdown3Hotkey,\n WORD* pomodoroHotkey, WORD* toggleVisibilityHotkey, WORD* editModeHotkey,\n WORD* pauseResumeHotkey, WORD* restartTimerHotkey)\n{\n // Parameter validation\n if (!showTimeHotkey || !countUpHotkey || !countdownHotkey || \n !quickCountdown1Hotkey || !quickCountdown2Hotkey || !quickCountdown3Hotkey ||\n !pomodoroHotkey || !toggleVisibilityHotkey || !editModeHotkey || \n !pauseResumeHotkey || !restartTimerHotkey) return;\n \n // Initialize to 0 (indicates no hotkey set)\n *showTimeHotkey = 0;\n *countUpHotkey = 0;\n *countdownHotkey = 0;\n *quickCountdown1Hotkey = 0;\n *quickCountdown2Hotkey = 0;\n *quickCountdown3Hotkey = 0;\n *pomodoroHotkey = 0;\n *toggleVisibilityHotkey = 0;\n *editModeHotkey = 0;\n *pauseResumeHotkey = 0;\n *restartTimerHotkey = 0;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *showTimeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countUpHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *countdownHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown1Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown2Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n char* value = line + 24;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *quickCountdown3Hotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n char* value = line + 16;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pomodoroHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n char* value = line + 25;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *toggleVisibilityHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n char* value = line + 17;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *editModeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n char* value = line + 20;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *pauseResumeHotkey = StringToHotkey(value);\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n char* value = line + 21;\n // Remove trailing newline\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // Parse hotkey string\n *restartTimerHotkey = StringToHotkey(value);\n }\n }\n \n fclose(file);\n}\n\n/** @brief Write hotkey configuration */\nvoid WriteConfigHotkeys(WORD showTimeHotkey, WORD countUpHotkey, WORD countdownHotkey,\n WORD quickCountdown1Hotkey, WORD quickCountdown2Hotkey, WORD quickCountdown3Hotkey,\n WORD pomodoroHotkey, WORD toggleVisibilityHotkey, WORD editModeHotkey,\n WORD pauseResumeHotkey, WORD restartTimerHotkey) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) {\n // If file doesn't exist, create new file\n file = fopen(config_path, \"w\");\n if (!file) return;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n char customCountdownStr[64] = {0}; // Add custom countdown hotkey\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n // Get custom countdown hotkey value\n WORD customCountdownHotkey = 0;\n ReadCustomCountdownHotkey(&customCountdownHotkey);\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n \n // Write hotkey configuration\n fprintf(file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n fprintf(file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n fprintf(file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n fprintf(file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n fprintf(file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n fprintf(file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n fprintf(file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n fprintf(file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n fprintf(file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n fprintf(file, \"HOTKEY_CUSTOM_COUNTDOWN=%s\\n\", customCountdownStr); // Add new hotkey\n \n fclose(file);\n return;\n }\n \n // File exists, read all lines and update hotkey settings\n char temp_path[MAX_PATH];\n sprintf(temp_path, \"%s.tmp\", config_path);\n FILE* temp_file = fopen(temp_path, \"w\");\n \n if (!temp_file) {\n fclose(file);\n return;\n }\n \n char line[256];\n BOOL foundShowTime = FALSE;\n BOOL foundCountUp = FALSE;\n BOOL foundCountdown = FALSE;\n BOOL foundQuickCountdown1 = FALSE;\n BOOL foundQuickCountdown2 = FALSE;\n BOOL foundQuickCountdown3 = FALSE;\n BOOL foundPomodoro = FALSE;\n BOOL foundToggleVisibility = FALSE;\n BOOL foundEditMode = FALSE;\n BOOL foundPauseResume = FALSE;\n BOOL foundRestartTimer = FALSE;\n \n // Convert hotkey values to readable format\n char showTimeStr[64] = {0};\n char countUpStr[64] = {0};\n char countdownStr[64] = {0};\n char quickCountdown1Str[64] = {0};\n char quickCountdown2Str[64] = {0};\n char quickCountdown3Str[64] = {0};\n char pomodoroStr[64] = {0};\n char toggleVisibilityStr[64] = {0};\n char editModeStr[64] = {0};\n char pauseResumeStr[64] = {0};\n char restartTimerStr[64] = {0};\n \n // Convert each hotkey\n HotkeyToString(showTimeHotkey, showTimeStr, sizeof(showTimeStr));\n HotkeyToString(countUpHotkey, countUpStr, sizeof(countUpStr));\n HotkeyToString(countdownHotkey, countdownStr, sizeof(countdownStr));\n HotkeyToString(quickCountdown1Hotkey, quickCountdown1Str, sizeof(quickCountdown1Str));\n HotkeyToString(quickCountdown2Hotkey, quickCountdown2Str, sizeof(quickCountdown2Str));\n HotkeyToString(quickCountdown3Hotkey, quickCountdown3Str, sizeof(quickCountdown3Str));\n HotkeyToString(pomodoroHotkey, pomodoroStr, sizeof(pomodoroStr));\n HotkeyToString(toggleVisibilityHotkey, toggleVisibilityStr, sizeof(toggleVisibilityStr));\n HotkeyToString(editModeHotkey, editModeStr, sizeof(editModeStr));\n HotkeyToString(pauseResumeHotkey, pauseResumeStr, sizeof(pauseResumeStr));\n HotkeyToString(restartTimerHotkey, restartTimerStr, sizeof(restartTimerStr));\n \n // Process each line\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_SHOW_TIME=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n foundShowTime = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNT_UP=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n foundCountUp = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_COUNTDOWN=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n foundCountdown = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN1=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n foundQuickCountdown1 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN2=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n foundQuickCountdown2 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_QUICK_COUNTDOWN3=\", 24) == 0) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n foundQuickCountdown3 = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_POMODORO=\", 16) == 0) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n foundPomodoro = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_TOGGLE_VISIBILITY=\", 25) == 0) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n foundToggleVisibility = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_EDIT_MODE=\", 17) == 0) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n foundEditMode = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_PAUSE_RESUME=\", 20) == 0) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n foundPauseResume = TRUE;\n }\n else if (strncmp(line, \"HOTKEY_RESTART_TIMER=\", 21) == 0) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n foundRestartTimer = TRUE;\n }\n else {\n // Keep other lines\n fputs(line, temp_file);\n }\n }\n \n // Add hotkey configuration items not found\n if (!foundShowTime) {\n fprintf(temp_file, \"HOTKEY_SHOW_TIME=%s\\n\", showTimeStr);\n }\n if (!foundCountUp) {\n fprintf(temp_file, \"HOTKEY_COUNT_UP=%s\\n\", countUpStr);\n }\n if (!foundCountdown) {\n fprintf(temp_file, \"HOTKEY_COUNTDOWN=%s\\n\", countdownStr);\n }\n if (!foundQuickCountdown1) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN1=%s\\n\", quickCountdown1Str);\n }\n if (!foundQuickCountdown2) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN2=%s\\n\", quickCountdown2Str);\n }\n if (!foundQuickCountdown3) {\n fprintf(temp_file, \"HOTKEY_QUICK_COUNTDOWN3=%s\\n\", quickCountdown3Str);\n }\n if (!foundPomodoro) {\n fprintf(temp_file, \"HOTKEY_POMODORO=%s\\n\", pomodoroStr);\n }\n if (!foundToggleVisibility) {\n fprintf(temp_file, \"HOTKEY_TOGGLE_VISIBILITY=%s\\n\", toggleVisibilityStr);\n }\n if (!foundEditMode) {\n fprintf(temp_file, \"HOTKEY_EDIT_MODE=%s\\n\", editModeStr);\n }\n if (!foundPauseResume) {\n fprintf(temp_file, \"HOTKEY_PAUSE_RESUME=%s\\n\", pauseResumeStr);\n }\n if (!foundRestartTimer) {\n fprintf(temp_file, \"HOTKEY_RESTART_TIMER=%s\\n\", restartTimerStr);\n }\n \n fclose(file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n}\n\n/** @brief Convert hotkey value to readable string */\nvoid HotkeyToString(WORD hotkey, char* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) return;\n \n // 如果热键为0,表示未设置\n if (hotkey == 0) {\n strncpy(buffer, \"None\", bufferSize - 1);\n buffer[bufferSize - 1] = '\\0';\n return;\n }\n \n BYTE vk = LOBYTE(hotkey); // 虚拟键码\n BYTE mod = HIBYTE(hotkey); // 修饰键\n \n buffer[0] = '\\0';\n size_t len = 0;\n \n // 添加修饰键\n if (mod & HOTKEYF_CONTROL) {\n strncpy(buffer, \"Ctrl\", bufferSize - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_SHIFT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Shift\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n if (mod & HOTKEYF_ALT) {\n if (len > 0 && len < bufferSize - 1) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n strncat(buffer, \"Alt\", bufferSize - len - 1);\n len = strlen(buffer);\n }\n \n // 添加虚拟键\n if (len > 0 && len < bufferSize - 1 && vk != 0) {\n buffer[len++] = '+';\n buffer[len] = '\\0';\n }\n \n // 获取虚拟键名称\n if (vk >= 'A' && vk <= 'Z') {\n // 字母键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= '0' && vk <= '9') {\n // 数字键\n char keyName[2] = {vk, '\\0'};\n strncat(buffer, keyName, bufferSize - len - 1);\n } else if (vk >= VK_F1 && vk <= VK_F24) {\n // 功能键\n char keyName[4];\n sprintf(keyName, \"F%d\", vk - VK_F1 + 1);\n strncat(buffer, keyName, bufferSize - len - 1);\n } else {\n // 其他特殊键\n switch (vk) {\n case VK_BACK: strncat(buffer, \"Backspace\", bufferSize - len - 1); break;\n case VK_TAB: strncat(buffer, \"Tab\", bufferSize - len - 1); break;\n case VK_RETURN: strncat(buffer, \"Enter\", bufferSize - len - 1); break;\n case VK_ESCAPE: strncat(buffer, \"Esc\", bufferSize - len - 1); break;\n case VK_SPACE: strncat(buffer, \"Space\", bufferSize - len - 1); break;\n case VK_PRIOR: strncat(buffer, \"PageUp\", bufferSize - len - 1); break;\n case VK_NEXT: strncat(buffer, \"PageDown\", bufferSize - len - 1); break;\n case VK_END: strncat(buffer, \"End\", bufferSize - len - 1); break;\n case VK_HOME: strncat(buffer, \"Home\", bufferSize - len - 1); break;\n case VK_LEFT: strncat(buffer, \"Left\", bufferSize - len - 1); break;\n case VK_UP: strncat(buffer, \"Up\", bufferSize - len - 1); break;\n case VK_RIGHT: strncat(buffer, \"Right\", bufferSize - len - 1); break;\n case VK_DOWN: strncat(buffer, \"Down\", bufferSize - len - 1); break;\n case VK_INSERT: strncat(buffer, \"Insert\", bufferSize - len - 1); break;\n case VK_DELETE: strncat(buffer, \"Delete\", bufferSize - len - 1); break;\n case VK_NUMPAD0: strncat(buffer, \"Num0\", bufferSize - len - 1); break;\n case VK_NUMPAD1: strncat(buffer, \"Num1\", bufferSize - len - 1); break;\n case VK_NUMPAD2: strncat(buffer, \"Num2\", bufferSize - len - 1); break;\n case VK_NUMPAD3: strncat(buffer, \"Num3\", bufferSize - len - 1); break;\n case VK_NUMPAD4: strncat(buffer, \"Num4\", bufferSize - len - 1); break;\n case VK_NUMPAD5: strncat(buffer, \"Num5\", bufferSize - len - 1); break;\n case VK_NUMPAD6: strncat(buffer, \"Num6\", bufferSize - len - 1); break;\n case VK_NUMPAD7: strncat(buffer, \"Num7\", bufferSize - len - 1); break;\n case VK_NUMPAD8: strncat(buffer, \"Num8\", bufferSize - len - 1); break;\n case VK_NUMPAD9: strncat(buffer, \"Num9\", bufferSize - len - 1); break;\n case VK_MULTIPLY: strncat(buffer, \"Num*\", bufferSize - len - 1); break;\n case VK_ADD: strncat(buffer, \"Num+\", bufferSize - len - 1); break;\n case VK_SUBTRACT: strncat(buffer, \"Num-\", bufferSize - len - 1); break;\n case VK_DECIMAL: strncat(buffer, \"Num.\", bufferSize - len - 1); break;\n case VK_DIVIDE: strncat(buffer, \"Num/\", bufferSize - len - 1); break;\n case VK_OEM_1: strncat(buffer, \";\", bufferSize - len - 1); break;\n case VK_OEM_PLUS: strncat(buffer, \"=\", bufferSize - len - 1); break;\n case VK_OEM_COMMA: strncat(buffer, \",\", bufferSize - len - 1); break;\n case VK_OEM_MINUS: strncat(buffer, \"-\", bufferSize - len - 1); break;\n case VK_OEM_PERIOD: strncat(buffer, \".\", bufferSize - len - 1); break;\n case VK_OEM_2: strncat(buffer, \"/\", bufferSize - len - 1); break;\n case VK_OEM_3: strncat(buffer, \"`\", bufferSize - len - 1); break;\n case VK_OEM_4: strncat(buffer, \"[\", bufferSize - len - 1); break;\n case VK_OEM_5: strncat(buffer, \"\\\\\", bufferSize - len - 1); break;\n case VK_OEM_6: strncat(buffer, \"]\", bufferSize - len - 1); break;\n case VK_OEM_7: strncat(buffer, \"'\", bufferSize - len - 1); break;\n default: \n // 对于其他未知键,使用十六进制表示\n {\n char keyName[8];\n sprintf(keyName, \"0x%02X\", vk);\n strncat(buffer, keyName, bufferSize - len - 1);\n }\n break;\n }\n }\n}\n\n/** @brief Convert string to hotkey value */\nWORD StringToHotkey(const char* str) {\n if (!str || str[0] == '\\0' || strcmp(str, \"None\") == 0) {\n return 0; // 未设置热键\n }\n \n // 尝试直接解析为数字(兼容旧格式)\n if (isdigit(str[0])) {\n return (WORD)atoi(str);\n }\n \n BYTE vk = 0; // 虚拟键码\n BYTE mod = 0; // 修饰键\n \n // 复制字符串以便使用strtok\n char buffer[256];\n strncpy(buffer, str, sizeof(buffer) - 1);\n buffer[sizeof(buffer) - 1] = '\\0';\n \n // 分割字符串,查找修饰键和主键\n char* token = strtok(buffer, \"+\");\n char* lastToken = NULL;\n \n while (token) {\n if (stricmp(token, \"Ctrl\") == 0) {\n mod |= HOTKEYF_CONTROL;\n } else if (stricmp(token, \"Shift\") == 0) {\n mod |= HOTKEYF_SHIFT;\n } else if (stricmp(token, \"Alt\") == 0) {\n mod |= HOTKEYF_ALT;\n } else {\n // 可能是主键\n lastToken = token;\n }\n token = strtok(NULL, \"+\");\n }\n \n // 解析主键\n if (lastToken) {\n // 检查是否是单个字符的字母或数字\n if (strlen(lastToken) == 1) {\n char ch = toupper(lastToken[0]);\n if ((ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) {\n vk = ch;\n }\n } \n // 检查是否是功能键\n else if (lastToken[0] == 'F' && isdigit(lastToken[1])) {\n int fNum = atoi(lastToken + 1);\n if (fNum >= 1 && fNum <= 24) {\n vk = VK_F1 + fNum - 1;\n }\n }\n // 检查特殊键名\n else if (stricmp(lastToken, \"Backspace\") == 0) vk = VK_BACK;\n else if (stricmp(lastToken, \"Tab\") == 0) vk = VK_TAB;\n else if (stricmp(lastToken, \"Enter\") == 0) vk = VK_RETURN;\n else if (stricmp(lastToken, \"Esc\") == 0) vk = VK_ESCAPE;\n else if (stricmp(lastToken, \"Space\") == 0) vk = VK_SPACE;\n else if (stricmp(lastToken, \"PageUp\") == 0) vk = VK_PRIOR;\n else if (stricmp(lastToken, \"PageDown\") == 0) vk = VK_NEXT;\n else if (stricmp(lastToken, \"End\") == 0) vk = VK_END;\n else if (stricmp(lastToken, \"Home\") == 0) vk = VK_HOME;\n else if (stricmp(lastToken, \"Left\") == 0) vk = VK_LEFT;\n else if (stricmp(lastToken, \"Up\") == 0) vk = VK_UP;\n else if (stricmp(lastToken, \"Right\") == 0) vk = VK_RIGHT;\n else if (stricmp(lastToken, \"Down\") == 0) vk = VK_DOWN;\n else if (stricmp(lastToken, \"Insert\") == 0) vk = VK_INSERT;\n else if (stricmp(lastToken, \"Delete\") == 0) vk = VK_DELETE;\n else if (stricmp(lastToken, \"Num0\") == 0) vk = VK_NUMPAD0;\n else if (stricmp(lastToken, \"Num1\") == 0) vk = VK_NUMPAD1;\n else if (stricmp(lastToken, \"Num2\") == 0) vk = VK_NUMPAD2;\n else if (stricmp(lastToken, \"Num3\") == 0) vk = VK_NUMPAD3;\n else if (stricmp(lastToken, \"Num4\") == 0) vk = VK_NUMPAD4;\n else if (stricmp(lastToken, \"Num5\") == 0) vk = VK_NUMPAD5;\n else if (stricmp(lastToken, \"Num6\") == 0) vk = VK_NUMPAD6;\n else if (stricmp(lastToken, \"Num7\") == 0) vk = VK_NUMPAD7;\n else if (stricmp(lastToken, \"Num8\") == 0) vk = VK_NUMPAD8;\n else if (stricmp(lastToken, \"Num9\") == 0) vk = VK_NUMPAD9;\n else if (stricmp(lastToken, \"Num*\") == 0) vk = VK_MULTIPLY;\n else if (stricmp(lastToken, \"Num+\") == 0) vk = VK_ADD;\n else if (stricmp(lastToken, \"Num-\") == 0) vk = VK_SUBTRACT;\n else if (stricmp(lastToken, \"Num.\") == 0) vk = VK_DECIMAL;\n else if (stricmp(lastToken, \"Num/\") == 0) vk = VK_DIVIDE;\n // 检查十六进制格式\n else if (strncmp(lastToken, \"0x\", 2) == 0) {\n vk = (BYTE)strtol(lastToken, NULL, 16);\n }\n }\n \n return MAKEWORD(vk, mod);\n}\n\n/**\n * @brief Read custom countdown hotkey setting from configuration file\n * @param hotkey Pointer to store the hotkey\n */\nvoid ReadCustomCountdownHotkey(WORD* hotkey) {\n if (!hotkey) return;\n \n *hotkey = 0; // 默认为0(未设置)\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE* file = fopen(config_path, \"r\");\n if (!file) return;\n \n char line[256];\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"HOTKEY_CUSTOM_COUNTDOWN=\", 24) == 0) {\n char* value = line + 24;\n // 去除末尾的换行符\n char* newline = strchr(value, '\\n');\n if (newline) *newline = '\\0';\n \n // 解析热键字符串\n *hotkey = StringToHotkey(value);\n break;\n }\n }\n \n fclose(file);\n}\n\n/**\n * @brief Write a single configuration item to the configuration file\n * @param key Configuration item key name\n * @param value Configuration item value\n * \n * Adds or updates a single configuration item in the configuration file, automatically selects section based on key name\n */\nvoid WriteConfigKeyValue(const char* key, const char* value) {\n if (!key || !value) return;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Determine which section to place in based on the key name\n const char* section;\n \n if (strcmp(key, \"CONFIG_VERSION\") == 0 ||\n strcmp(key, \"LANGUAGE\") == 0 ||\n strcmp(key, \"SHORTCUT_CHECK_DONE\") == 0) {\n section = INI_SECTION_GENERAL;\n }\n else if (strncmp(key, \"CLOCK_TEXT_COLOR\", 16) == 0 ||\n strncmp(key, \"FONT_FILE_NAME\", 14) == 0 ||\n strncmp(key, \"CLOCK_BASE_FONT_SIZE\", 20) == 0 ||\n strncmp(key, \"WINDOW_SCALE\", 12) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_X\", 18) == 0 ||\n strncmp(key, \"CLOCK_WINDOW_POS_Y\", 18) == 0 ||\n strncmp(key, \"WINDOW_TOPMOST\", 14) == 0) {\n section = INI_SECTION_DISPLAY;\n }\n else if (strncmp(key, \"CLOCK_DEFAULT_START_TIME\", 24) == 0 ||\n strncmp(key, \"CLOCK_USE_24HOUR\", 16) == 0 ||\n strncmp(key, \"CLOCK_SHOW_SECONDS\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIME_OPTIONS\", 18) == 0 ||\n strncmp(key, \"STARTUP_MODE\", 12) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_TEXT\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_ACTION\", 20) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_FILE\", 18) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_WEBSITE\", 21) == 0) {\n section = INI_SECTION_TIMER;\n }\n else if (strncmp(key, \"POMODORO_\", 9) == 0) {\n section = INI_SECTION_POMODORO;\n }\n else if (strncmp(key, \"NOTIFICATION_\", 13) == 0 ||\n strncmp(key, \"CLOCK_TIMEOUT_MESSAGE_TEXT\", 26) == 0) {\n section = INI_SECTION_NOTIFICATION;\n }\n else if (strncmp(key, \"HOTKEY_\", 7) == 0) {\n section = INI_SECTION_HOTKEYS;\n }\n else if (strncmp(key, \"CLOCK_RECENT_FILE\", 17) == 0) {\n section = INI_SECTION_RECENTFILES;\n }\n else if (strncmp(key, \"COLOR_OPTIONS\", 13) == 0) {\n section = INI_SECTION_COLORS;\n }\n else {\n // 其他设置放在OPTIONS节\n section = INI_SECTION_OPTIONS;\n }\n \n // 写入配置\n WriteIniString(section, key, value, config_path);\n}\n\n/** @brief Write current language setting to configuration file */\nvoid WriteConfigLanguage(int language) {\n const char* langName;\n \n // Convert language enum value to readable language name\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n langName = \"Chinese_Simplified\";\n break;\n case APP_LANG_CHINESE_TRAD:\n langName = \"Chinese_Traditional\";\n break;\n case APP_LANG_ENGLISH:\n langName = \"English\";\n break;\n case APP_LANG_SPANISH:\n langName = \"Spanish\";\n break;\n case APP_LANG_FRENCH:\n langName = \"French\";\n break;\n case APP_LANG_GERMAN:\n langName = \"German\";\n break;\n case APP_LANG_RUSSIAN:\n langName = \"Russian\";\n break;\n case APP_LANG_PORTUGUESE:\n langName = \"Portuguese\";\n break;\n case APP_LANG_JAPANESE:\n langName = \"Japanese\";\n break;\n case APP_LANG_KOREAN:\n langName = \"Korean\";\n break;\n default:\n langName = \"English\"; // Default to English\n break;\n }\n \n WriteConfigKeyValue(\"LANGUAGE\", langName);\n}\n\n/** @brief Determine if shortcut check has been performed */\nbool IsShortcutCheckDone(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n return ReadIniBool(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", FALSE, config_path);\n}\n\n/** @brief Set shortcut check status */\nvoid SetShortcutCheckDone(bool done) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // 使用INI写入方式设置状态\n WriteIniString(INI_SECTION_GENERAL, \"SHORTCUT_CHECK_DONE\", done ? \"TRUE\" : \"FALSE\", config_path);\n}\n\n/** @brief Read whether to disable notification setting from configuration file */\nvoid ReadNotificationDisabledConfig(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Use INI reading method to get settings\n NOTIFICATION_DISABLED = ReadIniBool(INI_SECTION_NOTIFICATION, \"NOTIFICATION_DISABLED\", FALSE, config_path);\n}\n\n/** @brief Write whether to disable notification configuration */\nvoid WriteConfigNotificationDisabled(BOOL disabled) {\n char config_path[MAX_PATH];\n char temp_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n snprintf(temp_path, MAX_PATH, \"%s.tmp\", config_path);\n \n FILE *source_file, *temp_file;\n \n source_file = fopen(config_path, \"r\");\n temp_file = fopen(temp_path, \"w\");\n \n if (!source_file || !temp_file) {\n if (source_file) fclose(source_file);\n if (temp_file) fclose(temp_file);\n return;\n }\n \n char line[1024];\n BOOL found = FALSE;\n \n // Read and write line by line\n while (fgets(line, sizeof(line), source_file)) {\n // Remove trailing newline characters for comparison\n size_t len = strlen(line);\n if (len > 0 && (line[len-1] == '\\n' || line[len-1] == '\\r')) {\n line[--len] = '\\0';\n if (len > 0 && line[len-1] == '\\r')\n line[--len] = '\\0';\n }\n \n if (strncmp(line, \"NOTIFICATION_DISABLED=\", 22) == 0) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n found = TRUE;\n } else {\n // Restore newline and write back as is\n fprintf(temp_file, \"%s\\n\", line);\n }\n }\n \n // If configuration item not found in the configuration, add it\n if (!found) {\n fprintf(temp_file, \"NOTIFICATION_DISABLED=%s\\n\", disabled ? \"TRUE\" : \"FALSE\");\n }\n \n fclose(source_file);\n fclose(temp_file);\n \n // Replace original file\n remove(config_path);\n rename(temp_path, config_path);\n \n // Update global variable\n NOTIFICATION_DISABLED = disabled;\n}\n"], ["/Catime/src/timer_events.c", "/**\n * @file timer_events.c\n * @brief Implementation of timer event handling\n * \n * This file implements the functionality related to the application's timer event handling,\n * including countdown and count-up mode event processing.\n */\n\n#include \n#include \n#include \"../include/timer_events.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/pomodoro.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \"../include/window.h\"\n#include \"audio_player.h\" // Include header reference\n\n// Maximum capacity of Pomodoro time list\n#define MAX_POMODORO_TIMES 10\nextern int POMODORO_TIMES[MAX_POMODORO_TIMES]; // Store all Pomodoro times\nextern int POMODORO_TIMES_COUNT; // Actual number of Pomodoro times\n\n// Index of the currently executing Pomodoro time\nint current_pomodoro_time_index = 0;\n\n// Define current_pomodoro_phase variable, which is declared as extern in pomodoro.h\nPOMODORO_PHASE current_pomodoro_phase = POMODORO_PHASE_IDLE;\n\n// Number of completed Pomodoro cycles\nint complete_pomodoro_cycles = 0;\n\n// Function declarations imported from main.c\nextern void ShowNotification(HWND hwnd, const char* message);\n\n// Variable declarations imported from main.c, for timeout actions\nextern int elapsed_time;\nextern BOOL message_shown;\n\n// Custom message text imported from config.c\nextern char CLOCK_TIMEOUT_MESSAGE_TEXT[100];\nextern char POMODORO_TIMEOUT_MESSAGE_TEXT[100]; // New Pomodoro-specific prompt\nextern char POMODORO_CYCLE_COMPLETE_TEXT[100];\n\n// Define ClockState type\ntypedef enum {\n CLOCK_STATE_IDLE,\n CLOCK_STATE_COUNTDOWN,\n CLOCK_STATE_COUNTUP,\n CLOCK_STATE_POMODORO\n} ClockState;\n\n// Define PomodoroState type\ntypedef struct {\n BOOL isLastCycle;\n int cycleIndex;\n int totalCycles;\n} PomodoroState;\n\nextern HWND g_hwnd; // Main window handle\nextern ClockState g_clockState;\nextern PomodoroState g_pomodoroState;\n\n// Timer behavior function declarations\nextern void ShowTrayNotification(HWND hwnd, const char* message);\nextern void ShowNotification(HWND hwnd, const char* message);\nextern void OpenFileByPath(const char* filePath);\nextern void OpenWebsite(const char* url);\nextern void SleepComputer(void);\nextern void ShutdownComputer(void);\nextern void RestartComputer(void);\nextern void SetTimeDisplay(void);\nextern void ShowCountUp(HWND hwnd);\n\n// Add external function declaration to the beginning of the file or before the function\nextern void StopNotificationSound(void);\n\n/**\n * @brief Convert UTF-8 encoded char* string to wchar_t* string\n * @param utf8String Input UTF-8 string\n * @return Converted wchar_t* string, memory needs to be freed with free() after use. Returns NULL if conversion fails.\n */\nstatic wchar_t* Utf8ToWideChar(const char* utf8String) {\n if (!utf8String || utf8String[0] == '\\0') {\n return NULL; // Return NULL to handle empty strings or NULL pointers\n }\n int size_needed = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, NULL, 0);\n if (size_needed == 0) {\n // Conversion failed\n return NULL;\n }\n wchar_t* wideString = (wchar_t*)malloc(size_needed * sizeof(wchar_t));\n if (!wideString) {\n // Memory allocation failed\n return NULL;\n }\n int result = MultiByteToWideChar(CP_UTF8, 0, utf8String, -1, wideString, size_needed);\n if (result == 0) {\n // Conversion failed\n free(wideString);\n return NULL;\n }\n return wideString;\n}\n\n/**\n * @brief Convert wide character string to UTF-8 encoded regular string and display notification\n * @param hwnd Window handle\n * @param message Wide character string message to display (read from configuration and converted)\n */\nstatic void ShowLocalizedNotification(HWND hwnd, const wchar_t* message) {\n // Don't display if message is empty\n if (!message || message[0] == L'\\0') {\n return;\n }\n\n // Calculate required buffer size\n int size_needed = WideCharToMultiByte(CP_UTF8, 0, message, -1, NULL, 0, NULL, NULL);\n if (size_needed == 0) return; // Conversion failed\n\n // Allocate memory\n char* utf8Msg = (char*)malloc(size_needed);\n if (utf8Msg) {\n // Convert to UTF-8\n int result = WideCharToMultiByte(CP_UTF8, 0, message, -1, utf8Msg, size_needed, NULL, NULL);\n\n if (result > 0) {\n // Display notification using the new ShowNotification function\n ShowNotification(hwnd, utf8Msg);\n \n // If timeout action is MESSAGE, play notification audio\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE) {\n // Read the latest audio settings\n ReadNotificationSoundConfig();\n \n // Play notification audio\n PlayNotificationSound(hwnd);\n }\n }\n\n // Free memory\n free(utf8Msg);\n }\n}\n\n/**\n * @brief Set Pomodoro to work phase\n * \n * Reset all timer counts and set Pomodoro to work phase\n */\nvoid InitializePomodoro(void) {\n // Use existing enum value POMODORO_PHASE_WORK instead of POMODORO_PHASE_RUNNING\n current_pomodoro_phase = POMODORO_PHASE_WORK;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n \n // Set initial countdown to the first time value\n if (POMODORO_TIMES_COUNT > 0) {\n CLOCK_TOTAL_TIME = POMODORO_TIMES[0];\n } else {\n // If no time is configured, use default 25 minutes\n CLOCK_TOTAL_TIME = 1500;\n }\n \n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n}\n\n/**\n * @brief Handle timer messages\n * @param hwnd Window handle\n * @param wp Message parameter\n * @return BOOL Whether the message was handled\n */\nBOOL HandleTimerEvent(HWND hwnd, WPARAM wp) {\n if (wp == 1) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // In current time display mode, reset the last displayed second on each timer trigger to ensure the latest time is displayed\n extern int last_displayed_second;\n last_displayed_second = -1; // Force reset of seconds cache to ensure the latest system time is displayed each time\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n return TRUE;\n }\n\n // If timer is paused, don't update time\n if (CLOCK_IS_PAUSED) {\n return TRUE;\n }\n\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time++;\n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n if (countdown_elapsed_time < CLOCK_TOTAL_TIME) {\n countdown_elapsed_time++;\n if (countdown_elapsed_time >= CLOCK_TOTAL_TIME && !countdown_message_shown) {\n countdown_message_shown = TRUE;\n\n // Re-read message text from config file before displaying notification\n ReadNotificationMessagesConfig();\n // Force re-read notification type config to ensure latest settings are used\n ReadNotificationTypeConfig();\n \n // Variable declaration before branches to ensure availability in all branches\n wchar_t* timeoutMsgW = NULL;\n\n // Check if in Pomodoro mode - must meet all three conditions:\n // 1. Current Pomodoro phase is not IDLE \n // 2. Pomodoro time configuration is valid\n // 3. Current countdown total time matches the time at current index in the Pomodoro time list\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE && \n POMODORO_TIMES_COUNT > 0 && \n current_pomodoro_time_index < POMODORO_TIMES_COUNT &&\n CLOCK_TOTAL_TIME == POMODORO_TIMES[current_pomodoro_time_index]) {\n \n // Use Pomodoro-specific prompt message\n timeoutMsgW = Utf8ToWideChar(POMODORO_TIMEOUT_MESSAGE_TEXT);\n \n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"番茄钟时间到!\"); // Fallback\n }\n \n // Move to next time period\n current_pomodoro_time_index++;\n \n // Check if a complete cycle has been finished\n if (current_pomodoro_time_index >= POMODORO_TIMES_COUNT) {\n // Reset index back to the first time\n current_pomodoro_time_index = 0;\n \n // Increase completed cycle count\n complete_pomodoro_cycles++;\n \n // Check if all configured loop counts have been completed\n if (complete_pomodoro_cycles >= POMODORO_LOOP_COUNT) {\n // All loop counts completed, end Pomodoro\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_TOTAL_TIME = 0;\n \n // Reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n \n // Try to read and convert completion message from config\n wchar_t* cycleCompleteMsgW = Utf8ToWideChar(POMODORO_CYCLE_COMPLETE_TEXT);\n // Display completion prompt (using config or default value)\n if (cycleCompleteMsgW) {\n ShowLocalizedNotification(hwnd, cycleCompleteMsgW);\n free(cycleCompleteMsgW); // Free completion message memory\n } else {\n ShowLocalizedNotification(hwnd, L\"所有番茄钟循环完成!\"); // Fallback\n }\n \n // Switch to idle state - add the following code\n CLOCK_COUNT_UP = FALSE; // Ensure not in count-up mode\n CLOCK_SHOW_CURRENT_TIME = FALSE; // Ensure not in current time display mode\n message_shown = TRUE; // Mark message as shown\n \n // Force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n KillTimer(hwnd, 1);\n if (timeoutMsgW) free(timeoutMsgW); // Free timeout message memory\n return TRUE;\n }\n }\n \n // Set countdown for next time period\n CLOCK_TOTAL_TIME = POMODORO_TIMES[current_pomodoro_time_index];\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n \n // If it's the first time period in a new round, display cycle prompt\n if (current_pomodoro_time_index == 0 && complete_pomodoro_cycles > 0) {\n wchar_t cycleMsg[100];\n // GetLocalizedString needs to be reconsidered, or hardcode English/Chinese\n // Temporarily keep the original approach, but ideally should be configurable\n const wchar_t* formatStr = GetLocalizedString(L\"开始第 %d 轮番茄钟\", L\"Starting Pomodoro cycle %d\");\n swprintf(cycleMsg, 100, formatStr, complete_pomodoro_cycles + 1);\n ShowLocalizedNotification(hwnd, cycleMsg); // Call the modified function\n }\n \n InvalidateRect(hwnd, NULL, TRUE);\n } else {\n // Not in Pomodoro mode, or switched to normal countdown mode\n // Use normal countdown prompt message\n timeoutMsgW = Utf8ToWideChar(CLOCK_TIMEOUT_MESSAGE_TEXT);\n \n // Only display notification message if timeout action is not open file, lock, shutdown, or restart\n if (CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_OPEN_FILE && \n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_LOCK &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SHUTDOWN &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_RESTART &&\n CLOCK_TIMEOUT_ACTION != TIMEOUT_ACTION_SLEEP) {\n // Display timeout message (using config or default value)\n if (timeoutMsgW) {\n ShowLocalizedNotification(hwnd, timeoutMsgW);\n } else {\n ShowLocalizedNotification(hwnd, L\"时间到!\"); // Fallback\n }\n }\n \n // If current mode is not Pomodoro (manually switched to normal countdown), ensure not to return to Pomodoro cycle\n if (current_pomodoro_phase != POMODORO_PHASE_IDLE &&\n (current_pomodoro_time_index >= POMODORO_TIMES_COUNT ||\n CLOCK_TOTAL_TIME != POMODORO_TIMES[current_pomodoro_time_index])) {\n // If switched to normal countdown, reset Pomodoro state\n current_pomodoro_phase = POMODORO_PHASE_IDLE;\n current_pomodoro_time_index = 0;\n complete_pomodoro_cycles = 0;\n }\n \n // If sleep option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute sleep command\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n return TRUE;\n }\n \n // If shutdown option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute shutdown command\n system(\"shutdown /s /t 0\");\n return TRUE;\n }\n \n // If restart option, process immediately, skip other processing logic\n if (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART) {\n // Reset display and apply changes\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n // Immediately force redraw window to clear display\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n \n // Free memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n \n // Execute restart command\n system(\"shutdown /r /t 0\");\n return TRUE;\n }\n \n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE:\n // Notification already displayed, no additional operation needed\n break;\n case TIMEOUT_ACTION_LOCK:\n LockWorkStation();\n break;\n case TIMEOUT_ACTION_OPEN_FILE: {\n if (strlen(CLOCK_TIMEOUT_FILE_PATH) > 0) {\n wchar_t wPath[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_FILE_PATH, -1, wPath, MAX_PATH);\n \n HINSTANCE result = ShellExecuteW(NULL, L\"open\", wPath, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)result <= 32) {\n MessageBoxW(hwnd, \n GetLocalizedString(L\"无法打开文件\", L\"Failed to open file\"),\n GetLocalizedString(L\"错误\", L\"Error\"),\n MB_ICONERROR);\n }\n }\n break;\n }\n case TIMEOUT_ACTION_SHOW_TIME:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_COUNT_UP:\n // Stop any playing notification audio\n StopNotificationSound();\n \n // Switch to count-up mode and reset\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n countup_elapsed_time = 0;\n elapsed_time = 0;\n message_shown = FALSE;\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Set Pomodoro state to idle\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n InvalidateRect(hwnd, NULL, TRUE);\n break;\n case TIMEOUT_ACTION_OPEN_WEBSITE:\n if (strlen(CLOCK_TIMEOUT_WEBSITE_URL) > 0) {\n wchar_t wideUrl[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_TIMEOUT_WEBSITE_URL, -1, wideUrl, MAX_PATH);\n ShellExecuteW(NULL, L\"open\", wideUrl, NULL, NULL, SW_NORMAL);\n }\n break;\n case TIMEOUT_ACTION_RUN_COMMAND:\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n case TIMEOUT_ACTION_HTTP_REQUEST:\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n }\n\n // Free converted wide string memory\n if (timeoutMsgW) {\n free(timeoutMsgW);\n }\n }\n InvalidateRect(hwnd, NULL, TRUE);\n }\n }\n return TRUE;\n }\n return FALSE;\n}\n\nvoid OnTimerTimeout(HWND hwnd) {\n // Execute different behaviors based on timeout action\n switch (CLOCK_TIMEOUT_ACTION) {\n case TIMEOUT_ACTION_MESSAGE: {\n char utf8Msg[256] = {0};\n \n // Select different prompt messages based on current state\n if (g_clockState == CLOCK_STATE_POMODORO) {\n // Check if Pomodoro has completed all cycles\n if (g_pomodoroState.isLastCycle && g_pomodoroState.cycleIndex >= g_pomodoroState.totalCycles - 1) {\n strncpy(utf8Msg, POMODORO_CYCLE_COMPLETE_TEXT, sizeof(utf8Msg) - 1);\n } else {\n strncpy(utf8Msg, POMODORO_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n } else {\n strncpy(utf8Msg, CLOCK_TIMEOUT_MESSAGE_TEXT, sizeof(utf8Msg) - 1);\n }\n \n utf8Msg[sizeof(utf8Msg) - 1] = '\\0'; // Ensure string ends with null character\n \n // Display custom prompt message\n ShowNotification(hwnd, utf8Msg);\n \n // Read latest audio settings and play alert sound\n ReadNotificationSoundConfig();\n PlayNotificationSound(hwnd);\n \n break;\n }\n case TIMEOUT_ACTION_RUN_COMMAND: {\n // TODO: 实现运行命令功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"运行命令功能正在开发中\", L\"Run Command feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n case TIMEOUT_ACTION_HTTP_REQUEST: {\n // TODO: 实现HTTP请求功能\n MessageBoxW(hwnd, \n GetLocalizedString(L\"HTTP请求功能正在开发中\", L\"HTTP Request feature is under development\"),\n GetLocalizedString(L\"提示\", L\"Notice\"),\n MB_ICONINFORMATION);\n break;\n }\n\n }\n}\n\n// Add missing global variable definitions (if not defined elsewhere)\n#ifndef STUB_VARIABLES_DEFINED\n#define STUB_VARIABLES_DEFINED\n// Main window handle\nHWND g_hwnd = NULL;\n// Current clock state\nClockState g_clockState = CLOCK_STATE_IDLE;\n// Pomodoro state\nPomodoroState g_pomodoroState = {FALSE, 0, 1};\n#endif\n\n// Add stub function definitions if needed\n#ifndef STUB_FUNCTIONS_DEFINED\n#define STUB_FUNCTIONS_DEFINED\n__attribute__((weak)) void SleepComputer(void) {\n // This is a weak symbol definition, if there's an actual implementation elsewhere, that implementation will be used\n system(\"rundll32.exe powrprof.dll,SetSuspendState 0,1,0\");\n}\n\n__attribute__((weak)) void ShutdownComputer(void) {\n system(\"shutdown /s /t 0\");\n}\n\n__attribute__((weak)) void RestartComputer(void) {\n system(\"shutdown /r /t 0\");\n}\n\n__attribute__((weak)) void SetTimeDisplay(void) {\n // Stub implementation for setting time display\n}\n\n__attribute__((weak)) void ShowCountUp(HWND hwnd) {\n // Stub implementation for showing count-up\n}\n#endif\n"], ["/Catime/src/font.c", "/**\n * @file font.c\n * @brief Font management module implementation file\n * \n * This file implements the font management functionality of the application, including font loading, preview,\n * application and configuration file management. Supports loading multiple predefined fonts from resources.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/font.h\"\n#include \"../resource/resource.h\"\n\n/// @name Global font variables\n/// @{\nchar FONT_FILE_NAME[100] = \"Hack Nerd Font.ttf\"; ///< Currently used font file name\nchar FONT_INTERNAL_NAME[100]; ///< Font internal name (without extension)\nchar PREVIEW_FONT_NAME[100] = \"\"; ///< Preview font file name\nchar PREVIEW_INTERNAL_NAME[100] = \"\"; ///< Preview font internal name\nBOOL IS_PREVIEWING = FALSE; ///< Whether font preview is active\n/// @}\n\n/**\n * @brief Font resource array\n * \n * Stores information for all built-in font resources in the application\n */\nFontResource fontResources[] = {\n {CLOCK_IDC_FONT_RECMONO, IDR_FONT_RECMONO, \"RecMonoCasual Nerd Font Mono Essence.ttf\"},\n {CLOCK_IDC_FONT_DEPARTURE, IDR_FONT_DEPARTURE, \"DepartureMono Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_TERMINESS, IDR_FONT_TERMINESS, \"Terminess Nerd Font Propo Essence.ttf\"},\n {CLOCK_IDC_FONT_ARBUTUS, IDR_FONT_ARBUTUS, \"Arbutus Essence.ttf\"},\n {CLOCK_IDC_FONT_BERKSHIRE, IDR_FONT_BERKSHIRE, \"Berkshire Swash Essence.ttf\"},\n {CLOCK_IDC_FONT_CAVEAT, IDR_FONT_CAVEAT, \"Caveat Brush Essence.ttf\"},\n {CLOCK_IDC_FONT_CREEPSTER, IDR_FONT_CREEPSTER, \"Creepster Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTGOTHIC, IDR_FONT_DOTGOTHIC, \"DotGothic16 Essence.ttf\"},\n {CLOCK_IDC_FONT_DOTO, IDR_FONT_DOTO, \"Doto ExtraBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FOLDIT, IDR_FONT_FOLDIT, \"Foldit SemiBold Essence.ttf\"},\n {CLOCK_IDC_FONT_FREDERICKA, IDR_FONT_FREDERICKA, \"Fredericka the Great Essence.ttf\"},\n {CLOCK_IDC_FONT_FRIJOLE, IDR_FONT_FRIJOLE, \"Frijole Essence.ttf\"},\n {CLOCK_IDC_FONT_GWENDOLYN, IDR_FONT_GWENDOLYN, \"Gwendolyn Essence.ttf\"},\n {CLOCK_IDC_FONT_HANDJET, IDR_FONT_HANDJET, \"Handjet Essence.ttf\"},\n {CLOCK_IDC_FONT_INKNUT, IDR_FONT_INKNUT, \"Inknut Antiqua Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARD, IDR_FONT_JACQUARD, \"Jacquard 12 Essence.ttf\"},\n {CLOCK_IDC_FONT_JACQUARDA, IDR_FONT_JACQUARDA, \"Jacquarda Bastarda 9 Essence.ttf\"},\n {CLOCK_IDC_FONT_KAVOON, IDR_FONT_KAVOON, \"Kavoon Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE_OUTLINE, IDR_FONT_KUMAR_ONE_OUTLINE, \"Kumar One Outline Essence.ttf\"},\n {CLOCK_IDC_FONT_KUMAR_ONE, IDR_FONT_KUMAR_ONE, \"Kumar One Essence.ttf\"},\n {CLOCK_IDC_FONT_LAKKI_REDDY, IDR_FONT_LAKKI_REDDY, \"Lakki Reddy Essence.ttf\"},\n {CLOCK_IDC_FONT_LICORICE, IDR_FONT_LICORICE, \"Licorice Essence.ttf\"},\n {CLOCK_IDC_FONT_MA_SHAN_ZHENG, IDR_FONT_MA_SHAN_ZHENG, \"Ma Shan Zheng Essence.ttf\"},\n {CLOCK_IDC_FONT_MOIRAI_ONE, IDR_FONT_MOIRAI_ONE, \"Moirai One Essence.ttf\"},\n {CLOCK_IDC_FONT_MYSTERY_QUEST, IDR_FONT_MYSTERY_QUEST, \"Mystery Quest Essence.ttf\"},\n {CLOCK_IDC_FONT_NOTO_NASTALIQ, IDR_FONT_NOTO_NASTALIQ, \"Noto Nastaliq Urdu Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PIEDRA, IDR_FONT_PIEDRA, \"Piedra Essence.ttf\"},\n {CLOCK_IDC_FONT_PINYON_SCRIPT, IDR_FONT_PINYON_SCRIPT, \"Pinyon Script Essence.ttf\"},\n {CLOCK_IDC_FONT_PIXELIFY, IDR_FONT_PIXELIFY, \"Pixelify Sans Medium Essence.ttf\"},\n {CLOCK_IDC_FONT_PRESS_START, IDR_FONT_PRESS_START, \"Press Start 2P Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BUBBLES, IDR_FONT_RUBIK_BUBBLES, \"Rubik Bubbles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_BURNED, IDR_FONT_RUBIK_BURNED, \"Rubik Burned Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_GLITCH, IDR_FONT_RUBIK_GLITCH, \"Rubik Glitch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_MARKER_HATCH, IDR_FONT_RUBIK_MARKER_HATCH, \"Rubik Marker Hatch Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_PUDDLES, IDR_FONT_RUBIK_PUDDLES, \"Rubik Puddles Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_VINYL, IDR_FONT_RUBIK_VINYL, \"Rubik Vinyl Essence.ttf\"},\n {CLOCK_IDC_FONT_RUBIK_WET_PAINT, IDR_FONT_RUBIK_WET_PAINT, \"Rubik Wet Paint Essence.ttf\"},\n {CLOCK_IDC_FONT_RUGE_BOOGIE, IDR_FONT_RUGE_BOOGIE, \"Ruge Boogie Essence.ttf\"},\n {CLOCK_IDC_FONT_SEVILLANA, IDR_FONT_SEVILLANA, \"Sevillana Essence.ttf\"},\n {CLOCK_IDC_FONT_SILKSCREEN, IDR_FONT_SILKSCREEN, \"Silkscreen Essence.ttf\"},\n {CLOCK_IDC_FONT_STICK, IDR_FONT_STICK, \"Stick Essence.ttf\"},\n {CLOCK_IDC_FONT_UNDERDOG, IDR_FONT_UNDERDOG, \"Underdog Essence.ttf\"},\n {CLOCK_IDC_FONT_WALLPOET, IDR_FONT_WALLPOET, \"Wallpoet Essence.ttf\"},\n {CLOCK_IDC_FONT_YESTERYEAR, IDR_FONT_YESTERYEAR, \"Yesteryear Essence.ttf\"},\n {CLOCK_IDC_FONT_ZCOOL_KUAILE, IDR_FONT_ZCOOL_KUAILE, \"ZCOOL KuaiLe Essence.ttf\"},\n {CLOCK_IDC_FONT_PROFONT, IDR_FONT_PROFONT, \"ProFont IIx Nerd Font Essence.ttf\"},\n {CLOCK_IDC_FONT_DADDYTIME, IDR_FONT_DADDYTIME, \"DaddyTimeMono Nerd Font Propo Essence.ttf\"},\n};\n\n/// Number of font resources\nconst int FONT_RESOURCES_COUNT = sizeof(fontResources) / sizeof(FontResource);\n\n/// @name External variable declarations\n/// @{\nextern char CLOCK_TEXT_COLOR[]; ///< Current clock text color\n/// @}\n\n/// @name External function declarations\n/// @{\nextern void GetConfigPath(char* path, size_t maxLen); ///< Get configuration file path\nextern void ReadConfig(void); ///< Read configuration file\nextern int CALLBACK EnumFontFamExProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam); ///< Font enumeration callback function\n/// @}\n\nBOOL LoadFontFromResource(HINSTANCE hInstance, int resourceId) {\n // Find font resource\n HRSRC hResource = FindResource(hInstance, MAKEINTRESOURCE(resourceId), RT_FONT);\n if (hResource == NULL) {\n return FALSE;\n }\n\n // Load resource into memory\n HGLOBAL hMemory = LoadResource(hInstance, hResource);\n if (hMemory == NULL) {\n return FALSE;\n }\n\n // Lock resource\n void* fontData = LockResource(hMemory);\n if (fontData == NULL) {\n return FALSE;\n }\n\n // Get resource size and add font\n DWORD fontLength = SizeofResource(hInstance, hResource);\n DWORD nFonts = 0;\n HANDLE handle = AddFontMemResourceEx(fontData, fontLength, NULL, &nFonts);\n \n if (handle == NULL) {\n return FALSE;\n }\n \n return TRUE;\n}\n\nBOOL LoadFontByName(HINSTANCE hInstance, const char* fontName) {\n // Iterate through the font resource array to find a matching font\n for (int i = 0; i < sizeof(fontResources) / sizeof(FontResource); i++) {\n if (strcmp(fontResources[i].fontName, fontName) == 0) {\n return LoadFontFromResource(hInstance, fontResources[i].resourceId);\n }\n }\n return FALSE;\n}\n\nvoid WriteConfigFont(const char* font_file_name) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n // Open configuration file for reading\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n // Read the entire configuration file content\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n // Create new configuration file content\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n // Process line by line and replace font settings\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"FONT_FILE_NAME=\", 15) == 0) {\n strcat(new_config, \"FONT_FILE_NAME=\");\n strcat(new_config, font_file_name);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n // Write new configuration content\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n // Re-read configuration\n ReadConfig();\n}\n\nvoid ListAvailableFonts(void) {\n HDC hdc = GetDC(NULL);\n LOGFONT lf;\n memset(&lf, 0, sizeof(LOGFONT));\n lf.lfCharSet = DEFAULT_CHARSET;\n\n // Create temporary font and enumerate fonts\n HFONT hFont = CreateFont(12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n lf.lfCharSet, OUT_DEFAULT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,\n DEFAULT_PITCH | FF_DONTCARE, NULL);\n SelectObject(hdc, hFont);\n\n EnumFontFamiliesEx(hdc, &lf, (FONTENUMPROC)EnumFontFamExProc, 0, 0);\n\n // Clean up resources\n DeleteObject(hFont);\n ReleaseDC(NULL, hdc);\n}\n\nint CALLBACK EnumFontFamExProc(\n ENUMLOGFONTEX *lpelfe,\n NEWTEXTMETRICEX *lpntme,\n DWORD FontType,\n LPARAM lParam\n) {\n return 1;\n}\n\nBOOL PreviewFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Save current font name\n strncpy(PREVIEW_FONT_NAME, fontName, sizeof(PREVIEW_FONT_NAME) - 1);\n PREVIEW_FONT_NAME[sizeof(PREVIEW_FONT_NAME) - 1] = '\\0';\n \n // Get internal font name (remove .ttf extension)\n size_t name_len = strlen(PREVIEW_FONT_NAME);\n if (name_len > 4 && strcmp(PREVIEW_FONT_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(PREVIEW_INTERNAL_NAME))\n copy_len = sizeof(PREVIEW_INTERNAL_NAME) - 1;\n \n memcpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, copy_len);\n PREVIEW_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(PREVIEW_INTERNAL_NAME, PREVIEW_FONT_NAME, sizeof(PREVIEW_INTERNAL_NAME) - 1);\n PREVIEW_INTERNAL_NAME[sizeof(PREVIEW_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Load preview font\n if (!LoadFontByName(hInstance, PREVIEW_FONT_NAME)) {\n return FALSE;\n }\n \n IS_PREVIEWING = TRUE;\n return TRUE;\n}\n\nvoid CancelFontPreview(void) {\n IS_PREVIEWING = FALSE;\n PREVIEW_FONT_NAME[0] = '\\0';\n PREVIEW_INTERNAL_NAME[0] = '\\0';\n}\n\nvoid ApplyFontPreview(void) {\n // Check if there is a valid preview font\n if (!IS_PREVIEWING || strlen(PREVIEW_FONT_NAME) == 0) return;\n \n // Update current font\n strncpy(FONT_FILE_NAME, PREVIEW_FONT_NAME, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n strncpy(FONT_INTERNAL_NAME, PREVIEW_INTERNAL_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n \n // Save to configuration file and cancel preview state\n WriteConfigFont(FONT_FILE_NAME);\n CancelFontPreview();\n}\n\nBOOL SwitchFont(HINSTANCE hInstance, const char* fontName) {\n if (!fontName) return FALSE;\n \n // Load new font\n if (!LoadFontByName(hInstance, fontName)) {\n return FALSE;\n }\n \n // Update font name\n strncpy(FONT_FILE_NAME, fontName, sizeof(FONT_FILE_NAME) - 1);\n FONT_FILE_NAME[sizeof(FONT_FILE_NAME) - 1] = '\\0';\n \n // Update internal font name (remove .ttf extension)\n size_t name_len = strlen(FONT_FILE_NAME);\n if (name_len > 4 && strcmp(FONT_FILE_NAME + name_len - 4, \".ttf\") == 0) {\n // Ensure target size is sufficient, avoid depending on source string length\n size_t copy_len = name_len - 4;\n if (copy_len >= sizeof(FONT_INTERNAL_NAME))\n copy_len = sizeof(FONT_INTERNAL_NAME) - 1;\n \n memcpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, copy_len);\n FONT_INTERNAL_NAME[copy_len] = '\\0';\n } else {\n strncpy(FONT_INTERNAL_NAME, FONT_FILE_NAME, sizeof(FONT_INTERNAL_NAME) - 1);\n FONT_INTERNAL_NAME[sizeof(FONT_INTERNAL_NAME) - 1] = '\\0';\n }\n \n // Write to configuration file\n WriteConfigFont(FONT_FILE_NAME);\n return TRUE;\n}"], ["/Catime/src/window.c", "/**\n * @file window.c\n * @brief Window management functionality implementation\n * \n * This file implements the functionality related to application window management,\n * including window creation, position adjustment, transparency, click-through, and drag functionality.\n */\n\n#include \"../include/window.h\"\n#include \"../include/timer.h\"\n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n#include \n#include \n#include \n\n// Forward declaration of WindowProcedure (defined in main.c)\nextern LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\n\n// Add declaration for SetProcessDPIAware function\n#ifndef _INC_WINUSER\n// If not included by windows.h, add SetProcessDPIAware function declaration\nWINUSERAPI BOOL WINAPI SetProcessDPIAware(VOID);\n#endif\n\n// Window size and position variables\nint CLOCK_BASE_WINDOW_WIDTH = 200;\nint CLOCK_BASE_WINDOW_HEIGHT = 100;\nfloat CLOCK_WINDOW_SCALE = 1.0f;\nint CLOCK_WINDOW_POS_X = 100;\nint CLOCK_WINDOW_POS_Y = 100;\n\n// Window state variables\nBOOL CLOCK_EDIT_MODE = FALSE;\nBOOL CLOCK_IS_DRAGGING = FALSE;\nPOINT CLOCK_LAST_MOUSE_POS = {0, 0};\nBOOL CLOCK_WINDOW_TOPMOST = TRUE; // Default topmost\n\n// Text area variables\nRECT CLOCK_TEXT_RECT = {0, 0, 0, 0};\nBOOL CLOCK_TEXT_RECT_VALID = FALSE;\n\n// DWM function pointer type definition\ntypedef HRESULT (WINAPI *pfnDwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);\nstatic pfnDwmEnableBlurBehindWindow _DwmEnableBlurBehindWindow = NULL;\n\n// Window composition attribute type definition\ntypedef enum _WINDOWCOMPOSITIONATTRIB {\n WCA_UNDEFINED = 0,\n WCA_NCRENDERING_ENABLED = 1,\n WCA_NCRENDERING_POLICY = 2,\n WCA_TRANSITIONS_FORCEDISABLED = 3,\n WCA_ALLOW_NCPAINT = 4,\n WCA_CAPTION_BUTTON_BOUNDS = 5,\n WCA_NONCLIENT_RTL_LAYOUT = 6,\n WCA_FORCE_ICONIC_REPRESENTATION = 7,\n WCA_EXTENDED_FRAME_BOUNDS = 8,\n WCA_HAS_ICONIC_BITMAP = 9,\n WCA_THEME_ATTRIBUTES = 10,\n WCA_NCRENDERING_EXILED = 11,\n WCA_NCADORNMENTINFO = 12,\n WCA_EXCLUDED_FROM_LIVEPREVIEW = 13,\n WCA_VIDEO_OVERLAY_ACTIVE = 14,\n WCA_FORCE_ACTIVEWINDOW_APPEARANCE = 15,\n WCA_DISALLOW_PEEK = 16,\n WCA_CLOAK = 17,\n WCA_CLOAKED = 18,\n WCA_ACCENT_POLICY = 19,\n WCA_FREEZE_REPRESENTATION = 20,\n WCA_EVER_UNCLOAKED = 21,\n WCA_VISUAL_OWNER = 22,\n WCA_HOLOGRAPHIC = 23,\n WCA_EXCLUDED_FROM_DDA = 24,\n WCA_PASSIVEUPDATEMODE = 25,\n WCA_USEDARKMODECOLORS = 26,\n WCA_LAST = 27\n} WINDOWCOMPOSITIONATTRIB;\n\ntypedef struct _WINDOWCOMPOSITIONATTRIBDATA {\n WINDOWCOMPOSITIONATTRIB Attrib;\n PVOID pvData;\n SIZE_T cbData;\n} WINDOWCOMPOSITIONATTRIBDATA;\n\nWINUSERAPI BOOL WINAPI SetWindowCompositionAttribute(HWND hwnd, WINDOWCOMPOSITIONATTRIBDATA* pData);\n\ntypedef enum _ACCENT_STATE {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5\n} ACCENT_STATE;\n\ntypedef struct _ACCENT_POLICY {\n ACCENT_STATE AccentState;\n DWORD AccentFlags;\n DWORD GradientColor;\n DWORD AnimationId;\n} ACCENT_POLICY;\n\nvoid SetClickThrough(HWND hwnd, BOOL enable) {\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n // Clear previously set related styles\n exStyle &= ~WS_EX_TRANSPARENT;\n \n if (enable) {\n // Set click-through\n exStyle |= WS_EX_TRANSPARENT;\n \n // If the window is a layered window, ensure it properly handles mouse input\n if (exStyle & WS_EX_LAYERED) {\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n }\n } else {\n // Ensure window receives all mouse input\n if (exStyle & WS_EX_LAYERED) {\n // Maintain transparency but allow receiving mouse input\n SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);\n }\n }\n \n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Update window to apply new style\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n}\n\nBOOL InitDWMFunctions() {\n HMODULE hDwmapi = LoadLibraryA(\"dwmapi.dll\");\n if (hDwmapi) {\n _DwmEnableBlurBehindWindow = (pfnDwmEnableBlurBehindWindow)GetProcAddress(hDwmapi, \"DwmEnableBlurBehindWindow\");\n return _DwmEnableBlurBehindWindow != NULL;\n }\n return FALSE;\n}\n\nvoid SetBlurBehind(HWND hwnd, BOOL enable) {\n if (enable) {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_ENABLE_BLURBEHIND;\n policy.AccentFlags = 0;\n policy.GradientColor = (180 << 24) | 0x00202020; // Changed to dark gray background with 180 transparency\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = TRUE;\n bb.hRgnBlur = NULL;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n } else {\n ACCENT_POLICY policy = {0};\n policy.AccentState = ACCENT_DISABLED;\n \n WINDOWCOMPOSITIONATTRIBDATA data = {0};\n data.Attrib = WCA_ACCENT_POLICY;\n data.pvData = &policy;\n data.cbData = sizeof(policy);\n \n if (SetWindowCompositionAttribute) {\n SetWindowCompositionAttribute(hwnd, &data);\n } else if (_DwmEnableBlurBehindWindow) {\n DWM_BLURBEHIND bb = {0};\n bb.dwFlags = DWM_BB_ENABLE;\n bb.fEnable = FALSE;\n _DwmEnableBlurBehindWindow(hwnd, &bb);\n }\n }\n}\n\nvoid AdjustWindowPosition(HWND hwnd, BOOL forceOnScreen) {\n if (!forceOnScreen) {\n // Do not force window to be on screen, return directly\n return;\n }\n \n // Original code to ensure window is on screen\n RECT rect;\n GetWindowRect(hwnd, &rect);\n \n int screenWidth = GetSystemMetrics(SM_CXSCREEN);\n int screenHeight = GetSystemMetrics(SM_CYSCREEN);\n \n int width = rect.right - rect.left;\n int height = rect.bottom - rect.top;\n \n int x = rect.left;\n int y = rect.top;\n \n // Ensure window right edge doesn't exceed screen\n if (x + width > screenWidth) {\n x = screenWidth - width;\n }\n \n // Ensure window bottom edge doesn't exceed screen\n if (y + height > screenHeight) {\n y = screenHeight - height;\n }\n \n // Ensure window left edge doesn't exceed screen\n if (x < 0) {\n x = 0;\n }\n \n // Ensure window top edge doesn't exceed screen\n if (y < 0) {\n y = 0;\n }\n \n // If window position needs adjustment, move the window\n if (x != rect.left || y != rect.top) {\n SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n }\n}\n\nextern void GetConfigPath(char* path, size_t size);\nextern void WriteConfigEditMode(const char* mode);\n\nvoid SaveWindowSettings(HWND hwnd) {\n if (!hwnd) return;\n\n RECT rect;\n if (!GetWindowRect(hwnd, &rect)) return;\n \n CLOCK_WINDOW_POS_X = rect.left;\n CLOCK_WINDOW_POS_Y = rect.top;\n \n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n size_t buffer_size = 8192; \n char *config = malloc(buffer_size);\n char *new_config = malloc(buffer_size);\n if (!config || !new_config) {\n if (config) free(config);\n if (new_config) free(new_config);\n fclose(fp);\n return;\n }\n \n config[0] = new_config[0] = '\\0';\n char line[256];\n size_t total_len = 0;\n \n while (fgets(line, sizeof(line), fp)) {\n size_t line_len = strlen(line);\n if (total_len + line_len >= buffer_size - 1) {\n size_t new_size = buffer_size * 2;\n char *temp_config = realloc(config, new_size);\n char *temp_new_config = realloc(new_config, new_size);\n \n if (!temp_config || !temp_new_config) {\n free(config);\n free(new_config);\n fclose(fp);\n return;\n }\n \n config = temp_config;\n new_config = temp_new_config;\n buffer_size = new_size;\n }\n strcat(config, line);\n total_len += line_len;\n }\n fclose(fp);\n \n char *start = config;\n char *end = config + strlen(config);\n BOOL has_window_scale = FALSE;\n size_t new_config_len = 0;\n \n while (start < end) {\n char *newline = strchr(start, '\\n');\n if (!newline) newline = end;\n \n char temp[256] = {0};\n size_t line_len = newline - start;\n if (line_len >= sizeof(temp)) line_len = sizeof(temp) - 1;\n strncpy(temp, start, line_len);\n \n if (strncmp(temp, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len, \n buffer_size - new_config_len, \n \"CLOCK_WINDOW_POS_X=%d\\n\", CLOCK_WINDOW_POS_X);\n } else if (strncmp(temp, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"CLOCK_WINDOW_POS_Y=%d\\n\", CLOCK_WINDOW_POS_Y);\n } else if (strncmp(temp, \"WINDOW_SCALE=\", 13) == 0) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n has_window_scale = TRUE;\n } else {\n size_t remaining = buffer_size - new_config_len;\n if (remaining > line_len + 1) {\n strncpy(new_config + new_config_len, start, line_len);\n new_config_len += line_len;\n new_config[new_config_len++] = '\\n';\n }\n }\n \n start = newline + 1;\n if (start > end) break;\n }\n \n if (!has_window_scale && buffer_size - new_config_len > 50) {\n new_config_len += snprintf(new_config + new_config_len,\n buffer_size - new_config_len,\n \"WINDOW_SCALE=%.2f\\n\", CLOCK_WINDOW_SCALE);\n }\n \n if (new_config_len < buffer_size) {\n new_config[new_config_len] = '\\0';\n } else {\n new_config[buffer_size - 1] = '\\0';\n }\n \n fp = fopen(config_path, \"w\");\n if (fp) {\n fputs(new_config, fp);\n fclose(fp);\n }\n \n free(config);\n free(new_config);\n}\n\nvoid LoadWindowSettings(HWND hwnd) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n FILE *fp = fopen(config_path, \"r\");\n if (!fp) return;\n \n char line[256];\n while (fgets(line, sizeof(line), fp)) {\n line[strcspn(line, \"\\n\")] = 0;\n \n if (strncmp(line, \"CLOCK_WINDOW_POS_X=\", 19) == 0) {\n CLOCK_WINDOW_POS_X = atoi(line + 19);\n } else if (strncmp(line, \"CLOCK_WINDOW_POS_Y=\", 19) == 0) {\n CLOCK_WINDOW_POS_Y = atoi(line + 19);\n } else if (strncmp(line, \"WINDOW_SCALE=\", 13) == 0) {\n CLOCK_WINDOW_SCALE = atof(line + 13);\n CLOCK_FONT_SCALE_FACTOR = CLOCK_WINDOW_SCALE;\n }\n }\n fclose(fp);\n \n // Apply position from config file directly, without additional adjustments\n SetWindowPos(hwnd, NULL, \n CLOCK_WINDOW_POS_X, \n CLOCK_WINDOW_POS_Y,\n (int)(CLOCK_BASE_WINDOW_WIDTH * CLOCK_WINDOW_SCALE),\n (int)(CLOCK_BASE_WINDOW_HEIGHT * CLOCK_WINDOW_SCALE),\n SWP_NOZORDER\n );\n \n // Don't call AdjustWindowPosition to avoid overriding user settings\n}\n\nBOOL HandleMouseWheel(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n // Remove original position calculation logic, directly use window center as scaling reference point\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n // Use window center as scaling reference\n float relativeX = 0.5f;\n float relativeY = 0.5f;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings after resizing\n SaveWindowSettings(hwnd);\n }\n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleMouseMove(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update the position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nHWND CreateMainWindow(HINSTANCE hInstance, int nCmdShow) {\n // Window class registration\n WNDCLASS wc = {0};\n wc.lpfnWndProc = WindowProcedure;\n wc.hInstance = hInstance;\n wc.lpszClassName = \"CatimeWindow\";\n \n if (!RegisterClass(&wc)) {\n MessageBox(NULL, \"Window Registration Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n // Set extended style\n DWORD exStyle = WS_EX_LAYERED | WS_EX_TOOLWINDOW;\n \n // If not in topmost mode, add WS_EX_NOACTIVATE extended style\n if (!CLOCK_WINDOW_TOPMOST) {\n exStyle |= WS_EX_NOACTIVATE;\n }\n \n // Create window\n HWND hwnd = CreateWindowEx(\n exStyle,\n \"CatimeWindow\",\n \"Catime\",\n WS_POPUP,\n CLOCK_WINDOW_POS_X, CLOCK_WINDOW_POS_Y,\n CLOCK_BASE_WINDOW_WIDTH, CLOCK_BASE_WINDOW_HEIGHT,\n NULL,\n NULL,\n hInstance,\n NULL\n );\n\n if (!hwnd) {\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return NULL;\n }\n\n EnableWindow(hwnd, TRUE);\n SetFocus(hwnd);\n\n // Set window transparency\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n\n // Set blur effect\n SetBlurBehind(hwnd, FALSE);\n\n // Initialize tray icon\n InitTrayIcon(hwnd, hInstance);\n\n // Show window\n ShowWindow(hwnd, nCmdShow);\n UpdateWindow(hwnd);\n\n // Set window position and parent based on topmost status\n if (CLOCK_WINDOW_TOPMOST) {\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n } else {\n // Find desktop window and set as parent\n HWND hProgman = FindWindow(\"Progman\", NULL);\n if (hProgman != NULL) {\n // Try to find the real desktop window\n HWND hDesktop = hProgman;\n \n // Look for WorkerW window (common in Win10+)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n \n // Set as child window of desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, set to bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, \n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n\n return hwnd;\n}\n\nfloat CLOCK_FONT_SCALE_FACTOR = 1.0f;\nint CLOCK_BASE_FONT_SIZE = 24;\n\nBOOL InitializeApplication(HINSTANCE hInstance) {\n // Set DPI awareness mode to Per-Monitor DPI Aware to properly handle scaling when moving window between displays with different DPIs\n // Use newer API SetProcessDpiAwarenessContext if available, otherwise fallback to older APIs\n \n // Define DPI awareness related constants and types\n #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2\n DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);\n #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n #endif\n \n // Define PROCESS_DPI_AWARENESS enum\n typedef enum {\n PROCESS_DPI_UNAWARE = 0,\n PROCESS_SYSTEM_DPI_AWARE = 1,\n PROCESS_PER_MONITOR_DPI_AWARE = 2\n } PROCESS_DPI_AWARENESS;\n \n HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n if (hUser32) {\n typedef BOOL(WINAPI* SetProcessDpiAwarenessContextFunc)(DPI_AWARENESS_CONTEXT);\n SetProcessDpiAwarenessContextFunc setProcessDpiAwarenessContextFunc =\n (SetProcessDpiAwarenessContextFunc)GetProcAddress(hUser32, \"SetProcessDpiAwarenessContext\");\n \n if (setProcessDpiAwarenessContextFunc) {\n // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 is the latest DPI awareness mode\n // It provides better multi-monitor DPI support\n setProcessDpiAwarenessContextFunc(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);\n } else {\n // Try using older API\n HMODULE hShcore = LoadLibraryA(\"shcore.dll\");\n if (hShcore) {\n typedef HRESULT(WINAPI* SetProcessDpiAwarenessFunc)(PROCESS_DPI_AWARENESS);\n SetProcessDpiAwarenessFunc setProcessDpiAwarenessFunc =\n (SetProcessDpiAwarenessFunc)GetProcAddress(hShcore, \"SetProcessDpiAwareness\");\n \n if (setProcessDpiAwarenessFunc) {\n // PROCESS_PER_MONITOR_DPI_AWARE corresponds to per-monitor DPI awareness\n setProcessDpiAwarenessFunc(PROCESS_PER_MONITOR_DPI_AWARE);\n } else {\n // Finally try the oldest API\n SetProcessDPIAware();\n }\n \n FreeLibrary(hShcore);\n } else {\n // If shcore.dll is not available, use the most basic DPI awareness API\n SetProcessDPIAware();\n }\n }\n }\n \n SetConsoleOutputCP(936);\n SetConsoleCP(936);\n\n // Modified initialization order: read config file first, then initialize other features\n ReadConfig();\n UpdateStartupShortcut();\n InitializeDefaultLanguage();\n\n int defaultFontIndex = -1;\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, FONT_FILE_NAME) == 0) {\n defaultFontIndex = i;\n break;\n }\n }\n\n if (defaultFontIndex != -1) {\n LoadFontFromResource(hInstance, fontResources[defaultFontIndex].resourceId);\n }\n\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n \n return TRUE;\n}\n\nBOOL OpenFileDialog(HWND hwnd, char* filePath, DWORD maxPath) {\n OPENFILENAME ofn = { 0 };\n ofn.lStructSize = sizeof(OPENFILENAME);\n ofn.hwndOwner = hwnd;\n ofn.lpstrFilter = \"All Files\\0*.*\\0\";\n ofn.lpstrFile = filePath;\n ofn.nMaxFile = maxPath;\n ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;\n ofn.lpstrDefExt = \"\";\n \n return GetOpenFileName(&ofn);\n}\n\n// Add function to set window topmost state\nvoid SetWindowTopmost(HWND hwnd, BOOL topmost) {\n CLOCK_WINDOW_TOPMOST = topmost;\n \n // Get current window style\n LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n \n if (topmost) {\n // Topmost mode: remove no-activate style (if exists), add topmost style\n exStyle &= ~WS_EX_NOACTIVATE;\n \n // If window was previously set as desktop child window, need to restore\n // First set window as top-level window, clear parent window relationship\n SetParent(hwnd, NULL);\n \n // Reset window owner, ensure Z-order is correct\n SetWindowLongPtr(hwnd, GWLP_HWNDPARENT, 0);\n \n // Set window position to top layer, and force window update\n SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_FRAMECHANGED);\n } else {\n // Non-topmost mode: add no-activate style to prevent window from gaining focus\n exStyle |= WS_EX_NOACTIVATE;\n \n // Set as child window of desktop\n HWND hProgman = FindWindow(\"Progman\", NULL);\n HWND hDesktop = NULL;\n \n // Try to find the real desktop window\n if (hProgman != NULL) {\n // First try using Progman\n hDesktop = hProgman;\n \n // Look for WorkerW window (more common on Win10)\n HWND hWorkerW = FindWindowEx(NULL, NULL, \"WorkerW\", NULL);\n while (hWorkerW != NULL) {\n HWND hView = FindWindowEx(hWorkerW, NULL, \"SHELLDLL_DefView\", NULL);\n if (hView != NULL) {\n // Found the real desktop container\n hDesktop = hWorkerW;\n break;\n }\n hWorkerW = FindWindowEx(NULL, hWorkerW, \"WorkerW\", NULL);\n }\n }\n \n if (hDesktop != NULL) {\n // Set window as child of desktop, this keeps it on the desktop\n SetParent(hwnd, hDesktop);\n } else {\n // If desktop window not found, at least place at bottom of Z-order\n SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n }\n }\n \n // Apply new window style\n SetWindowLong(hwnd, GWL_EXSTYLE, exStyle);\n \n // Force window update\n SetWindowPos(hwnd, NULL, 0, 0, 0, 0,\n SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n \n // Save window topmost setting\n WriteConfigTopmost(topmost ? \"TRUE\" : \"FALSE\");\n}\n"], ["/Catime/src/tray_events.c", "/**\n * @file tray_events.c\n * @brief Implementation of system tray event handling module\n * \n * This module implements the event handling functionality for the application's system tray,\n * including response to various mouse events on the tray icon, menu display and control,\n * as well as tray operations related to the timer such as pause/resume and restart.\n * It provides core functionality for users to quickly control the application through the tray icon.\n */\n\n#include \n#include \n#include \"../include/tray_events.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/language.h\"\n#include \"../include/window_events.h\"\n#include \"../resource/resource.h\"\n\n// Declaration of function to read timeout action from configuration file\nextern void ReadTimeoutActionFromConfig(void);\n\n/**\n * @brief Handle system tray messages\n * @param hwnd Window handle\n * @param uID Tray icon ID\n * @param uMouseMsg Mouse message type\n * \n * Process mouse events for the system tray, displaying different context menus based on the event type:\n * - Left click: Display main function context menu, including timer control functions\n * - Right click: Display color selection menu for quickly changing display color\n * \n * All menu item command processing is implemented in the corresponding menu display module.\n */\nvoid HandleTrayIconMessage(HWND hwnd, UINT uID, UINT uMouseMsg) {\n // Set default cursor to prevent wait cursor display\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n if (uMouseMsg == WM_RBUTTONUP) {\n ShowColorMenu(hwnd);\n }\n else if (uMouseMsg == WM_LBUTTONUP) {\n ShowContextMenu(hwnd);\n }\n}\n\n/**\n * @brief Pause or resume timer\n * @param hwnd Window handle\n * \n * Toggle timer pause/resume state based on current status:\n * 1. Check if there is an active timer (countdown or count-up)\n * 2. If timer is active, toggle pause/resume state\n * 3. When paused, record current time point and stop timer\n * 4. When resumed, restart timer\n * 5. Refresh window to reflect new state\n * \n * Note: Can only operate when displaying timer (not current time) and timer is active\n */\nvoid PauseResumeTimer(HWND hwnd) {\n // Check if there is an active timer\n if (!CLOCK_SHOW_CURRENT_TIME && (CLOCK_COUNT_UP || CLOCK_TOTAL_TIME > 0)) {\n \n // Toggle pause/resume state\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n if (CLOCK_IS_PAUSED) {\n // If paused, record current time point\n CLOCK_LAST_TIME_UPDATE = time(NULL);\n // Stop timer\n KillTimer(hwnd, 1);\n \n // Pause playing notification audio (new addition)\n extern BOOL PauseNotificationSound(void);\n PauseNotificationSound();\n } else {\n // If resumed, restart timer\n SetTimer(hwnd, 1, 1000, NULL);\n \n // Resume notification audio (new addition)\n extern BOOL ResumeNotificationSound(void);\n ResumeNotificationSound();\n }\n \n // Update window to reflect new state\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Restart timer\n * @param hwnd Window handle\n * \n * Reset timer to initial state and continue running, keeping current timer type unchanged:\n * 1. Read current timeout action settings\n * 2. Reset timer progress based on current mode (countdown/count-up)\n * 3. Reset all related timer state variables\n * 4. Cancel pause state, ensure timer is running\n * 5. Refresh window and ensure window is on top after reset\n * \n * This operation does not change the timer mode or total duration, it only resets progress to initial state.\n */\nvoid RestartTimer(HWND hwnd) {\n // Stop any notification audio that may be playing\n extern void StopNotificationSound(void);\n StopNotificationSound();\n \n // Determine operation based on current mode\n if (!CLOCK_COUNT_UP) {\n // Countdown mode\n if (CLOCK_TOTAL_TIME > 0) {\n countdown_elapsed_time = 0;\n countdown_message_shown = FALSE;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n } else {\n // Count-up mode\n countup_elapsed_time = 0;\n CLOCK_IS_PAUSED = FALSE;\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n \n // Update window\n InvalidateRect(hwnd, NULL, TRUE);\n \n // Ensure window is on top and visible\n HandleWindowReset(hwnd);\n}\n\n/**\n * @brief Set startup mode\n * @param hwnd Window handle\n * @param mode Startup mode (\"COUNTDOWN\"/\"COUNT_UP\"/\"SHOW_TIME\"/\"NO_DISPLAY\")\n * \n * Set the application's default startup mode and save it to the configuration file:\n * 1. Save the selected mode to the configuration file\n * 2. Update menu item checked state to reflect current setting\n * 3. Refresh window display\n * \n * The startup mode determines the default behavior of the application at startup, such as whether to display current time or start timing.\n * The setting will take effect the next time the program starts.\n */\nvoid SetStartupMode(HWND hwnd, const char* mode) {\n // Save startup mode to configuration file\n WriteConfigStartupMode(mode);\n \n // Update menu item checked state\n HMENU hMenu = GetMenu(hwnd);\n if (hMenu) {\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\n/**\n * @brief Open user guide webpage\n * \n * Use ShellExecute to open Catime's user guide webpage,\n * providing detailed software instructions and help documentation for users.\n * URL: https://vladelaina.github.io/Catime/guide\n */\nvoid OpenUserGuide(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/guide\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open support page\n * \n * Use ShellExecute to open Catime's support page,\n * providing channels for users to support the developer.\n * URL: https://vladelaina.github.io/Catime/support\n */\nvoid OpenSupportPage(void) {\n ShellExecuteW(NULL, L\"open\", L\"https://vladelaina.github.io/Catime/support\", NULL, NULL, SW_SHOWNORMAL);\n}\n\n/**\n * @brief Open feedback page\n * \n * Open different feedback channels based on current language setting:\n * - Simplified Chinese: Open bilibili private message page\n * - Other languages: Open GitHub Issues page\n */\nvoid OpenFeedbackPage(void) {\n extern AppLanguage CURRENT_LANGUAGE; // Declare external variable\n \n // Choose different feedback links based on language\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP) {\n // Simplified Chinese users open bilibili private message\n ShellExecuteW(NULL, L\"open\", URL_FEEDBACK, NULL, NULL, SW_SHOWNORMAL);\n } else {\n // Users of other languages open GitHub Issues\n ShellExecuteW(NULL, L\"open\", L\"https://github.com/vladelaina/Catime/issues\", NULL, NULL, SW_SHOWNORMAL);\n }\n}"], ["/Catime/src/hotkey.c", "/**\n * @file hotkey.c\n * @brief Hotkey management implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#if defined _M_IX86\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_IA64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#elif defined _M_X64\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#else\n#pragma comment(linker,\"/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n#endif\n#include \"../include/hotkey.h\"\n#include \"../include/language.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../resource/resource.h\"\n\n#ifndef HOTKEYF_SHIFT\n#define HOTKEYF_SHIFT 0x01\n#define HOTKEYF_CONTROL 0x02\n#define HOTKEYF_ALT 0x04\n#endif\n\nstatic WORD g_dlgShowTimeHotkey = 0;\nstatic WORD g_dlgCountUpHotkey = 0;\nstatic WORD g_dlgCountdownHotkey = 0;\nstatic WORD g_dlgCustomCountdownHotkey = 0;\nstatic WORD g_dlgQuickCountdown1Hotkey = 0;\nstatic WORD g_dlgQuickCountdown2Hotkey = 0;\nstatic WORD g_dlgQuickCountdown3Hotkey = 0;\nstatic WORD g_dlgPomodoroHotkey = 0;\nstatic WORD g_dlgToggleVisibilityHotkey = 0;\nstatic WORD g_dlgEditModeHotkey = 0;\nstatic WORD g_dlgPauseResumeHotkey = 0;\nstatic WORD g_dlgRestartTimerHotkey = 0;\n\nstatic WNDPROC g_OldHotkeyDlgProc = NULL;\n\n/**\n * @brief Dialog subclassing procedure\n */\nLRESULT CALLBACK HotkeyDialogSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n if (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN || msg == WM_KEYUP || msg == WM_SYSKEYUP) {\n BYTE vk = (BYTE)wParam;\n if (!(vk == VK_SHIFT || vk == VK_CONTROL || vk == VK_MENU || vk == VK_LWIN || vk == VK_RWIN)) {\n BYTE currentModifiers = 0;\n if (GetKeyState(VK_SHIFT) & 0x8000) currentModifiers |= HOTKEYF_SHIFT;\n if (GetKeyState(VK_CONTROL) & 0x8000) currentModifiers |= HOTKEYF_CONTROL;\n if (msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP || (GetKeyState(VK_MENU) & 0x8000)) {\n currentModifiers |= HOTKEYF_ALT;\n }\n\n WORD currentEventKeyCombination = MAKEWORD(vk, currentModifiers);\n\n const WORD originalHotkeys[] = {\n g_dlgShowTimeHotkey, g_dlgCountUpHotkey, g_dlgCountdownHotkey,\n g_dlgQuickCountdown1Hotkey, g_dlgQuickCountdown2Hotkey, g_dlgQuickCountdown3Hotkey,\n g_dlgPomodoroHotkey, g_dlgToggleVisibilityHotkey, g_dlgEditModeHotkey,\n g_dlgPauseResumeHotkey, g_dlgRestartTimerHotkey\n };\n BOOL isAnOriginalHotkeyEvent = FALSE;\n for (size_t i = 0; i < sizeof(originalHotkeys) / sizeof(originalHotkeys[0]); ++i) {\n if (originalHotkeys[i] != 0 && originalHotkeys[i] == currentEventKeyCombination) {\n isAnOriginalHotkeyEvent = TRUE;\n break;\n }\n }\n\n if (isAnOriginalHotkeyEvent) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n }\n\n switch (msg) {\n case WM_SYSKEYDOWN:\n case WM_SYSKEYUP:\n {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (isHotkeyEditControl) {\n break;\n }\n }\n return 0;\n }\n\n case WM_KEYDOWN:\n case WM_KEYUP:\n {\n BYTE vk_code = (BYTE)wParam;\n if (vk_code == VK_SHIFT || vk_code == VK_CONTROL || vk_code == VK_LWIN || vk_code == VK_RWIN) {\n HWND hwndFocus = GetFocus();\n if (hwndFocus) {\n DWORD ctrlId = GetDlgCtrlID(hwndFocus);\n BOOL isHotkeyEditControl = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) { isHotkeyEditControl = TRUE; break; }\n }\n if (!isHotkeyEditControl) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n }\n break;\n\n case WM_SYSCOMMAND:\n if ((wParam & 0xFFF0) == SC_KEYMENU) {\n return 0;\n }\n break;\n }\n\n return CallWindowProc(g_OldHotkeyDlgProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Show hotkey settings dialog\n */\nvoid ShowHotkeySettingsDialog(HWND hwndParent) {\n DialogBox(GetModuleHandle(NULL),\n MAKEINTRESOURCE(CLOCK_IDD_HOTKEY_DIALOG),\n hwndParent,\n HotkeySettingsDlgProc);\n}\n\n/**\n * @brief Check if a hotkey is a single key\n */\nBOOL IsSingleKey(WORD hotkey) {\n BYTE modifiers = HIBYTE(hotkey);\n\n return modifiers == 0;\n}\n\n/**\n * @brief Check if a hotkey is a standalone letter, number, or symbol\n */\nBOOL IsRestrictedSingleKey(WORD hotkey) {\n if (hotkey == 0) {\n return FALSE;\n }\n\n BYTE vk = LOBYTE(hotkey);\n BYTE modifiers = HIBYTE(hotkey);\n\n if (modifiers != 0) {\n return FALSE;\n }\n\n if (vk >= 'A' && vk <= 'Z') {\n return TRUE;\n }\n\n if (vk >= '0' && vk <= '9') {\n return TRUE;\n }\n\n if (vk >= VK_NUMPAD0 && vk <= VK_NUMPAD9) {\n return TRUE;\n }\n\n switch (vk) {\n case VK_OEM_1:\n case VK_OEM_PLUS:\n case VK_OEM_COMMA:\n case VK_OEM_MINUS:\n case VK_OEM_PERIOD:\n case VK_OEM_2:\n case VK_OEM_3:\n case VK_OEM_4:\n case VK_OEM_5:\n case VK_OEM_6:\n case VK_OEM_7:\n case VK_SPACE:\n case VK_RETURN:\n case VK_ESCAPE:\n case VK_TAB:\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey settings dialog message processing procedure\n */\nINT_PTR CALLBACK HotkeySettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HBRUSH hBackgroundBrush = NULL;\n static HBRUSH hButtonBrush = NULL;\n\n switch (msg) {\n case WM_INITDIALOG: {\n SetWindowPos(hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n\n SetWindowTextW(hwndDlg, GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL1,\n GetLocalizedString(L\"显示当前时间:\", L\"Show Current Time:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL2,\n GetLocalizedString(L\"正计时:\", L\"Count Up:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL12,\n GetLocalizedString(L\"倒计时:\", L\"Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL3,\n GetLocalizedString(L\"默认倒计时:\", L\"Default Countdown:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL9,\n GetLocalizedString(L\"快捷倒计时1:\", L\"Quick Countdown 1:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL10,\n GetLocalizedString(L\"快捷倒计时2:\", L\"Quick Countdown 2:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL11,\n GetLocalizedString(L\"快捷倒计时3:\", L\"Quick Countdown 3:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL4,\n GetLocalizedString(L\"开始番茄钟:\", L\"Start Pomodoro:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL5,\n GetLocalizedString(L\"隐藏/显示窗口:\", L\"Hide/Show Window:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL6,\n GetLocalizedString(L\"进入编辑模式:\", L\"Enter Edit Mode:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL7,\n GetLocalizedString(L\"暂停/继续计时:\", L\"Pause/Resume Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_LABEL8,\n GetLocalizedString(L\"重新开始计时:\", L\"Restart Timer:\"));\n SetDlgItemTextW(hwndDlg, IDC_HOTKEY_NOTE,\n GetLocalizedString(L\"* 热键将全局生效\", L\"* Hotkeys will work globally\"));\n\n SetDlgItemTextW(hwndDlg, IDOK, GetLocalizedString(L\"确定\", L\"OK\"));\n SetDlgItemTextW(hwndDlg, IDCANCEL, GetLocalizedString(L\"取消\", L\"Cancel\"));\n\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n\n ReadConfigHotkeys(&g_dlgShowTimeHotkey, &g_dlgCountUpHotkey, &g_dlgCountdownHotkey,\n &g_dlgQuickCountdown1Hotkey, &g_dlgQuickCountdown2Hotkey, &g_dlgQuickCountdown3Hotkey,\n &g_dlgPomodoroHotkey, &g_dlgToggleVisibilityHotkey, &g_dlgEditModeHotkey,\n &g_dlgPauseResumeHotkey, &g_dlgRestartTimerHotkey);\n\n ReadCustomCountdownHotkey(&g_dlgCustomCountdownHotkey);\n\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_SETHOTKEY, g_dlgShowTimeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_SETHOTKEY, g_dlgCountUpHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_SETHOTKEY, g_dlgCustomCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_SETHOTKEY, g_dlgCountdownHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_SETHOTKEY, g_dlgQuickCountdown1Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_SETHOTKEY, g_dlgQuickCountdown2Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_SETHOTKEY, g_dlgQuickCountdown3Hotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_SETHOTKEY, g_dlgPomodoroHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_SETHOTKEY, g_dlgToggleVisibilityHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_SETHOTKEY, g_dlgEditModeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_SETHOTKEY, g_dlgPauseResumeHotkey, 0);\n SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_SETHOTKEY, g_dlgRestartTimerHotkey, 0);\n\n UnregisterGlobalHotkeys(GetParent(hwndDlg));\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n SetWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i, 0);\n }\n }\n\n g_OldHotkeyDlgProc = (WNDPROC)SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)HotkeyDialogSubclassProc);\n\n SetFocus(GetDlgItem(hwndDlg, IDCANCEL));\n\n return FALSE;\n }\n \n case WM_CTLCOLORDLG:\n case WM_CTLCOLORSTATIC: {\n HDC hdcStatic = (HDC)wParam;\n SetBkColor(hdcStatic, RGB(0xF3, 0xF3, 0xF3));\n if (!hBackgroundBrush) {\n hBackgroundBrush = CreateSolidBrush(RGB(0xF3, 0xF3, 0xF3));\n }\n return (INT_PTR)hBackgroundBrush;\n }\n \n case WM_CTLCOLORBTN: {\n HDC hdcBtn = (HDC)wParam;\n SetBkColor(hdcBtn, RGB(0xFD, 0xFD, 0xFD));\n if (!hButtonBrush) {\n hButtonBrush = CreateSolidBrush(RGB(0xFD, 0xFD, 0xFD));\n }\n return (INT_PTR)hButtonBrush;\n }\n \n case WM_LBUTTONDOWN: {\n POINT pt = {LOWORD(lParam), HIWORD(lParam)};\n HWND hwndHit = ChildWindowFromPoint(hwndDlg, pt);\n\n if (hwndHit != NULL && hwndHit != hwndDlg) {\n int ctrlId = GetDlgCtrlID(hwndHit);\n\n BOOL isHotkeyEdit = FALSE;\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT11; i++) {\n if (ctrlId == i) {\n isHotkeyEdit = TRUE;\n break;\n }\n }\n\n if (!isHotkeyEdit) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n }\n }\n else if (hwndHit == hwndDlg) {\n SetFocus(GetDlgItem(hwndDlg, IDC_HOTKEY_NOTE));\n return TRUE;\n }\n break;\n }\n \n case WM_COMMAND: {\n WORD ctrlId = LOWORD(wParam);\n WORD notifyCode = HIWORD(wParam);\n\n if (notifyCode == EN_CHANGE &&\n (ctrlId == IDC_HOTKEY_EDIT1 || ctrlId == IDC_HOTKEY_EDIT2 ||\n ctrlId == IDC_HOTKEY_EDIT3 || ctrlId == IDC_HOTKEY_EDIT4 ||\n ctrlId == IDC_HOTKEY_EDIT5 || ctrlId == IDC_HOTKEY_EDIT6 ||\n ctrlId == IDC_HOTKEY_EDIT7 || ctrlId == IDC_HOTKEY_EDIT8 ||\n ctrlId == IDC_HOTKEY_EDIT9 || ctrlId == IDC_HOTKEY_EDIT10 ||\n ctrlId == IDC_HOTKEY_EDIT11 || ctrlId == IDC_HOTKEY_EDIT12)) {\n\n WORD newHotkey = (WORD)SendDlgItemMessage(hwndDlg, ctrlId, HKM_GETHOTKEY, 0, 0);\n\n BYTE vk = LOBYTE(newHotkey);\n BYTE modifiers = HIBYTE(newHotkey);\n\n if (vk == 0xE5 && modifiers == HOTKEYF_SHIFT) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0 && IsRestrictedSingleKey(newHotkey)) {\n SendDlgItemMessage(hwndDlg, ctrlId, HKM_SETHOTKEY, 0, 0);\n return TRUE;\n }\n\n if (newHotkey != 0) {\n static const int hotkeyCtrlIds[] = {\n IDC_HOTKEY_EDIT1, IDC_HOTKEY_EDIT2, IDC_HOTKEY_EDIT3,\n IDC_HOTKEY_EDIT9, IDC_HOTKEY_EDIT10, IDC_HOTKEY_EDIT11,\n IDC_HOTKEY_EDIT4, IDC_HOTKEY_EDIT5, IDC_HOTKEY_EDIT6,\n IDC_HOTKEY_EDIT7, IDC_HOTKEY_EDIT8, IDC_HOTKEY_EDIT12\n };\n\n for (int i = 0; i < sizeof(hotkeyCtrlIds) / sizeof(hotkeyCtrlIds[0]); i++) {\n if (hotkeyCtrlIds[i] == ctrlId) {\n continue;\n }\n\n WORD otherHotkey = (WORD)SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_GETHOTKEY, 0, 0);\n\n if (otherHotkey != 0 && otherHotkey == newHotkey) {\n SendDlgItemMessage(hwndDlg, hotkeyCtrlIds[i], HKM_SETHOTKEY, 0, 0);\n }\n }\n }\n\n return TRUE;\n }\n \n switch (LOWORD(wParam)) {\n case IDOK: {\n WORD showTimeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT1, HKM_GETHOTKEY, 0, 0);\n WORD countUpHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT2, HKM_GETHOTKEY, 0, 0);\n WORD customCountdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT12, HKM_GETHOTKEY, 0, 0);\n WORD countdownHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT3, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown1Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT9, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown2Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT10, HKM_GETHOTKEY, 0, 0);\n WORD quickCountdown3Hotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT11, HKM_GETHOTKEY, 0, 0);\n WORD pomodoroHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT4, HKM_GETHOTKEY, 0, 0);\n WORD toggleVisibilityHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT5, HKM_GETHOTKEY, 0, 0);\n WORD editModeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT6, HKM_GETHOTKEY, 0, 0);\n WORD pauseResumeHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT7, HKM_GETHOTKEY, 0, 0);\n WORD restartTimerHotkey = (WORD)SendDlgItemMessage(hwndDlg, IDC_HOTKEY_EDIT8, HKM_GETHOTKEY, 0, 0);\n\n WORD* hotkeys[] = {\n &showTimeHotkey, &countUpHotkey, &countdownHotkey,\n &quickCountdown1Hotkey, &quickCountdown2Hotkey, &quickCountdown3Hotkey,\n &pomodoroHotkey, &toggleVisibilityHotkey, &editModeHotkey,\n &pauseResumeHotkey, &restartTimerHotkey, &customCountdownHotkey\n };\n\n for (int i = 0; i < sizeof(hotkeys) / sizeof(hotkeys[0]); i++) {\n if (LOBYTE(*hotkeys[i]) == 0xE5 && HIBYTE(*hotkeys[i]) == HOTKEYF_SHIFT) {\n *hotkeys[i] = 0;\n continue;\n }\n\n if (*hotkeys[i] != 0 && IsRestrictedSingleKey(*hotkeys[i])) {\n *hotkeys[i] = 0;\n }\n }\n\n WriteConfigHotkeys(showTimeHotkey, countUpHotkey, countdownHotkey,\n quickCountdown1Hotkey, quickCountdown2Hotkey, quickCountdown3Hotkey,\n pomodoroHotkey, toggleVisibilityHotkey, editModeHotkey,\n pauseResumeHotkey, restartTimerHotkey);\n g_dlgCustomCountdownHotkey = customCountdownHotkey;\n char customCountdownStr[64] = {0};\n HotkeyToString(customCountdownHotkey, customCountdownStr, sizeof(customCountdownStr));\n WriteConfigKeyValue(\"HOTKEY_CUSTOM_COUNTDOWN\", customCountdownStr);\n\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n\n case IDCANCEL:\n PostMessage(GetParent(hwndDlg), WM_APP+1, 0, 0);\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n \n case WM_DESTROY:\n if (hBackgroundBrush) {\n DeleteObject(hBackgroundBrush);\n hBackgroundBrush = NULL;\n }\n if (hButtonBrush) {\n DeleteObject(hButtonBrush);\n hButtonBrush = NULL;\n }\n\n if (g_OldHotkeyDlgProc) {\n SetWindowLongPtr(hwndDlg, GWLP_WNDPROC, (LONG_PTR)g_OldHotkeyDlgProc);\n g_OldHotkeyDlgProc = NULL;\n }\n\n for (int i = IDC_HOTKEY_EDIT1; i <= IDC_HOTKEY_EDIT12; i++) {\n HWND hHotkeyCtrl = GetDlgItem(hwndDlg, i);\n if (hHotkeyCtrl) {\n RemoveWindowSubclass(hHotkeyCtrl, HotkeyControlSubclassProc, i);\n }\n }\n break;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Hotkey control subclass procedure\n */\nLRESULT CALLBACK HotkeyControlSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam,\n LPARAM lParam, UINT_PTR uIdSubclass,\n DWORD_PTR dwRefData) {\n switch (uMsg) {\n case WM_GETDLGCODE:\n return DLGC_WANTALLKEYS | DLGC_WANTCHARS;\n\n case WM_KEYDOWN:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(hwndDlg, IDOK));\n return 0;\n }\n }\n break;\n }\n\n return DefSubclassProc(hwnd, uMsg, wParam, lParam);\n}"], ["/Catime/src/timer.c", "/**\n * @file timer.c\n * @brief Implementation of core timer functionality\n * \n * This file contains the implementation of the core timer logic, including time format conversion, \n * input parsing, configuration saving, and other functionalities,\n * while maintaining various timer states and configuration parameters.\n */\n\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n/** @name Timer status flags\n * @{ */\nBOOL CLOCK_IS_PAUSED = FALSE; ///< Timer pause status flag\nBOOL CLOCK_SHOW_CURRENT_TIME = FALSE; ///< Show current time mode flag\nBOOL CLOCK_USE_24HOUR = TRUE; ///< Use 24-hour format flag\nBOOL CLOCK_SHOW_SECONDS = TRUE; ///< Show seconds flag\nBOOL CLOCK_COUNT_UP = FALSE; ///< Countdown/count-up mode flag\nchar CLOCK_STARTUP_MODE[20] = \"COUNTDOWN\"; ///< Startup mode (countdown/count-up)\n/** @} */\n\n/** @name Timer time parameters \n * @{ */\nint CLOCK_TOTAL_TIME = 0; ///< Total timer time (seconds)\nint countdown_elapsed_time = 0; ///< Countdown elapsed time (seconds)\nint countup_elapsed_time = 0; ///< Count-up accumulated time (seconds)\ntime_t CLOCK_LAST_TIME_UPDATE = 0; ///< Last update timestamp\n\n// High-precision timer related variables\nLARGE_INTEGER timer_frequency; ///< High-precision timer frequency\nLARGE_INTEGER timer_last_count; ///< Last timing point\nBOOL high_precision_timer_initialized = FALSE; ///< High-precision timer initialization flag\n/** @} */\n\n/** @name Message status flags\n * @{ */\nBOOL countdown_message_shown = FALSE; ///< Countdown completion message display status\nBOOL countup_message_shown = FALSE; ///< Count-up completion message display status\nint pomodoro_work_cycles = 0; ///< Pomodoro work cycle count\n/** @} */\n\n/** @name Timeout action configuration\n * @{ */\nTimeoutActionType CLOCK_TIMEOUT_ACTION = TIMEOUT_ACTION_MESSAGE; ///< Timeout action type\nchar CLOCK_TIMEOUT_TEXT[50] = \"\"; ///< Timeout display text\nchar CLOCK_TIMEOUT_FILE_PATH[MAX_PATH] = \"\"; ///< Timeout executable file path\n/** @} */\n\n/** @name Pomodoro time settings\n * @{ */\nint POMODORO_WORK_TIME = 25 * 60; ///< Pomodoro work time (25 minutes)\nint POMODORO_SHORT_BREAK = 5 * 60; ///< Pomodoro short break time (5 minutes)\nint POMODORO_LONG_BREAK = 15 * 60; ///< Pomodoro long break time (15 minutes)\nint POMODORO_LOOP_COUNT = 1; ///< Pomodoro loop count (default 1 time)\n/** @} */\n\n/** @name Preset time options\n * @{ */\nint time_options[MAX_TIME_OPTIONS]; ///< Preset time options array\nint time_options_count = 0; ///< Number of valid preset times\n/** @} */\n\n/** Last displayed time (seconds), used to prevent time display jumping phenomenon */\nint last_displayed_second = -1;\n\n/**\n * @brief Initialize high-precision timer\n * \n * Get system timer frequency and record initial timing point\n * @return BOOL Whether initialization was successful\n */\nBOOL InitializeHighPrecisionTimer(void) {\n if (!QueryPerformanceFrequency(&timer_frequency)) {\n return FALSE; // System does not support high-precision timer\n }\n \n if (!QueryPerformanceCounter(&timer_last_count)) {\n return FALSE; // Failed to get current count\n }\n \n high_precision_timer_initialized = TRUE;\n return TRUE;\n}\n\n/**\n * @brief Calculate milliseconds elapsed since last call\n * \n * Use high-precision timer to calculate exact time interval\n * @return double Elapsed milliseconds\n */\ndouble GetElapsedMilliseconds(void) {\n if (!high_precision_timer_initialized) {\n if (!InitializeHighPrecisionTimer()) {\n return 0.0; // Initialization failed, return 0\n }\n }\n \n LARGE_INTEGER current_count;\n if (!QueryPerformanceCounter(¤t_count)) {\n return 0.0; // Failed to get current count\n }\n \n // Calculate time difference (convert to milliseconds)\n double elapsed = (double)(current_count.QuadPart - timer_last_count.QuadPart) * 1000.0 / (double)timer_frequency.QuadPart;\n \n // Update last timing point\n timer_last_count = current_count;\n \n return elapsed;\n}\n\n/**\n * @brief Update elapsed time for countdown/count-up\n * \n * Use high-precision timer to calculate time elapsed since last call, and update\n * countup_elapsed_time (count-up mode) or countdown_elapsed_time (countdown mode) accordingly.\n * No updates are made in pause state.\n */\nvoid UpdateElapsedTime(void) {\n if (CLOCK_IS_PAUSED) {\n return; // Do not update in pause state\n }\n \n double elapsed_ms = GetElapsedMilliseconds();\n \n if (CLOCK_COUNT_UP) {\n // Count-up mode\n countup_elapsed_time += (int)(elapsed_ms / 1000.0);\n } else {\n // Countdown mode\n countdown_elapsed_time += (int)(elapsed_ms / 1000.0);\n \n // Ensure does not exceed total time\n if (countdown_elapsed_time > CLOCK_TOTAL_TIME) {\n countdown_elapsed_time = CLOCK_TOTAL_TIME;\n }\n }\n}\n\n/**\n * @brief Format display time\n * @param remaining_time Remaining time (seconds)\n * @param[out] time_text Formatted time string output buffer\n * \n * Format time as a string according to current configuration (12/24 hour format, whether to show seconds, countdown/count-up mode).\n * Supports three display modes: current system time, countdown remaining time, count-up accumulated time.\n */\nvoid FormatTime(int remaining_time, char* time_text) {\n if (CLOCK_SHOW_CURRENT_TIME) {\n // Get local time\n SYSTEMTIME st;\n GetLocalTime(&st);\n \n // Check time continuity, prevent second jumping display\n if (last_displayed_second != -1) {\n // If not consecutive seconds, and not a cross-minute situation\n if (st.wSecond != (last_displayed_second + 1) % 60 && \n !(last_displayed_second == 59 && st.wSecond == 0)) {\n // Relax conditions, allow larger differences to sync, ensure not lagging behind for long\n if (st.wSecond != last_displayed_second) {\n // Directly use system time seconds\n last_displayed_second = st.wSecond;\n }\n } else {\n // Time is consecutive, normal update\n last_displayed_second = st.wSecond;\n }\n } else {\n // First display, initialize record\n last_displayed_second = st.wSecond;\n }\n \n int hour = st.wHour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, st.wMinute, last_displayed_second);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, st.wMinute);\n }\n return;\n }\n\n if (CLOCK_COUNT_UP) {\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n return;\n }\n\n // Update elapsed time before display\n UpdateElapsedTime();\n \n int remaining = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining <= 0) {\n // Do not return empty string, show 0:00 instead\n sprintf(time_text, \" 0:00\");\n return;\n }\n\n int hours = remaining / 3600;\n int minutes = (remaining % 3600) / 60;\n int seconds = remaining % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n if (minutes >= 10) {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \" %d:%02d\", minutes, seconds);\n }\n } else {\n if (seconds < 10) {\n sprintf(time_text, \" %d\", seconds);\n } else {\n sprintf(time_text, \" %d\", seconds);\n }\n }\n}\n\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n */\n\n// Detailed explanation of parsing logic and boundary handling\n/**\n * @brief Parse user input time string\n * @param input User input time string\n * @param[out] total_seconds Total seconds parsed\n * @return int Returns 1 if parsing successful, 0 if failed\n * \n * Supports multiple input formats:\n * - Single number (default minutes): \"25\" → 25 minutes\n * - With units: \"1h30m\" → 1 hour 30 minutes\n * - Two-segment format: \"25 3\" → 25 minutes 3 seconds\n * - Three-segment format: \"1 30 15\" → 1 hour 30 minutes 15 seconds\n * - Mixed format: \"25 30m\" → 25 hours 30 minutes\n * - Target time: \"17 30t\" or \"17 30T\" → Countdown to 17:30\n * \n * Parsing process:\n * 1. First check the validity of the input\n * 2. Detect if it's a target time format (ending with 't' or 'T')\n * - If so, calculate seconds from current to target time, if time has passed set to same time tomorrow\n * 3. Otherwise, check if it contains unit identifiers (h/m/s)\n * - If it does, process according to units\n * - If not, decide processing method based on number of space-separated numbers\n * \n * Boundary handling:\n * - Invalid input returns 0\n * - Negative or zero value returns 0\n * - Value exceeding INT_MAX returns 0\n */\nint ParseInput(const char* input, int* total_seconds) {\n if (!isValidInput(input)) return 0;\n\n int total = 0;\n char input_copy[256];\n strncpy(input_copy, input, sizeof(input_copy)-1);\n input_copy[sizeof(input_copy)-1] = '\\0';\n\n // Check if it's a target time format (ending with 't' or 'T')\n int len = strlen(input_copy);\n if (len > 0 && (input_copy[len-1] == 't' || input_copy[len-1] == 'T')) {\n // Remove 't' or 'T' suffix\n input_copy[len-1] = '\\0';\n \n // Get current time\n time_t now = time(NULL);\n struct tm *tm_now = localtime(&now);\n \n // Target time, initialize to current date\n struct tm tm_target = *tm_now;\n \n // Parse target time\n int hour = -1, minute = -1, second = -1;\n int count = 0;\n char *token = strtok(input_copy, \" \");\n \n while (token && count < 3) {\n int value = atoi(token);\n if (count == 0) hour = value;\n else if (count == 1) minute = value;\n else if (count == 2) second = value;\n count++;\n token = strtok(NULL, \" \");\n }\n \n // Set target time, set according to provided values, defaults to 0 if not provided\n if (hour >= 0) {\n tm_target.tm_hour = hour;\n \n // If only hour provided, set minute and second to 0\n if (minute < 0) {\n tm_target.tm_min = 0;\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_min = minute;\n \n // If second not provided, set to 0\n if (second < 0) {\n tm_target.tm_sec = 0;\n } else {\n tm_target.tm_sec = second;\n }\n }\n }\n \n // Calculate time difference (seconds)\n time_t target_time = mktime(&tm_target);\n \n // If target time has passed, set to same time tomorrow\n if (target_time <= now) {\n tm_target.tm_mday += 1;\n target_time = mktime(&tm_target);\n }\n \n total = (int)difftime(target_time, now);\n } else {\n // Check if it contains unit identifiers\n BOOL hasUnits = FALSE;\n for (int i = 0; input_copy[i]; i++) {\n char c = tolower((unsigned char)input_copy[i]);\n if (c == 'h' || c == 'm' || c == 's') {\n hasUnits = TRUE;\n break;\n }\n }\n \n if (hasUnits) {\n // For input with units, merge all parts with unit markings\n char* parts[10] = {0}; // Store up to 10 parts\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 10) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n // Process each part\n for (int i = 0; i < part_count; i++) {\n char* part = parts[i];\n int part_len = strlen(part);\n BOOL has_unit = FALSE;\n \n // Check if this part has a unit\n for (int j = 0; j < part_len; j++) {\n char c = tolower((unsigned char)part[j]);\n if (c == 'h' || c == 'm' || c == 's') {\n has_unit = TRUE;\n break;\n }\n }\n \n if (has_unit) {\n // If it has a unit, process according to unit\n char unit = tolower((unsigned char)part[part_len-1]);\n part[part_len-1] = '\\0'; // Remove unit\n int value = atoi(part);\n \n switch (unit) {\n case 'h': total += value * 3600; break;\n case 'm': total += value * 60; break;\n case 's': total += value; break;\n }\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'h') {\n // If next item has h unit, current item is hours\n total += atoi(part) * 3600;\n } else if (i < part_count - 1 && \n strlen(parts[i+1]) > 0 && \n tolower((unsigned char)parts[i+1][strlen(parts[i+1])-1]) == 'm') {\n // If next item has m unit, current item is hours\n total += atoi(part) * 3600;\n } else {\n // Default process as two-segment or three-segment format\n if (part_count == 2) {\n // Two-segment format: first segment is minutes, second segment is seconds\n if (i == 0) total += atoi(part) * 60;\n else total += atoi(part);\n } else if (part_count == 3) {\n // Three-segment format: hour:minute:second\n if (i == 0) total += atoi(part) * 3600;\n else if (i == 1) total += atoi(part) * 60;\n else total += atoi(part);\n } else {\n // Other cases treated as minutes\n total += atoi(part) * 60;\n }\n }\n }\n } else {\n // Processing without units\n char* parts[3] = {0}; // Store up to 3 parts (hour, minute, second)\n int part_count = 0;\n \n // Split input string\n char* token = strtok(input_copy, \" \");\n while (token && part_count < 3) {\n parts[part_count++] = token;\n token = strtok(NULL, \" \");\n }\n \n if (part_count == 1) {\n // Single number, calculate as minutes\n total = atoi(parts[0]) * 60;\n } else if (part_count == 2) {\n // Two numbers: minute:second\n total = atoi(parts[0]) * 60 + atoi(parts[1]);\n } else if (part_count == 3) {\n // Three numbers: hour:minute:second\n total = atoi(parts[0]) * 3600 + atoi(parts[1]) * 60 + atoi(parts[2]);\n }\n }\n }\n\n *total_seconds = total;\n if (*total_seconds <= 0) return 0;\n\n if (*total_seconds > INT_MAX) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Validate if input string is legal\n * @param input Input string to validate\n * @return int Returns 1 if legal, 0 if illegal\n * \n * Valid character check rules:\n * - Only allows digits, spaces, and h/m/s/t unit identifiers at the end (case insensitive)\n * - Must contain at least one digit\n * - Maximum of two space separators\n */\nint isValidInput(const char* input) {\n if (input == NULL || *input == '\\0') {\n return 0;\n }\n\n int len = strlen(input);\n int digitCount = 0;\n\n for (int i = 0; i < len; i++) {\n if (isdigit(input[i])) {\n digitCount++;\n } else if (input[i] == ' ') {\n // Allow any number of spaces\n } else if (i == len - 1 && (input[i] == 'h' || input[i] == 'm' || input[i] == 's' || \n input[i] == 't' || input[i] == 'T' || \n input[i] == 'H' || input[i] == 'M' || input[i] == 'S')) {\n // Allow last character to be h/m/s/t or their uppercase forms\n } else {\n return 0;\n }\n }\n\n if (digitCount == 0) {\n return 0;\n }\n\n return 1;\n}\n\n/**\n * @brief Reset timer\n * \n * Reset timer state, including pause flag, elapsed time, etc.\n */\nvoid ResetTimer(void) {\n // Reset timing state\n if (CLOCK_COUNT_UP) {\n countup_elapsed_time = 0;\n } else {\n countdown_elapsed_time = 0;\n \n // Ensure countdown total time is not zero, zero would cause timer not to display\n if (CLOCK_TOTAL_TIME <= 0) {\n // If total time is invalid, use default value\n CLOCK_TOTAL_TIME = 60; // Default set to 1 minute\n }\n }\n \n // Cancel pause state\n CLOCK_IS_PAUSED = FALSE;\n \n // Reset message display flags\n countdown_message_shown = FALSE;\n countup_message_shown = FALSE;\n \n // Reinitialize high-precision timer\n InitializeHighPrecisionTimer();\n}\n\n/**\n * @brief Toggle timer pause state\n * \n * Toggle timer between pause and continue states\n */\nvoid TogglePauseTimer(void) {\n CLOCK_IS_PAUSED = !CLOCK_IS_PAUSED;\n \n // If resuming from pause state, reinitialize high-precision timer\n if (!CLOCK_IS_PAUSED) {\n InitializeHighPrecisionTimer();\n }\n}\n\n/**\n * @brief Write default startup time to configuration file\n * @param seconds Default startup time (seconds)\n * \n * Use the general path retrieval method in the configuration management module to write to INI format configuration file\n */\nvoid WriteConfigDefaultStartTime(int seconds) {\n char config_path[MAX_PATH];\n \n // Get configuration file path\n GetConfigPath(config_path, MAX_PATH);\n \n // Write using INI format\n WriteIniInt(INI_SECTION_TIMER, \"CLOCK_DEFAULT_START_TIME\", seconds, config_path);\n}\n"], ["/Catime/src/dialog_language.c", "/**\n * @file dialog_language.c\n * @brief Dialog multi-language support module implementation\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \"../include/dialog_language.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\ntypedef struct {\n int dialogID;\n wchar_t* titleKey;\n} DialogTitleEntry;\n\ntypedef struct {\n int dialogID;\n int controlID;\n wchar_t* textKey;\n wchar_t* fallbackText;\n} SpecialControlEntry;\n\ntypedef struct {\n HWND hwndDlg;\n int dialogID;\n} EnumChildWindowsData;\n\nstatic DialogTitleEntry g_dialogTitles[] = {\n {IDD_ABOUT_DIALOG, L\"About\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, L\"Notification Settings\"},\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, L\"Set Pomodoro Loop Count\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, L\"Set Pomodoro Time Combination\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, L\"Set Pomodoro Time\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, L\"Countdown Presets\"},\n {CLOCK_IDD_WEBSITE_DIALOG, L\"Open Website\"},\n {CLOCK_IDD_DIALOG1, L\"Set Countdown\"},\n {IDD_NO_UPDATE_DIALOG, L\"Update Check\"},\n {IDD_UPDATE_DIALOG, L\"Update Available\"}\n};\n\nstatic SpecialControlEntry g_specialControls[] = {\n {IDD_ABOUT_DIALOG, IDC_ABOUT_TITLE, L\"关于\", L\"About\"},\n {IDD_ABOUT_DIALOG, IDC_VERSION_TEXT, L\"Version: %hs\", L\"Version: %hs\"},\n {IDD_ABOUT_DIALOG, IDC_BUILD_DATE, L\"构建日期:\", L\"Build Date:\"},\n {IDD_ABOUT_DIALOG, IDC_COPYRIGHT, L\"COPYRIGHT_TEXT\", L\"COPYRIGHT_TEXT\"},\n {IDD_ABOUT_DIALOG, IDC_CREDITS, L\"鸣谢\", L\"Credits\"},\n\n {IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT, L\"NoUpdateRequired\", L\"You are already using the latest version!\"},\n\n {IDD_UPDATE_DIALOG, IDC_UPDATE_TEXT, L\"CurrentVersion: %s\\nNewVersion: %s\", L\"Current Version: %s\\nNew Version: %s\"},\n {IDD_UPDATE_DIALOG, IDC_UPDATE_EXIT_TEXT, L\"The application will exit now\", L\"The application will exit now\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_CONTENT_GROUP, L\"Notification Content\", L\"Notification Content\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL1, L\"Countdown timeout message:\", L\"Countdown timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL2, L\"Pomodoro timeout message:\", L\"Pomodoro timeout message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_LABEL3, L\"Pomodoro cycle complete message:\", L\"Pomodoro cycle complete message:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_DISPLAY_GROUP, L\"Notification Display\", L\"Notification Display\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TIME_LABEL, L\"Notification display time:\", L\"Notification display time:\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_LABEL, L\"Maximum notification opacity (1-100%):\", L\"Maximum notification opacity (1-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_DISABLE_NOTIFICATION_CHECK, L\"Disable notifications\", L\"Disable notifications\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_METHOD_GROUP, L\"Notification Method\", L\"Notification Method\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_CATIME, L\"Catime notification window\", L\"Catime notification window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_OS, L\"System notification\", L\"System notification\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_TYPE_SYSTEM_MODAL, L\"System modal window\", L\"System modal window\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_SOUND_LABEL, L\"Sound (supports .mp3/.wav/.flac):\", L\"Sound (supports .mp3/.wav/.flac):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_LABEL, L\"Volume (0-100%):\", L\"Volume (0-100%):\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_VOLUME_TEXT, L\"100%\", L\"100%\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_NOTIFICATION_OPACITY_TEXT, L\"100%\", L\"100%\"},\n\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_STATIC,\n L\"25=25 minutes\\\\n25h=25 hours\\\\n25s=25 seconds\\\\n25 30=25 minutes 30 seconds\\\\n25 30m=25 hours 30 minutes\\\\n1 30 20=1 hour 30 minutes 20 seconds\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\"},\n\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter pomodoro time sequence, separated by spaces:\\\\n\\\\n25m = 25 minutes\\\\n30s = 30 seconds\\\\n1h30m = 1 hour 30 minutes\\\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\",\n L\"Enter pomodoro time sequence, separated by spaces:\\n\\n25m = 25 minutes\\n30s = 30 seconds\\n1h30m = 1 hour 30 minutes\\nExample: 25m 5m 25m 10m - work 25min, short break 5min, work 25min, long break 10min\"},\n\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_STATIC,\n L\"Enter the website URL to open when the countdown ends:\\\\nExample: https://github.com/vladelaina/Catime\",\n L\"Enter the website URL to open when the countdown ends:\\nExample: https://github.com/vladelaina/Catime\"},\n\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_STATIC,\n L\"CountdownPresetDialogStaticText\",\n L\"Enter numbers (minutes), separated by spaces\\n\\n25 10 5\\n\\nThis will create options for 25 minutes, 10 minutes, and 5 minutes\"},\n\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_STATIC,\n L\"CountdownDialogStaticText\",\n L\"25=25 minutes\\n25h=25 hours\\n25s=25 seconds\\n25 30=25 minutes 30 seconds\\n25 30m=25 hours 30 minutes\\n1 30 20=1 hour 30 minutes 20 seconds\\n17 20t=Countdown to 17:20\\n9 9 9t=Countdown to 09:09:09\"}\n};\n\nstatic SpecialControlEntry g_specialButtons[] = {\n {IDD_UPDATE_DIALOG, IDYES, L\"Yes\", L\"Yes\"},\n {IDD_UPDATE_DIALOG, IDNO, L\"No\", L\"No\"},\n {IDD_UPDATE_DIALOG, IDOK, L\"OK\", L\"OK\"},\n\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_TEST_SOUND_BUTTON, L\"Test\", L\"Test\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDC_OPEN_SOUND_DIR_BUTTON, L\"Audio folder\", L\"Audio folder\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDOK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_NOTIFICATION_SETTINGS_DIALOG, IDCANCEL, L\"Cancel\", L\"Cancel\"},\n\n {CLOCK_IDD_POMODORO_LOOP_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_COMBO_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_POMODORO_TIME_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_WEBSITE_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_SHORTCUT_DIALOG, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"},\n {CLOCK_IDD_DIALOG1, CLOCK_IDC_BUTTON_OK, L\"OK\", L\"OK\"}\n};\n\n#define DIALOG_TITLES_COUNT (sizeof(g_dialogTitles) / sizeof(g_dialogTitles[0]))\n#define SPECIAL_CONTROLS_COUNT (sizeof(g_specialControls) / sizeof(g_specialControls[0]))\n#define SPECIAL_BUTTONS_COUNT (sizeof(g_specialButtons) / sizeof(g_specialButtons[0]))\n\n/**\n * @brief Find localized text for special controls\n */\nstatic const wchar_t* FindSpecialControlText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_CONTROLS_COUNT; i++) {\n if (g_specialControls[i].dialogID == dialogID &&\n g_specialControls[i].controlID == controlID) {\n const wchar_t* localizedText = GetLocalizedString(NULL, g_specialControls[i].textKey);\n if (localizedText) {\n return localizedText;\n } else {\n return g_specialControls[i].fallbackText;\n }\n }\n }\n return NULL;\n}\n\n/**\n * @brief Find localized text for special buttons\n */\nstatic const wchar_t* FindSpecialButtonText(int dialogID, int controlID) {\n for (int i = 0; i < SPECIAL_BUTTONS_COUNT; i++) {\n if (g_specialButtons[i].dialogID == dialogID &&\n g_specialButtons[i].controlID == controlID) {\n return GetLocalizedString(NULL, g_specialButtons[i].textKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get localized text for dialog title\n */\nstatic const wchar_t* GetDialogTitleText(int dialogID) {\n for (int i = 0; i < DIALOG_TITLES_COUNT; i++) {\n if (g_dialogTitles[i].dialogID == dialogID) {\n return GetLocalizedString(NULL, g_dialogTitles[i].titleKey);\n }\n }\n return NULL;\n}\n\n/**\n * @brief Get original text of a control for translation lookup\n */\nstatic BOOL GetControlOriginalText(HWND hwndCtl, wchar_t* buffer, int bufferSize) {\n wchar_t className[256];\n GetClassNameW(hwndCtl, className, 256);\n\n if (wcscmp(className, L\"Button\") == 0 ||\n wcscmp(className, L\"Static\") == 0 ||\n wcscmp(className, L\"ComboBox\") == 0 ||\n wcscmp(className, L\"Edit\") == 0) {\n return GetWindowTextW(hwndCtl, buffer, bufferSize) > 0;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Process special control text settings, such as line breaks\n */\nstatic BOOL ProcessSpecialControlText(HWND hwndCtl, const wchar_t* localizedText, int dialogID, int controlID) {\n if ((dialogID == CLOCK_IDD_POMODORO_COMBO_DIALOG ||\n dialogID == CLOCK_IDD_POMODORO_TIME_DIALOG ||\n dialogID == CLOCK_IDD_WEBSITE_DIALOG ||\n dialogID == CLOCK_IDD_SHORTCUT_DIALOG ||\n dialogID == CLOCK_IDD_DIALOG1) &&\n controlID == CLOCK_IDC_STATIC) {\n wchar_t processedText[1024];\n const wchar_t* src = localizedText;\n wchar_t* dst = processedText;\n\n while (*src) {\n if (src[0] == L'\\\\' && src[1] == L'n') {\n *dst++ = L'\\n';\n src += 2;\n }\n else if (src[0] == L'\\n') {\n *dst++ = L'\\n';\n src++;\n }\n else {\n *dst++ = *src++;\n }\n }\n *dst = L'\\0';\n\n SetWindowTextW(hwndCtl, processedText);\n return TRUE;\n }\n\n if (controlID == IDC_VERSION_TEXT && dialogID == IDD_ABOUT_DIALOG) {\n wchar_t versionText[256];\n const wchar_t* localizedVersionFormat = GetLocalizedString(NULL, L\"Version: %hs\");\n if (localizedVersionFormat) {\n StringCbPrintfW(versionText, sizeof(versionText), localizedVersionFormat, CATIME_VERSION);\n } else {\n StringCbPrintfW(versionText, sizeof(versionText), localizedText, CATIME_VERSION);\n }\n SetWindowTextW(hwndCtl, versionText);\n return TRUE;\n }\n\n return FALSE;\n}\n\n/**\n * @brief Dialog child window enumeration callback function\n */\nstatic BOOL CALLBACK EnumChildProc(HWND hwndCtl, LPARAM lParam) {\n EnumChildWindowsData* data = (EnumChildWindowsData*)lParam;\n HWND hwndDlg = data->hwndDlg;\n int dialogID = data->dialogID;\n\n int controlID = GetDlgCtrlID(hwndCtl);\n if (controlID == 0) {\n return TRUE;\n }\n\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n if (ProcessSpecialControlText(hwndCtl, specialText, dialogID, controlID)) {\n return TRUE;\n }\n SetWindowTextW(hwndCtl, specialText);\n return TRUE;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n SetWindowTextW(hwndCtl, buttonText);\n return TRUE;\n }\n\n wchar_t originalText[512] = {0};\n if (GetControlOriginalText(hwndCtl, originalText, 512) && originalText[0] != L'\\0') {\n const wchar_t* localizedText = GetLocalizedString(NULL, originalText);\n if (localizedText && wcscmp(localizedText, originalText) != 0) {\n SetWindowTextW(hwndCtl, localizedText);\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Initialize dialog multi-language support\n */\nBOOL InitDialogLanguageSupport(void) {\n return TRUE;\n}\n\n/**\n * @brief Apply multi-language support to dialog\n */\nBOOL ApplyDialogLanguage(HWND hwndDlg, int dialogID) {\n if (!hwndDlg) return FALSE;\n\n const wchar_t* titleText = GetDialogTitleText(dialogID);\n if (titleText) {\n SetWindowTextW(hwndDlg, titleText);\n }\n\n EnumChildWindowsData data = {\n .hwndDlg = hwndDlg,\n .dialogID = dialogID\n };\n\n EnumChildWindows(hwndDlg, EnumChildProc, (LPARAM)&data);\n\n return TRUE;\n}\n\n/**\n * @brief Get localized text for dialog element\n */\nconst wchar_t* GetDialogLocalizedString(int dialogID, int controlID) {\n const wchar_t* specialText = FindSpecialControlText(dialogID, controlID);\n if (specialText) {\n return specialText;\n }\n\n const wchar_t* buttonText = FindSpecialButtonText(dialogID, controlID);\n if (buttonText) {\n return buttonText;\n }\n\n if (controlID == -1) {\n return GetDialogTitleText(dialogID);\n }\n\n return NULL;\n}"], ["/Catime/src/language.c", "/**\n * @file language.c\n * @brief Multilingual support module implementation\n * \n * This file implements the multilingual support functionality for the application, \n * including language detection and localized string handling.\n * Translation content is embedded as resources in the executable file.\n */\n\n#include \n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n\n/// Global language variable, stores the current application language setting\nAppLanguage CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default to English\n\n/// Global hash table for storing translations of the current language\n#define MAX_TRANSLATIONS 200\n#define MAX_STRING_LENGTH 1024\n\n// Language resource IDs (defined in languages.rc)\n#define LANG_EN_INI 1001 // Corresponds to languages/en.ini\n#define LANG_ZH_CN_INI 1002 // Corresponds to languages/zh_CN.ini\n#define LANG_ZH_TW_INI 1003 // Corresponds to languages/zh-Hant.ini\n#define LANG_ES_INI 1004 // Corresponds to languages/es.ini\n#define LANG_FR_INI 1005 // Corresponds to languages/fr.ini\n#define LANG_DE_INI 1006 // Corresponds to languages/de.ini\n#define LANG_RU_INI 1007 // Corresponds to languages/ru.ini\n#define LANG_PT_INI 1008 // Corresponds to languages/pt.ini\n#define LANG_JA_INI 1009 // Corresponds to languages/ja.ini\n#define LANG_KO_INI 1010 // Corresponds to languages/ko.ini\n\n/**\n * @brief Define language string key-value pair structure\n */\ntypedef struct {\n wchar_t english[MAX_STRING_LENGTH]; // English key\n wchar_t translation[MAX_STRING_LENGTH]; // Translated value\n} LocalizedString;\n\nstatic LocalizedString g_translations[MAX_TRANSLATIONS];\nstatic int g_translation_count = 0;\n\n/**\n * @brief Get the resource ID corresponding to a language\n * \n * @param language Language enumeration value\n * @return UINT Corresponding resource ID\n */\nstatic UINT GetLanguageResourceID(AppLanguage language) {\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n return LANG_ZH_CN_INI;\n case APP_LANG_CHINESE_TRAD:\n return LANG_ZH_TW_INI;\n case APP_LANG_SPANISH:\n return LANG_ES_INI;\n case APP_LANG_FRENCH:\n return LANG_FR_INI;\n case APP_LANG_GERMAN:\n return LANG_DE_INI;\n case APP_LANG_RUSSIAN:\n return LANG_RU_INI;\n case APP_LANG_PORTUGUESE:\n return LANG_PT_INI;\n case APP_LANG_JAPANESE:\n return LANG_JA_INI;\n case APP_LANG_KOREAN:\n return LANG_KO_INI;\n case APP_LANG_ENGLISH:\n default:\n return LANG_EN_INI;\n }\n}\n\n/**\n * @brief Convert UTF-8 string to wide character (UTF-16) string\n * \n * @param utf8 UTF-8 string\n * @param wstr Output wide character string buffer\n * @param wstr_size Buffer size (in characters)\n * @return int Number of characters after conversion, returns -1 if failed\n */\nstatic int UTF8ToWideChar(const char* utf8, wchar_t* wstr, int wstr_size) {\n return MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, wstr_size) - 1;\n}\n\n/**\n * @brief Parse a line in an ini file\n * \n * @param line A line from the ini file\n * @return int Whether parsing was successful (1 for success, 0 for failure)\n */\nstatic int ParseIniLine(const wchar_t* line) {\n // Skip empty lines and comment lines\n if (line[0] == L'\\0' || line[0] == L';' || line[0] == L'[') {\n return 0;\n }\n\n // Find content between the first and last quotes as the key\n const wchar_t* key_start = wcschr(line, L'\"');\n if (!key_start) return 0;\n key_start++; // Skip the first quote\n\n const wchar_t* key_end = wcschr(key_start, L'\"');\n if (!key_end) return 0;\n\n // Find content between the first and last quotes after the equal sign as the value\n const wchar_t* value_start = wcschr(key_end + 1, L'=');\n if (!value_start) return 0;\n \n value_start = wcschr(value_start, L'\"');\n if (!value_start) return 0;\n value_start++; // Skip the first quote\n\n const wchar_t* value_end = wcsrchr(value_start, L'\"');\n if (!value_end) return 0;\n\n // Copy key\n size_t key_len = key_end - key_start;\n if (key_len >= MAX_STRING_LENGTH) key_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].english, key_start, key_len);\n g_translations[g_translation_count].english[key_len] = L'\\0';\n\n // Copy value\n size_t value_len = value_end - value_start;\n if (value_len >= MAX_STRING_LENGTH) value_len = MAX_STRING_LENGTH - 1;\n wcsncpy(g_translations[g_translation_count].translation, value_start, value_len);\n g_translations[g_translation_count].translation[value_len] = L'\\0';\n\n g_translation_count++;\n return 1;\n}\n\n/**\n * @brief Load translations for a specified language from resources\n * \n * @param language Language enumeration value\n * @return int Whether loading was successful\n */\nstatic int LoadLanguageResource(AppLanguage language) {\n UINT resourceID = GetLanguageResourceID(language);\n \n // Reset translation count\n g_translation_count = 0;\n \n // Find resource\n HRSRC hResInfo = FindResource(NULL, MAKEINTRESOURCE(resourceID), RT_RCDATA);\n if (!hResInfo) {\n // If not found, check if it's Chinese and return\n if (language == APP_LANG_CHINESE_SIMP || language == APP_LANG_CHINESE_TRAD) {\n return 0;\n }\n \n // If not Chinese, load English as fallback\n if (language != APP_LANG_ENGLISH) {\n return LoadLanguageResource(APP_LANG_ENGLISH);\n }\n \n return 0;\n }\n \n // Get resource size\n DWORD dwSize = SizeofResource(NULL, hResInfo);\n if (dwSize == 0) {\n return 0;\n }\n \n // Load resource\n HGLOBAL hResData = LoadResource(NULL, hResInfo);\n if (!hResData) {\n return 0;\n }\n \n // Lock resource to get pointer\n const char* pData = (const char*)LockResource(hResData);\n if (!pData) {\n return 0;\n }\n \n // Create memory buffer copy\n char* buffer = (char*)malloc(dwSize + 1);\n if (!buffer) {\n return 0;\n }\n \n // Copy resource data to buffer\n memcpy(buffer, pData, dwSize);\n buffer[dwSize] = '\\0';\n \n // Split by lines and parse\n char* line = strtok(buffer, \"\\r\\n\");\n wchar_t wide_buffer[MAX_STRING_LENGTH];\n \n while (line && g_translation_count < MAX_TRANSLATIONS) {\n // Skip empty lines and BOM markers\n if (line[0] == '\\0' || (line[0] == (char)0xEF && line[1] == (char)0xBB && line[2] == (char)0xBF)) {\n line = strtok(NULL, \"\\r\\n\");\n continue;\n }\n \n // Convert to wide characters\n if (UTF8ToWideChar(line, wide_buffer, MAX_STRING_LENGTH) > 0) {\n ParseIniLine(wide_buffer);\n }\n \n line = strtok(NULL, \"\\r\\n\");\n }\n \n free(buffer);\n return 1;\n}\n\n/**\n * @brief Find corresponding translation in the global translation table\n * \n * @param english English original text\n * @return const wchar_t* Found translation, returns NULL if not found\n */\nstatic const wchar_t* FindTranslation(const wchar_t* english) {\n for (int i = 0; i < g_translation_count; i++) {\n if (wcscmp(english, g_translations[i].english) == 0) {\n return g_translations[i].translation;\n }\n }\n return NULL;\n}\n\n/**\n * @brief Initialize the application language environment\n * \n * Automatically detect and set the current language of the application based on system language.\n * Supports detection of Simplified Chinese, Traditional Chinese, and other preset languages.\n */\nstatic void DetectSystemLanguage() {\n LANGID langID = GetUserDefaultUILanguage();\n switch (PRIMARYLANGID(langID)) {\n case LANG_CHINESE:\n // Distinguish between Simplified and Traditional Chinese\n if (SUBLANGID(langID) == SUBLANG_CHINESE_SIMPLIFIED) {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_SIMP;\n } else {\n CURRENT_LANGUAGE = APP_LANG_CHINESE_TRAD;\n }\n break;\n case LANG_SPANISH:\n CURRENT_LANGUAGE = APP_LANG_SPANISH;\n break;\n case LANG_FRENCH:\n CURRENT_LANGUAGE = APP_LANG_FRENCH;\n break;\n case LANG_GERMAN:\n CURRENT_LANGUAGE = APP_LANG_GERMAN;\n break;\n case LANG_RUSSIAN:\n CURRENT_LANGUAGE = APP_LANG_RUSSIAN;\n break;\n case LANG_PORTUGUESE:\n CURRENT_LANGUAGE = APP_LANG_PORTUGUESE;\n break;\n case LANG_JAPANESE:\n CURRENT_LANGUAGE = APP_LANG_JAPANESE;\n break;\n case LANG_KOREAN:\n CURRENT_LANGUAGE = APP_LANG_KOREAN;\n break;\n default:\n CURRENT_LANGUAGE = APP_LANG_ENGLISH; // Default fallback to English\n }\n}\n\n/**\n * @brief Get localized string\n * @param chinese Simplified Chinese version of the string\n * @param english English version of the string\n * @return const wchar_t* Pointer to the string corresponding to the current language\n * \n * Returns the string in the corresponding language based on the current language setting.\n */\nconst wchar_t* GetLocalizedString(const wchar_t* chinese, const wchar_t* english) {\n // Initialize translation resources on first call, but don't automatically detect system language\n static BOOL initialized = FALSE;\n if (!initialized) {\n // No longer call DetectSystemLanguage() to automatically detect system language\n // Instead, use the currently set CURRENT_LANGUAGE value (possibly from a configuration file)\n LoadLanguageResource(CURRENT_LANGUAGE);\n initialized = TRUE;\n }\n\n const wchar_t* translation = NULL;\n\n // If Simplified Chinese and Chinese string is provided, return directly\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP && chinese) {\n return chinese;\n }\n\n // Find translation\n translation = FindTranslation(english);\n if (translation) {\n return translation;\n }\n\n // For Traditional Chinese but no translation found, return Simplified Chinese as a fallback\n if (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD && chinese) {\n return chinese;\n }\n\n // Default to English\n return english;\n}\n\n/**\n * @brief Set application language\n * \n * @param language The language to set\n * @return BOOL Whether the setting was successful\n */\nBOOL SetLanguage(AppLanguage language) {\n if (language < 0 || language >= APP_LANG_COUNT) {\n return FALSE;\n }\n \n CURRENT_LANGUAGE = language;\n g_translation_count = 0; // Clear existing translations\n return LoadLanguageResource(language);\n}\n\n/**\n * @brief Get current application language\n * \n * @return AppLanguage Current language\n */\nAppLanguage GetCurrentLanguage() {\n return CURRENT_LANGUAGE;\n}\n\n/**\n * @brief Get the name of the current language\n * @param buffer Buffer to store the language name\n * @param bufferSize Buffer size (in characters)\n * @return Whether the language name was successfully retrieved\n */\nBOOL GetCurrentLanguageName(wchar_t* buffer, size_t bufferSize) {\n if (!buffer || bufferSize == 0) {\n return FALSE;\n }\n \n // Get current language\n AppLanguage language = GetCurrentLanguage();\n \n // Return corresponding name based on language enumeration\n switch (language) {\n case APP_LANG_CHINESE_SIMP:\n wcscpy_s(buffer, bufferSize, L\"zh_CN\");\n break;\n case APP_LANG_CHINESE_TRAD:\n wcscpy_s(buffer, bufferSize, L\"zh-Hant\");\n break;\n case APP_LANG_SPANISH:\n wcscpy_s(buffer, bufferSize, L\"es\");\n break;\n case APP_LANG_FRENCH:\n wcscpy_s(buffer, bufferSize, L\"fr\");\n break;\n case APP_LANG_GERMAN:\n wcscpy_s(buffer, bufferSize, L\"de\");\n break;\n case APP_LANG_RUSSIAN:\n wcscpy_s(buffer, bufferSize, L\"ru\");\n break;\n case APP_LANG_PORTUGUESE:\n wcscpy_s(buffer, bufferSize, L\"pt\");\n break;\n case APP_LANG_JAPANESE:\n wcscpy_s(buffer, bufferSize, L\"ja\");\n break;\n case APP_LANG_KOREAN:\n wcscpy_s(buffer, bufferSize, L\"ko\");\n break;\n case APP_LANG_ENGLISH:\n default:\n wcscpy_s(buffer, bufferSize, L\"en\");\n break;\n }\n \n return TRUE;\n}\n"], ["/Catime/src/notification.c", "/**\n * @file notification.c\n * @brief Application notification system implementation\n * \n * This module implements various notification functions of the application, including:\n * 1. Custom styled popup notification windows with fade-in/fade-out animation effects\n * 2. System tray notification message integration\n * 3. Creation, display and lifecycle management of notification windows\n * \n * The notification system supports UTF-8 encoded Chinese text to ensure correct display in multilingual environments.\n */\n\n#include \n#include \n#include \"../include/tray.h\"\n#include \"../include/language.h\"\n#include \"../include/notification.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\" // Contains definitions of all IDs and constants\n#include // For GET_X_LPARAM and GET_Y_LPARAM macros\n\n// Imported from config.h\n// New: notification type configuration\nextern NotificationType NOTIFICATION_TYPE;\n\n/**\n * Notification window animation state enumeration\n * Tracks the current animation phase of the notification window\n */\ntypedef enum {\n ANIM_FADE_IN, // Fade-in phase - opacity increases from 0 to target value\n ANIM_VISIBLE, // Fully visible phase - maintains maximum opacity\n ANIM_FADE_OUT, // Fade-out phase - opacity decreases from maximum to 0\n} AnimationState;\n\n// Forward declarations\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid RegisterNotificationClass(HINSTANCE hInstance);\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius);\n\n/**\n * @brief Calculate the width required for text rendering\n * @param hdc Device context\n * @param text Text to measure\n * @param font Font to use\n * @return int Width required for text rendering (pixels)\n */\nint CalculateTextWidth(HDC hdc, const wchar_t* text, HFONT font) {\n HFONT oldFont = (HFONT)SelectObject(hdc, font);\n SIZE textSize;\n GetTextExtentPoint32W(hdc, text, wcslen(text), &textSize);\n SelectObject(hdc, oldFont);\n return textSize.cx;\n}\n\n/**\n * @brief Show notification (based on configured notification type)\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays different styles of notifications based on the configured notification type\n */\nvoid ShowNotification(HWND hwnd, const char* message) {\n // Read the latest notification type configuration\n ReadNotificationTypeConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Choose the corresponding notification method based on notification type\n switch (NOTIFICATION_TYPE) {\n case NOTIFICATION_TYPE_CATIME:\n ShowToastNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_SYSTEM_MODAL:\n ShowModalNotification(hwnd, message);\n break;\n case NOTIFICATION_TYPE_OS:\n ShowTrayNotification(hwnd, message);\n break;\n default:\n // Default to using Catime notification window\n ShowToastNotification(hwnd, message);\n break;\n }\n}\n\n/**\n * Modal dialog thread parameter structure\n */\ntypedef struct {\n HWND hwnd; // Parent window handle\n char message[512]; // Message content\n} DialogThreadParams;\n\n/**\n * @brief Thread function to display modal dialog\n * @param lpParam Thread parameter, pointer to DialogThreadParams structure\n * @return DWORD Thread return value\n */\nDWORD WINAPI ShowModalDialogThread(LPVOID lpParam) {\n DialogThreadParams* params = (DialogThreadParams*)lpParam;\n \n // Convert UTF-8 message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, params->message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, display English version directly\n MessageBoxA(params->hwnd, params->message, \"Catime\", MB_OK);\n free(params);\n return 0;\n }\n \n MultiByteToWideChar(CP_UTF8, 0, params->message, -1, wmessage, wlen);\n \n // Display modal dialog with fixed title \"Catime\"\n MessageBoxW(params->hwnd, wmessage, L\"Catime\", MB_OK);\n \n // Free allocated memory\n free(wmessage);\n free(params);\n \n return 0;\n}\n\n/**\n * @brief Display system modal dialog notification\n * @param hwnd Parent window handle\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a modal dialog in a separate thread, which won't block the main program\n */\nvoid ShowModalNotification(HWND hwnd, const char* message) {\n // Create thread parameter structure\n DialogThreadParams* params = (DialogThreadParams*)malloc(sizeof(DialogThreadParams));\n if (!params) return;\n \n // Copy parameters\n params->hwnd = hwnd;\n strncpy(params->message, message, sizeof(params->message) - 1);\n params->message[sizeof(params->message) - 1] = '\\0';\n \n // Create new thread to display dialog\n HANDLE hThread = CreateThread(\n NULL, // Default security attributes\n 0, // Default stack size\n ShowModalDialogThread, // Thread function\n params, // Thread parameter\n 0, // Run thread immediately\n NULL // Don't receive thread ID\n );\n \n // If thread creation fails, free resources\n if (hThread == NULL) {\n free(params);\n // Fall back to non-blocking notification method\n MessageBeep(MB_OK);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Close thread handle, let system clean up automatically\n CloseHandle(hThread);\n}\n\n/**\n * @brief Display custom styled toast notification\n * @param hwnd Parent window handle, used to get application instance and calculate position\n * @param message Notification message text to display (UTF-8 encoded)\n * \n * Displays a custom notification window with animation effects in the bottom right corner of the screen:\n * 1. Register notification window class (if needed)\n * 2. Calculate notification display position (bottom right of work area)\n * 3. Create notification window with fade-in/fade-out effects\n * 4. Set auto-close timer\n * \n * Note: If creating custom notification window fails, will fall back to using system tray notification\n */\nvoid ShowToastNotification(HWND hwnd, const char* message) {\n static BOOL isClassRegistered = FALSE;\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n \n // Dynamically read the latest notification settings before displaying notification\n ReadNotificationTimeoutConfig();\n ReadNotificationOpacityConfig();\n ReadNotificationDisabledConfig();\n \n // If notifications are disabled or timeout is 0, return directly\n if (NOTIFICATION_DISABLED || NOTIFICATION_TIMEOUT_MS == 0) {\n return;\n }\n \n // Register notification window class (if not already registered)\n if (!isClassRegistered) {\n RegisterNotificationClass(hInstance);\n isClassRegistered = TRUE;\n }\n \n // Convert message to wide characters to support Unicode display\n int wlen = MultiByteToWideChar(CP_UTF8, 0, message, -1, NULL, 0);\n wchar_t* wmessage = (wchar_t*)malloc(wlen * sizeof(wchar_t));\n if (!wmessage) {\n // Memory allocation failed, fall back to system tray notification\n ShowTrayNotification(hwnd, message);\n return;\n }\n MultiByteToWideChar(CP_UTF8, 0, message, -1, wmessage, wlen);\n \n // Calculate width needed for text\n HDC hdc = GetDC(hwnd);\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Calculate text width and add margins\n int textWidth = CalculateTextWidth(hdc, wmessage, contentFont);\n int notificationWidth = textWidth + 40; // 20 pixel margin on each side\n \n // Ensure width is within allowed range\n if (notificationWidth < NOTIFICATION_MIN_WIDTH) \n notificationWidth = NOTIFICATION_MIN_WIDTH;\n if (notificationWidth > NOTIFICATION_MAX_WIDTH) \n notificationWidth = NOTIFICATION_MAX_WIDTH;\n \n DeleteObject(contentFont);\n ReleaseDC(hwnd, hdc);\n \n // Get work area size, calculate notification window position (bottom right)\n RECT workArea;\n SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);\n \n int x = workArea.right - notificationWidth - 20;\n int y = workArea.bottom - NOTIFICATION_HEIGHT - 20;\n \n // Create notification window, add layered support for transparency effects\n HWND hNotification = CreateWindowExW(\n WS_EX_TOPMOST | WS_EX_LAYERED | WS_EX_TOOLWINDOW, // Keep on top and hide from taskbar\n NOTIFICATION_CLASS_NAME,\n L\"Catime Notification\", // Window title (not visible)\n WS_POPUP, // Borderless popup window style\n x, y, // Bottom right screen position\n notificationWidth, NOTIFICATION_HEIGHT,\n NULL, NULL, hInstance, NULL\n );\n \n // Fall back to system tray notification if creation fails\n if (!hNotification) {\n free(wmessage);\n ShowTrayNotification(hwnd, message);\n return;\n }\n \n // Save message text and window width to window properties\n SetPropW(hNotification, L\"MessageText\", (HANDLE)wmessage);\n SetPropW(hNotification, L\"WindowWidth\", (HANDLE)(LONG_PTR)notificationWidth);\n \n // Set initial animation state to fade-in\n SetPropW(hNotification, L\"AnimState\", (HANDLE)ANIM_FADE_IN);\n SetPropW(hNotification, L\"Opacity\", (HANDLE)0); // Initial opacity is 0\n \n // Set initial window to completely transparent\n SetLayeredWindowAttributes(hNotification, 0, 0, LWA_ALPHA);\n \n // Show window but don't activate (don't steal focus)\n ShowWindow(hNotification, SW_SHOWNOACTIVATE);\n UpdateWindow(hNotification);\n \n // Start fade-in animation\n SetTimer(hNotification, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n \n // Set auto-close timer, using globally configured timeout\n SetTimer(hNotification, NOTIFICATION_TIMER_ID, NOTIFICATION_TIMEOUT_MS, NULL);\n}\n\n/**\n * @brief Register notification window class\n * @param hInstance Application instance handle\n * \n * Registers custom notification window class with Windows, defining basic behavior and appearance:\n * 1. Set window procedure function\n * 2. Define default cursor and background\n * 3. Specify unique window class name\n * \n * This function is only called the first time a notification is displayed, subsequent calls reuse the registered class.\n */\nvoid RegisterNotificationClass(HINSTANCE hInstance) {\n WNDCLASSEXW wc = {0};\n wc.cbSize = sizeof(WNDCLASSEXW);\n wc.lpfnWndProc = NotificationWndProc;\n wc.hInstance = hInstance;\n wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n wc.lpszClassName = NOTIFICATION_CLASS_NAME;\n \n RegisterClassExW(&wc);\n}\n\n/**\n * @brief Notification window message processing procedure\n * @param hwnd Window handle\n * @param msg Message ID\n * @param wParam Message parameter\n * @param lParam Message parameter\n * @return LRESULT Message processing result\n * \n * Handles all Windows messages for the notification window, including:\n * - WM_PAINT: Draw notification window content (title, message text)\n * - WM_TIMER: Handle auto-close and animation effects\n * - WM_LBUTTONDOWN: Handle user click to close\n * - WM_DESTROY: Release window resources\n * \n * Specifically handles animation state transition logic to ensure smooth fade-in/fade-out effects.\n */\nLRESULT CALLBACK NotificationWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_PAINT: {\n PAINTSTRUCT ps;\n HDC hdc = BeginPaint(hwnd, &ps);\n \n // Get window client area size\n RECT clientRect;\n GetClientRect(hwnd, &clientRect);\n \n // Create compatible DC and bitmap for double-buffered drawing to avoid flickering\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, clientRect.right, clientRect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n \n // Fill white background\n HBRUSH whiteBrush = CreateSolidBrush(RGB(255, 255, 255));\n FillRect(memDC, &clientRect, whiteBrush);\n DeleteObject(whiteBrush);\n \n // Draw rectangle with border\n DrawRoundedRectangle(memDC, clientRect, 0);\n \n // Set text drawing mode to transparent background\n SetBkMode(memDC, TRANSPARENT);\n \n // Create title font - bold\n HFONT titleFont = CreateFontW(22, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Create message content font\n HFONT contentFont = CreateFontW(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\n DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L\"Microsoft YaHei\");\n \n // Draw title \"Catime\"\n SelectObject(memDC, titleFont);\n SetTextColor(memDC, RGB(0, 0, 0));\n RECT titleRect = {15, 10, clientRect.right - 15, 35};\n DrawTextW(memDC, L\"Catime\", -1, &titleRect, DT_SINGLELINE);\n \n // Draw message content - placed below title, using single line mode\n SelectObject(memDC, contentFont);\n SetTextColor(memDC, RGB(100, 100, 100));\n const wchar_t* message = (const wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n RECT textRect = {15, 35, clientRect.right - 15, clientRect.bottom - 10};\n // Use DT_SINGLELINE|DT_END_ELLIPSIS to ensure text is displayed in one line, with ellipsis for long text\n DrawTextW(memDC, message, -1, &textRect, DT_SINGLELINE|DT_END_ELLIPSIS);\n }\n \n // Copy content from memory DC to window DC\n BitBlt(hdc, 0, 0, clientRect.right, clientRect.bottom, memDC, 0, 0, SRCCOPY);\n \n // Clean up resources\n SelectObject(memDC, oldBitmap);\n DeleteObject(titleFont);\n DeleteObject(contentFont);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n \n EndPaint(hwnd, &ps);\n return 0;\n }\n \n case WM_TIMER:\n if (wParam == NOTIFICATION_TIMER_ID) {\n // Auto-close timer triggered, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // Check current state - only start fade-out when fully visible\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState == ANIM_VISIBLE) {\n // Set to fade-out state\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start animation timer\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n return 0;\n }\n else if (wParam == ANIMATION_TIMER_ID) {\n // Handle animation effect timer\n AnimationState state = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n DWORD opacityVal = (DWORD)(DWORD_PTR)GetPropW(hwnd, L\"Opacity\");\n BYTE opacity = (BYTE)opacityVal;\n \n // Calculate maximum opacity value (percentage converted to 0-255 range)\n BYTE maxOpacity = (BYTE)((NOTIFICATION_MAX_OPACITY * 255) / 100);\n \n switch (state) {\n case ANIM_FADE_IN:\n // Fade-in animation - gradually increase opacity\n if (opacity >= maxOpacity - ANIMATION_STEP) {\n // Reached maximum opacity, completed fade-in\n opacity = maxOpacity;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n \n // Switch to visible state and stop animation\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_VISIBLE);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n } else {\n // Normal fade-in - increase by one step each time\n opacity += ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_FADE_OUT:\n // Fade-out animation - gradually decrease opacity\n if (opacity <= ANIMATION_STEP) {\n // Completely transparent, destroy window\n KillTimer(hwnd, ANIMATION_TIMER_ID); // Make sure to stop timer first\n DestroyWindow(hwnd);\n } else {\n // Normal fade-out - decrease by one step each time\n opacity -= ANIMATION_STEP;\n SetPropW(hwnd, L\"Opacity\", (HANDLE)(DWORD_PTR)opacity);\n SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA);\n }\n break;\n \n case ANIM_VISIBLE:\n // Fully visible state doesn't need animation, stop timer\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n break;\n }\n return 0;\n }\n break;\n \n case WM_LBUTTONDOWN: {\n // Handle left mouse button click event (close notification early)\n \n // Get current state - only respond to clicks when fully visible or after fade-in completes\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n if (currentState != ANIM_VISIBLE) {\n return 0; // Ignore click, avoid interference during animation\n }\n \n // Click anywhere, start fade-out animation\n KillTimer(hwnd, NOTIFICATION_TIMER_ID); // Stop auto-close timer\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n return 0;\n }\n \n case WM_DESTROY: {\n // Cleanup work when window is destroyed\n \n // Stop all timers\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n KillTimer(hwnd, ANIMATION_TIMER_ID);\n \n // Free message text memory\n wchar_t* message = (wchar_t*)GetPropW(hwnd, L\"MessageText\");\n if (message) {\n free(message);\n }\n \n // Remove all window properties\n RemovePropW(hwnd, L\"MessageText\");\n RemovePropW(hwnd, L\"AnimState\");\n RemovePropW(hwnd, L\"Opacity\");\n return 0;\n }\n }\n \n return DefWindowProc(hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Draw rectangle with border\n * @param hdc Device context\n * @param rect Rectangle area\n * @param radius Corner radius (unused)\n * \n * Draws a rectangle with light gray border in the specified device context.\n * This function reserves the corner radius parameter, but current implementation uses standard rectangle.\n * Can be extended to support true rounded rectangles in future versions.\n */\nvoid DrawRoundedRectangle(HDC hdc, RECT rect, int radius) {\n // Create light gray border pen\n HPEN pen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200));\n HPEN oldPen = (HPEN)SelectObject(hdc, pen);\n \n // Use normal rectangle instead of rounded rectangle\n Rectangle(hdc, rect.left, rect.top, rect.right, rect.bottom);\n \n // Clean up resources\n SelectObject(hdc, oldPen);\n DeleteObject(pen);\n}\n\n/**\n * @brief Close all currently displayed Catime notification windows\n * \n * Find and close all notification windows created by Catime, ignoring their current display time settings,\n * directly start fade-out animation. Usually called when switching timer modes to ensure notifications don't continue to display.\n */\nvoid CloseAllNotifications(void) {\n // Find all notification windows created by Catime\n HWND hwnd = NULL;\n HWND hwndPrev = NULL;\n \n // Use FindWindowExW to find each matching window one by one\n // First call with hwndPrev as NULL finds the first window\n // Subsequent calls pass the previously found window handle to find the next window\n while ((hwnd = FindWindowExW(NULL, hwndPrev, NOTIFICATION_CLASS_NAME, NULL)) != NULL) {\n // Check current state\n AnimationState currentState = (AnimationState)GetPropW(hwnd, L\"AnimState\");\n \n // Stop current auto-close timer\n KillTimer(hwnd, NOTIFICATION_TIMER_ID);\n \n // If window hasn't started fading out yet, start fade-out animation\n if (currentState != ANIM_FADE_OUT) {\n SetPropW(hwnd, L\"AnimState\", (HANDLE)ANIM_FADE_OUT);\n // Start fade-out animation\n SetTimer(hwnd, ANIMATION_TIMER_ID, ANIMATION_INTERVAL, NULL);\n }\n \n // Save current window handle for next search\n hwndPrev = hwnd;\n }\n}\n"], ["/Catime/src/update_checker.c", "/**\n * @file update_checker.c\n * @brief Minimalist application update check functionality implementation\n * \n * This file implements functions for checking versions, opening browser for downloads, and deleting configuration files.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/language.h\"\n#include \"../include/dialog_language.h\"\n#include \"../resource/resource.h\"\n\n#pragma comment(lib, \"wininet.lib\")\n\n// Update source URL\n#define GITHUB_API_URL \"https://api.github.com/repos/vladelaina/Catime/releases/latest\"\n#define USER_AGENT \"Catime Update Checker\"\n\n// Version information structure definition\ntypedef struct {\n const char* currentVersion;\n const char* latestVersion;\n const char* downloadUrl;\n} UpdateVersionInfo;\n\n// Function declarations\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\n\n/**\n * @brief Compare version numbers\n * @param version1 First version string\n * @param version2 Second version string\n * @return Returns 1 if version1 > version2, 0 if equal, -1 if version1 < version2\n */\nint CompareVersions(const char* version1, const char* version2) {\n LOG_DEBUG(\"Comparing versions: '%s' vs '%s'\", version1, version2);\n \n int major1, minor1, patch1;\n int major2, minor2, patch2;\n \n // Parse version numbers\n sscanf(version1, \"%d.%d.%d\", &major1, &minor1, &patch1);\n sscanf(version2, \"%d.%d.%d\", &major2, &minor2, &patch2);\n \n LOG_DEBUG(\"Parsed version1: %d.%d.%d, version2: %d.%d.%d\", major1, minor1, patch1, major2, minor2, patch2);\n \n // Compare major version\n if (major1 > major2) return 1;\n if (major1 < major2) return -1;\n \n // Compare minor version\n if (minor1 > minor2) return 1;\n if (minor1 < minor2) return -1;\n \n // Compare patch version\n if (patch1 > patch2) return 1;\n if (patch1 < patch2) return -1;\n \n return 0;\n}\n\n/**\n * @brief Parse JSON response to get latest version and download URL\n */\nBOOL ParseLatestVersionFromJson(const char* jsonResponse, char* latestVersion, size_t maxLen, \n char* downloadUrl, size_t urlMaxLen) {\n LOG_DEBUG(\"Starting to parse JSON response, extracting version information\");\n \n // Find version number\n const char* tagNamePos = strstr(jsonResponse, \"\\\"tag_name\\\":\");\n if (!tagNamePos) {\n LOG_ERROR(\"JSON parsing failed: tag_name field not found\");\n return FALSE;\n }\n \n const char* firstQuote = strchr(tagNamePos + 11, '\\\"');\n if (!firstQuote) return FALSE;\n \n const char* secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy version number\n size_t versionLen = secondQuote - (firstQuote + 1);\n if (versionLen >= maxLen) versionLen = maxLen - 1;\n \n strncpy(latestVersion, firstQuote + 1, versionLen);\n latestVersion[versionLen] = '\\0';\n \n // If version starts with 'v', remove it\n if (latestVersion[0] == 'v' || latestVersion[0] == 'V') {\n memmove(latestVersion, latestVersion + 1, versionLen);\n }\n \n // Find download URL\n const char* downloadUrlPos = strstr(jsonResponse, \"\\\"browser_download_url\\\":\");\n if (!downloadUrlPos) {\n LOG_ERROR(\"JSON parsing failed: browser_download_url field not found\");\n return FALSE;\n }\n \n firstQuote = strchr(downloadUrlPos + 22, '\\\"');\n if (!firstQuote) return FALSE;\n \n secondQuote = strchr(firstQuote + 1, '\\\"');\n if (!secondQuote) return FALSE;\n \n // Copy download URL\n size_t urlLen = secondQuote - (firstQuote + 1);\n if (urlLen >= urlMaxLen) urlLen = urlMaxLen - 1;\n \n strncpy(downloadUrl, firstQuote + 1, urlLen);\n downloadUrl[urlLen] = '\\0';\n \n return TRUE;\n}\n\n/**\n * @brief Exit message dialog procedure\n */\nINT_PTR CALLBACK ExitMsgDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Get localized exit text\n const wchar_t* exitText = GetLocalizedString(L\"程序即将退出\", L\"The application will exit now\");\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, exitText);\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, L\"\"); // Clear version text\n \n // Set OK button text\n const wchar_t* okText = GetLocalizedString(L\"确定\", L\"OK\");\n SetDlgItemTextW(hwndDlg, IDOK, okText);\n \n // Hide Yes/No buttons, only show OK button\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_HIDE);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_SHOW);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"Catime - 更新提示\", L\"Catime - Update Notice\");\n SetWindowTextW(hwndDlg, titleText);\n \n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display custom exit message dialog\n */\nvoid ShowExitMessageDialog(HWND hwnd) {\n DialogBox(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n ExitMsgDlgProc);\n}\n\n/**\n * @brief Update dialog procedure\n */\nINT_PTR CALLBACK UpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static UpdateVersionInfo* versionInfo = NULL;\n \n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_UPDATE_DIALOG);\n \n // Save version information\n versionInfo = (UpdateVersionInfo*)lParam;\n \n // Format display text\n if (versionInfo) {\n // Convert ASCII version numbers to Unicode\n wchar_t currentVersionW[64] = {0};\n wchar_t newVersionW[64] = {0};\n \n // Convert version numbers to wide characters\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->currentVersion, -1, \n currentVersionW, sizeof(currentVersionW)/sizeof(wchar_t));\n MultiByteToWideChar(CP_UTF8, 0, versionInfo->latestVersion, -1, \n newVersionW, sizeof(newVersionW)/sizeof(wchar_t));\n \n // Use pre-formatted strings instead of trying to format ourselves\n wchar_t displayText[256];\n \n // Get localized version text (pre-formatted)\n const wchar_t* currentVersionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n const wchar_t* newVersionText = GetLocalizedString(L\"新版本:\", L\"New version:\");\n\n // Manually build formatted string\n StringCbPrintfW(displayText, sizeof(displayText),\n L\"%s %s\\n%s %s\",\n currentVersionText, currentVersionW,\n newVersionText, newVersionW);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_TEXT, displayText);\n \n // Set button text\n const wchar_t* yesText = GetLocalizedString(L\"是\", L\"Yes\");\n const wchar_t* noText = GetLocalizedString(L\"否\", L\"No\");\n \n // Explicitly set button text, not relying on dialog resource\n SetDlgItemTextW(hwndDlg, IDYES, yesText);\n SetDlgItemTextW(hwndDlg, IDNO, noText);\n \n // Set dialog title\n const wchar_t* titleText = GetLocalizedString(L\"发现新版本\", L\"Update Available\");\n SetWindowTextW(hwndDlg, titleText);\n \n // Hide exit text and OK button, show Yes/No buttons\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_EXIT_TEXT, L\"\");\n ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_SHOW);\n ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_HIDE);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDYES || LOWORD(wParam) == IDNO) {\n EndDialog(hwndDlg, LOWORD(wParam));\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDNO);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update notification dialog\n */\nint ShowUpdateNotification(HWND hwnd, const char* currentVersion, const char* latestVersion, const char* downloadUrl) {\n // Create version info structure\n UpdateVersionInfo versionInfo;\n versionInfo.currentVersion = currentVersion;\n versionInfo.latestVersion = latestVersion;\n versionInfo.downloadUrl = downloadUrl;\n \n // Display custom dialog\n return DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_DIALOG), \n hwnd, \n UpdateDlgProc, \n (LPARAM)&versionInfo);\n}\n\n/**\n * @brief Update error dialog procedure\n */\nINT_PTR CALLBACK UpdateErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Get error message text\n const wchar_t* errorMsg = (const wchar_t*)lParam;\n if (errorMsg) {\n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_UPDATE_ERROR_TEXT, errorMsg);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display update error dialog\n */\nvoid ShowUpdateErrorDialog(HWND hwnd, const wchar_t* errorMsg) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_UPDATE_ERROR_DIALOG), \n hwnd, \n UpdateErrorDlgProc, \n (LPARAM)errorMsg);\n}\n\n/**\n * @brief No update required dialog procedure\n */\nINT_PTR CALLBACK NoUpdateDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n // Apply dialog multilingual support\n ApplyDialogLanguage(hwndDlg, IDD_NO_UPDATE_DIALOG);\n \n // Get current version information\n const char* currentVersion = (const char*)lParam;\n if (currentVersion) {\n // Get localized basic text\n const wchar_t* baseText = GetDialogLocalizedString(IDD_NO_UPDATE_DIALOG, IDC_NO_UPDATE_TEXT);\n if (!baseText) {\n // If localized text not found, use default text\n baseText = L\"You are already using the latest version!\";\n }\n \n // Get localized \"Current version\" text\n const wchar_t* versionText = GetLocalizedString(L\"当前版本:\", L\"Current version:\");\n \n // Create complete message including version number\n wchar_t fullMessage[256];\n StringCbPrintfW(fullMessage, sizeof(fullMessage),\n L\"%s\\n%s %hs\", baseText, versionText, currentVersion);\n \n // Set dialog text\n SetDlgItemTextW(hwndDlg, IDC_NO_UPDATE_TEXT, fullMessage);\n }\n return TRUE;\n }\n \n case WM_COMMAND:\n if (LOWORD(wParam) == IDOK) {\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n }\n break;\n \n case WM_CLOSE:\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Display no update required dialog\n * @param hwnd Parent window handle\n * @param currentVersion Current version number\n */\nvoid ShowNoUpdateDialog(HWND hwnd, const char* currentVersion) {\n DialogBoxParam(GetModuleHandle(NULL), \n MAKEINTRESOURCE(IDD_NO_UPDATE_DIALOG), \n hwnd, \n NoUpdateDlgProc, \n (LPARAM)currentVersion);\n}\n\n/**\n * @brief Open browser to download update and exit program\n */\nBOOL OpenBrowserForUpdateAndExit(const char* url, HWND hwnd) {\n // Open browser\n HINSTANCE hInstance = ShellExecuteA(hwnd, \"open\", url, NULL, NULL, SW_SHOWNORMAL);\n \n if ((INT_PTR)hInstance <= 32) {\n // Failed to open browser\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法打开浏览器下载更新\", L\"Could not open browser to download update\"));\n return FALSE;\n }\n \n LOG_INFO(\"Successfully opened browser, preparing to exit program\");\n \n // Prompt user\n wchar_t message[512];\n StringCbPrintfW(message, sizeof(message),\n L\"即将退出程序\");\n \n LOG_INFO(\"Sending exit message to main window\");\n // Use custom dialog to display exit message\n ShowExitMessageDialog(hwnd);\n \n // Exit program\n PostMessage(hwnd, WM_CLOSE, 0, 0);\n return TRUE;\n}\n\n/**\n * @brief General update check function\n */\nvoid CheckForUpdateInternal(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Starting update check process, silent mode: %s\", silentCheck ? \"yes\" : \"no\");\n \n // Create Internet session\n LOG_INFO(\"Attempting to create Internet session\");\n HINTERNET hInternet = InternetOpenA(USER_AGENT, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);\n if (!hInternet) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to create Internet session, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法创建Internet连接\", L\"Could not create Internet connection\"));\n }\n return;\n }\n LOG_INFO(\"Internet session created successfully\");\n \n // Connect to update API\n LOG_INFO(\"Attempting to connect to GitHub API: %s\", GITHUB_API_URL);\n HINTERNET hConnect = InternetOpenUrlA(hInternet, GITHUB_API_URL, NULL, 0, \n INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, 0);\n if (!hConnect) {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Failed to connect to GitHub API, error code: %lu, error message: %s\", errorCode, errorMsg);\n \n InternetCloseHandle(hInternet);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法连接到更新服务器\", L\"Could not connect to update server\"));\n }\n return;\n }\n LOG_INFO(\"Successfully connected to GitHub API\");\n \n // Allocate buffer\n LOG_INFO(\"Allocating memory buffer for API response\");\n char* buffer = (char*)malloc(8192);\n if (!buffer) {\n LOG_ERROR(\"Memory allocation failed, could not allocate buffer for API response\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n \n // Read response\n LOG_INFO(\"Starting to read response data from API\");\n DWORD bytesRead = 0;\n DWORD totalBytes = 0;\n size_t bufferSize = 8192;\n \n while (InternetReadFile(hConnect, buffer + totalBytes, \n bufferSize - totalBytes - 1, &bytesRead) && bytesRead > 0) {\n LOG_DEBUG(\"Read %lu bytes of data, accumulated %lu bytes\", bytesRead, totalBytes + bytesRead);\n totalBytes += bytesRead;\n if (totalBytes >= bufferSize - 256) {\n size_t newSize = bufferSize * 2;\n char* newBuffer = (char*)realloc(buffer, newSize);\n if (!newBuffer) {\n // Fix: If realloc fails, free the original buffer and abort\n LOG_ERROR(\"Failed to reallocate buffer, current size: %zu bytes\", bufferSize);\n free(buffer);\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n return;\n }\n LOG_DEBUG(\"Buffer expanded, new size: %zu bytes\", newSize);\n buffer = newBuffer;\n bufferSize = newSize;\n }\n }\n \n buffer[totalBytes] = '\\0';\n LOG_INFO(\"Successfully read API response, total %lu bytes of data\", totalBytes);\n \n // Close connection\n LOG_INFO(\"Closing Internet connection\");\n InternetCloseHandle(hConnect);\n InternetCloseHandle(hInternet);\n \n // Parse version and download URL\n LOG_INFO(\"Starting to parse API response, extracting version info and download URL\");\n char latestVersion[32] = {0};\n char downloadUrl[256] = {0};\n if (!ParseLatestVersionFromJson(buffer, latestVersion, sizeof(latestVersion), \n downloadUrl, sizeof(downloadUrl))) {\n LOG_ERROR(\"Failed to parse version information, response may not be valid JSON format\");\n free(buffer);\n if (!silentCheck) {\n ShowUpdateErrorDialog(hwnd, GetLocalizedString(L\"无法解析版本信息\", L\"Could not parse version information\"));\n }\n return;\n }\n LOG_INFO(\"Successfully parsed version information, GitHub latest version: %s, download URL: %s\", latestVersion, downloadUrl);\n \n free(buffer);\n \n // Get current version\n const char* currentVersion = CATIME_VERSION;\n LOG_INFO(\"Current application version: %s\", currentVersion);\n \n // Compare versions\n LOG_INFO(\"Comparing version numbers: current version %s vs. latest version %s\", currentVersion, latestVersion);\n int versionCompare = CompareVersions(latestVersion, currentVersion);\n if (versionCompare > 0) {\n // New version available\n LOG_INFO(\"New version found! Current: %s, Available update: %s\", currentVersion, latestVersion);\n int response = ShowUpdateNotification(hwnd, currentVersion, latestVersion, downloadUrl);\n LOG_INFO(\"Update prompt dialog result: %s\", response == IDYES ? \"User agreed to update\" : \"User declined update\");\n \n if (response == IDYES) {\n LOG_INFO(\"User chose to update now, preparing to open browser and exit program\");\n OpenBrowserForUpdateAndExit(downloadUrl, hwnd);\n }\n } else if (!silentCheck) {\n // Already using latest version\n LOG_INFO(\"Current version %s is already the latest, no update needed\", currentVersion);\n \n // Use localized strings instead of building complete message\n ShowNoUpdateDialog(hwnd, currentVersion);\n } else {\n LOG_INFO(\"Silent check mode: Current version %s is already the latest, no prompt shown\", currentVersion);\n }\n \n LOG_INFO(\"Update check process complete\");\n}\n\n/**\n * @brief Check for application updates\n */\nvoid CheckForUpdate(HWND hwnd) {\n CheckForUpdateInternal(hwnd, FALSE);\n}\n\n/**\n * @brief Silently check for application updates\n */\nvoid CheckForUpdateSilent(HWND hwnd, BOOL silentCheck) {\n CheckForUpdateInternal(hwnd, silentCheck);\n} \n"], ["/Catime/src/color.c", "/**\n * @file color.c\n * @brief Color processing functionality implementation\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/color.h\"\n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/dialog_procedure.h\"\n\nPredefinedColor* COLOR_OPTIONS = NULL;\nsize_t COLOR_OPTIONS_COUNT = 0;\nchar PREVIEW_COLOR[10] = \"\";\nBOOL IS_COLOR_PREVIEWING = FALSE;\nchar CLOCK_TEXT_COLOR[10] = \"#FFFFFF\";\n\nvoid GetConfigPath(char* path, size_t size);\nvoid CreateDefaultConfig(const char* config_path);\nvoid ReadConfig(void);\nvoid WriteConfig(const char* config_path);\nvoid replaceBlackColor(const char* color, char* output, size_t output_size);\n\nstatic const CSSColor CSS_COLORS[] = {\n {\"white\", \"#FFFFFF\"},\n {\"black\", \"#000000\"},\n {\"red\", \"#FF0000\"},\n {\"lime\", \"#00FF00\"},\n {\"blue\", \"#0000FF\"},\n {\"yellow\", \"#FFFF00\"},\n {\"cyan\", \"#00FFFF\"},\n {\"magenta\", \"#FF00FF\"},\n {\"silver\", \"#C0C0C0\"},\n {\"gray\", \"#808080\"},\n {\"maroon\", \"#800000\"},\n {\"olive\", \"#808000\"},\n {\"green\", \"#008000\"},\n {\"purple\", \"#800080\"},\n {\"teal\", \"#008080\"},\n {\"navy\", \"#000080\"},\n {\"orange\", \"#FFA500\"},\n {\"pink\", \"#FFC0CB\"},\n {\"brown\", \"#A52A2A\"},\n {\"violet\", \"#EE82EE\"},\n {\"indigo\", \"#4B0082\"},\n {\"gold\", \"#FFD700\"},\n {\"coral\", \"#FF7F50\"},\n {\"salmon\", \"#FA8072\"},\n {\"khaki\", \"#F0E68C\"},\n {\"plum\", \"#DDA0DD\"},\n {\"azure\", \"#F0FFFF\"},\n {\"ivory\", \"#FFFFF0\"},\n {\"wheat\", \"#F5DEB3\"},\n {\"snow\", \"#FFFAFA\"}\n};\n\n#define CSS_COLORS_COUNT (sizeof(CSS_COLORS) / sizeof(CSS_COLORS[0]))\n\nstatic const char* DEFAULT_COLOR_OPTIONS[] = {\n \"#FFFFFF\",\n \"#F9DB91\",\n \"#F4CAE0\",\n \"#FFB6C1\",\n \"#A8E7DF\",\n \"#A3CFB3\",\n \"#92CBFC\",\n \"#BDA5E7\",\n \"#9370DB\",\n \"#8C92CF\",\n \"#72A9A5\",\n \"#EB99A7\",\n \"#EB96BD\",\n \"#FFAE8B\",\n \"#FF7F50\",\n \"#CA6174\"\n};\n\n#define DEFAULT_COLOR_OPTIONS_COUNT (sizeof(DEFAULT_COLOR_OPTIONS) / sizeof(DEFAULT_COLOR_OPTIONS[0]))\n\nWNDPROC g_OldEditProc;\n\n#include \n\nCOLORREF ShowColorDialog(HWND hwnd) {\n CHOOSECOLOR cc = {0};\n static COLORREF acrCustClr[16] = {0};\n static DWORD rgbCurrent;\n\n int r, g, b;\n if (CLOCK_TEXT_COLOR[0] == '#') {\n sscanf(CLOCK_TEXT_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n } else {\n sscanf(CLOCK_TEXT_COLOR, \"%d,%d,%d\", &r, &g, &b);\n }\n rgbCurrent = RGB(r, g, b);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT && i < 16; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n if (hexColor[0] == '#') {\n sscanf(hexColor + 1, \"%02x%02x%02x\", &r, &g, &b);\n acrCustClr[i] = RGB(r, g, b);\n }\n }\n\n cc.lStructSize = sizeof(CHOOSECOLOR);\n cc.hwndOwner = hwnd;\n cc.lpCustColors = acrCustClr;\n cc.rgbResult = rgbCurrent;\n cc.Flags = CC_FULLOPEN | CC_RGBINIT | CC_ENABLEHOOK;\n cc.lpfnHook = ColorDialogHookProc;\n\n if (ChooseColor(&cc)) {\n COLORREF finalColor;\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n int r, g, b;\n sscanf(PREVIEW_COLOR + 1, \"%02x%02x%02x\", &r, &g, &b);\n finalColor = RGB(r, g, b);\n } else {\n finalColor = cc.rgbResult;\n }\n\n char tempColor[10];\n snprintf(tempColor, sizeof(tempColor), \"#%02X%02X%02X\",\n GetRValue(finalColor),\n GetGValue(finalColor),\n GetBValue(finalColor));\n\n char finalColorStr[10];\n replaceBlackColor(tempColor, finalColorStr, sizeof(finalColorStr));\n\n strncpy(CLOCK_TEXT_COLOR, finalColorStr, sizeof(CLOCK_TEXT_COLOR) - 1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR) - 1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n\n IS_COLOR_PREVIEWING = FALSE;\n\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return finalColor;\n }\n\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd);\n return (COLORREF)-1;\n}\n\nUINT_PTR CALLBACK ColorDialogHookProc(HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n static HWND hwndParent;\n static CHOOSECOLOR* pcc;\n static BOOL isColorLocked = FALSE;\n static DWORD rgbCurrent;\n static COLORREF lastCustomColors[16] = {0};\n\n switch (msg) {\n case WM_INITDIALOG:\n pcc = (CHOOSECOLOR*)lParam;\n hwndParent = pcc->hwndOwner;\n rgbCurrent = pcc->rgbResult;\n isColorLocked = FALSE;\n \n for (int i = 0; i < 16; i++) {\n lastCustomColors[i] = pcc->lpCustColors[i];\n }\n return TRUE;\n\n case WM_LBUTTONDOWN:\n case WM_RBUTTONDOWN:\n isColorLocked = !isColorLocked;\n \n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n \n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n \n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n \n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n\n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_MOUSEMOVE:\n if (!isColorLocked) {\n POINT pt;\n GetCursorPos(&pt);\n ScreenToClient(hdlg, &pt);\n\n HDC hdc = GetDC(hdlg);\n COLORREF color = GetPixel(hdc, pt.x, pt.y);\n ReleaseDC(hdlg, hdc);\n\n if (color != CLR_INVALID && color != RGB(240, 240, 240)) {\n if (pcc) {\n pcc->rgbResult = color;\n }\n\n char colorStr[20];\n sprintf(colorStr, \"#%02X%02X%02X\",\n GetRValue(color),\n GetGValue(color),\n GetBValue(color));\n\n char finalColorStr[20];\n replaceBlackColor(colorStr, finalColorStr, sizeof(finalColorStr));\n \n strncpy(PREVIEW_COLOR, finalColorStr, sizeof(PREVIEW_COLOR) - 1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR) - 1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n \n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n }\n }\n break;\n\n case WM_COMMAND:\n if (HIWORD(wParam) == BN_CLICKED) {\n switch (LOWORD(wParam)) {\n case IDOK: {\n if (IS_COLOR_PREVIEWING && PREVIEW_COLOR[0] == '#') {\n } else {\n snprintf(PREVIEW_COLOR, sizeof(PREVIEW_COLOR), \"#%02X%02X%02X\",\n GetRValue(pcc->rgbResult),\n GetGValue(pcc->rgbResult),\n GetBValue(pcc->rgbResult));\n }\n break;\n }\n \n case IDCANCEL:\n IS_COLOR_PREVIEWING = FALSE;\n InvalidateRect(hwndParent, NULL, TRUE);\n UpdateWindow(hwndParent);\n break;\n }\n }\n break;\n\n case WM_CTLCOLORBTN:\n case WM_CTLCOLOREDIT:\n case WM_CTLCOLORSTATIC:\n if (pcc) {\n BOOL colorsChanged = FALSE;\n for (int i = 0; i < 16; i++) {\n if (lastCustomColors[i] != pcc->lpCustColors[i]) {\n colorsChanged = TRUE;\n lastCustomColors[i] = pcc->lpCustColors[i];\n \n char colorStr[20];\n snprintf(colorStr, sizeof(colorStr), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n \n }\n }\n \n if (colorsChanged) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n \n ClearColorOptions();\n \n for (int i = 0; i < 16; i++) {\n if (pcc->lpCustColors[i] != 0) {\n char hexColor[10];\n snprintf(hexColor, sizeof(hexColor), \"#%02X%02X%02X\",\n GetRValue(pcc->lpCustColors[i]),\n GetGValue(pcc->lpCustColors[i]),\n GetBValue(pcc->lpCustColors[i]));\n AddColorOption(hexColor);\n }\n }\n \n WriteConfig(config_path);\n }\n }\n break;\n }\n return 0;\n}\n\nvoid InitializeDefaultLanguage(void) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n ClearColorOptions();\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n CreateDefaultConfig(config_path);\n file = fopen(config_path, \"r\");\n }\n\n if (file) {\n char line[1024];\n BOOL found_colors = FALSE;\n\n while (fgets(line, sizeof(line), file)) {\n if (strncmp(line, \"COLOR_OPTIONS=\", 13) == 0) {\n ClearColorOptions();\n\n char* colors = line + 13;\n while (*colors == '=' || *colors == ' ') {\n colors++;\n }\n\n char* newline = strchr(colors, '\\n');\n if (newline) *newline = '\\0';\n\n char* token = strtok(colors, \",\");\n while (token) {\n while (*token == ' ') token++;\n char* end = token + strlen(token) - 1;\n while (end > token && *end == ' ') {\n *end = '\\0';\n end--;\n }\n\n if (*token) {\n if (token[0] != '#') {\n char colorWithHash[10];\n snprintf(colorWithHash, sizeof(colorWithHash), \"#%s\", token);\n AddColorOption(colorWithHash);\n } else {\n AddColorOption(token);\n }\n }\n token = strtok(NULL, \",\");\n }\n found_colors = TRUE;\n break;\n }\n }\n fclose(file);\n\n if (!found_colors || COLOR_OPTIONS_COUNT == 0) {\n for (size_t i = 0; i < DEFAULT_COLOR_OPTIONS_COUNT; i++) {\n AddColorOption(DEFAULT_COLOR_OPTIONS[i]);\n }\n }\n }\n}\n\n/**\n * @brief Add color option\n */\nvoid AddColorOption(const char* hexColor) {\n if (!hexColor || !*hexColor) {\n return;\n }\n\n char normalizedColor[10];\n const char* hex = (hexColor[0] == '#') ? hexColor + 1 : hexColor;\n\n size_t len = strlen(hex);\n if (len != 6) {\n return;\n }\n\n for (int i = 0; i < 6; i++) {\n if (!isxdigit((unsigned char)hex[i])) {\n return;\n }\n }\n\n unsigned int color;\n if (sscanf(hex, \"%x\", &color) != 1) {\n return;\n }\n\n snprintf(normalizedColor, sizeof(normalizedColor), \"#%06X\", color);\n\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n if (strcasecmp(normalizedColor, COLOR_OPTIONS[i].hexColor) == 0) {\n return;\n }\n }\n\n PredefinedColor* newArray = realloc(COLOR_OPTIONS,\n (COLOR_OPTIONS_COUNT + 1) * sizeof(PredefinedColor));\n if (newArray) {\n COLOR_OPTIONS = newArray;\n COLOR_OPTIONS[COLOR_OPTIONS_COUNT].hexColor = _strdup(normalizedColor);\n COLOR_OPTIONS_COUNT++;\n }\n}\n\n/**\n * @brief Clear all color options\n */\nvoid ClearColorOptions(void) {\n if (COLOR_OPTIONS) {\n for (size_t i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n free((void*)COLOR_OPTIONS[i].hexColor);\n }\n free(COLOR_OPTIONS);\n COLOR_OPTIONS = NULL;\n COLOR_OPTIONS_COUNT = 0;\n }\n}\n\n/**\n * @brief Write color to configuration file\n */\nvoid WriteConfigColor(const char* color_input) {\n char config_path[MAX_PATH];\n GetConfigPath(config_path, MAX_PATH);\n\n FILE *file = fopen(config_path, \"r\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for reading: %s\\n\", config_path);\n return;\n }\n\n fseek(file, 0, SEEK_END);\n long file_size = ftell(file);\n fseek(file, 0, SEEK_SET);\n\n char *config_content = (char *)malloc(file_size + 1);\n if (!config_content) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n fclose(file);\n return;\n }\n fread(config_content, sizeof(char), file_size, file);\n config_content[file_size] = '\\0';\n fclose(file);\n\n char *new_config = (char *)malloc(file_size + 100);\n if (!new_config) {\n fprintf(stderr, \"Memory allocation failed!\\n\");\n free(config_content);\n return;\n }\n new_config[0] = '\\0';\n\n char *line = strtok(config_content, \"\\n\");\n while (line) {\n if (strncmp(line, \"CLOCK_TEXT_COLOR=\", 17) == 0) {\n strcat(new_config, \"CLOCK_TEXT_COLOR=\");\n strcat(new_config, color_input);\n strcat(new_config, \"\\n\");\n } else {\n strcat(new_config, line);\n strcat(new_config, \"\\n\");\n }\n line = strtok(NULL, \"\\n\");\n }\n\n free(config_content);\n\n file = fopen(config_path, \"w\");\n if (!file) {\n fprintf(stderr, \"Failed to open config file for writing: %s\\n\", config_path);\n free(new_config);\n return;\n }\n fwrite(new_config, sizeof(char), strlen(new_config), file);\n fclose(file);\n\n free(new_config);\n\n ReadConfig();\n}\n\n/**\n * @brief Normalize color format\n */\nvoid normalizeColor(const char* input, char* output, size_t output_size) {\n while (isspace(*input)) input++;\n\n char color[32];\n strncpy(color, input, sizeof(color)-1);\n color[sizeof(color)-1] = '\\0';\n for (char* p = color; *p; p++) {\n *p = tolower(*p);\n }\n\n for (size_t i = 0; i < CSS_COLORS_COUNT; i++) {\n if (strcmp(color, CSS_COLORS[i].name) == 0) {\n strncpy(output, CSS_COLORS[i].hex, output_size);\n return;\n }\n }\n\n char cleaned[32] = {0};\n int j = 0;\n for (int i = 0; color[i]; i++) {\n if (!isspace(color[i]) && color[i] != ',' && color[i] != '(' && color[i] != ')') {\n cleaned[j++] = color[i];\n }\n }\n cleaned[j] = '\\0';\n\n if (cleaned[0] == '#') {\n memmove(cleaned, cleaned + 1, strlen(cleaned));\n }\n\n if (strlen(cleaned) == 3) {\n snprintf(output, output_size, \"#%c%c%c%c%c%c\",\n cleaned[0], cleaned[0], cleaned[1], cleaned[1], cleaned[2], cleaned[2]);\n return;\n }\n\n if (strlen(cleaned) == 6 && strspn(cleaned, \"0123456789abcdefABCDEF\") == 6) {\n snprintf(output, output_size, \"#%s\", cleaned);\n return;\n }\n\n int r = -1, g = -1, b = -1;\n char* rgb_str = color;\n\n if (strncmp(rgb_str, \"rgb\", 3) == 0) {\n rgb_str += 3;\n while (*rgb_str && (*rgb_str == '(' || isspace(*rgb_str))) rgb_str++;\n }\n\n if (sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d,%d,%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d;%d;%d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d %d %d\", &r, &g, &b) == 3 ||\n sscanf(rgb_str, \"%d|%d|%d\", &r, &g, &b) == 3) {\n\n if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) {\n snprintf(output, output_size, \"#%02X%02X%02X\", r, g, b);\n return;\n }\n }\n\n strncpy(output, input, output_size);\n}\n\n/**\n * @brief Check if color is valid\n */\nBOOL isValidColor(const char* input) {\n if (!input || !*input) return FALSE;\n\n char normalized[32];\n normalizeColor(input, normalized, sizeof(normalized));\n\n if (normalized[0] != '#' || strlen(normalized) != 7) {\n return FALSE;\n }\n\n for (int i = 1; i < 7; i++) {\n if (!isxdigit((unsigned char)normalized[i])) {\n return FALSE;\n }\n }\n\n int r, g, b;\n if (sscanf(normalized + 1, \"%02x%02x%02x\", &r, &g, &b) == 3) {\n return (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255);\n }\n\n return FALSE;\n}\n\n/**\n * @brief Color edit box subclass procedure\n */\nLRESULT CALLBACK ColorEditSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_KEYDOWN:\n if (wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {\n SendMessage(hwnd, EM_SETSEL, 0, -1);\n return 0;\n }\n case WM_COMMAND:\n if (wParam == VK_RETURN) {\n HWND hwndDlg = GetParent(hwnd);\n if (hwndDlg) {\n SendMessage(hwndDlg, WM_COMMAND, CLOCK_IDC_BUTTON_OK, 0);\n return 0;\n }\n }\n break;\n\n case WM_CHAR:\n if (GetKeyState(VK_CONTROL) < 0 && (wParam == 1 || wParam == 'a' || wParam == 'A')) {\n return 0;\n }\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n }\n\n return result;\n\n case WM_PASTE:\n case WM_CUT: {\n LRESULT result = CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n\n char color[32];\n GetWindowTextA(hwnd, color, sizeof(color));\n\n char normalized[32];\n normalizeColor(color, normalized, sizeof(normalized));\n\n if (normalized[0] == '#') {\n char finalColor[32];\n replaceBlackColor(normalized, finalColor, sizeof(finalColor));\n\n strncpy(PREVIEW_COLOR, finalColor, sizeof(PREVIEW_COLOR)-1);\n PREVIEW_COLOR[sizeof(PREVIEW_COLOR)-1] = '\\0';\n IS_COLOR_PREVIEWING = TRUE;\n } else {\n IS_COLOR_PREVIEWING = FALSE;\n }\n\n HWND hwndMain = GetParent(GetParent(hwnd));\n InvalidateRect(hwndMain, NULL, TRUE);\n UpdateWindow(hwndMain);\n\n return result;\n }\n }\n\n return CallWindowProc(g_OldEditProc, hwnd, msg, wParam, lParam);\n}\n\n/**\n * @brief Color settings dialog procedure\n */\nINT_PTR CALLBACK ColorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_INITDIALOG: {\n HWND hwndEdit = GetDlgItem(hwndDlg, CLOCK_IDC_EDIT);\n if (hwndEdit) {\n g_OldEditProc = (WNDPROC)SetWindowLongPtr(hwndEdit, GWLP_WNDPROC,\n (LONG_PTR)ColorEditSubclassProc);\n\n if (CLOCK_TEXT_COLOR[0] != '\\0') {\n SetWindowTextA(hwndEdit, CLOCK_TEXT_COLOR);\n }\n }\n return TRUE;\n }\n\n case WM_COMMAND: {\n if (LOWORD(wParam) == CLOCK_IDC_BUTTON_OK) {\n char color[32];\n GetDlgItemTextA(hwndDlg, CLOCK_IDC_EDIT, color, sizeof(color));\n\n BOOL isAllSpaces = TRUE;\n for (int i = 0; color[i]; i++) {\n if (!isspace((unsigned char)color[i])) {\n isAllSpaces = FALSE;\n break;\n }\n }\n if (color[0] == '\\0' || isAllSpaces) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n\n if (isValidColor(color)) {\n char normalized_color[10];\n normalizeColor(color, normalized_color, sizeof(normalized_color));\n strncpy(CLOCK_TEXT_COLOR, normalized_color, sizeof(CLOCK_TEXT_COLOR)-1);\n CLOCK_TEXT_COLOR[sizeof(CLOCK_TEXT_COLOR)-1] = '\\0';\n\n WriteConfigColor(CLOCK_TEXT_COLOR);\n EndDialog(hwndDlg, IDOK);\n return TRUE;\n } else {\n ShowErrorDialog(hwndDlg);\n SetWindowTextA(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT), \"\");\n SetFocus(GetDlgItem(hwndDlg, CLOCK_IDC_EDIT));\n return TRUE;\n }\n } else if (LOWORD(wParam) == IDCANCEL) {\n EndDialog(hwndDlg, IDCANCEL);\n return TRUE;\n }\n break;\n }\n }\n return FALSE;\n}\n\n/**\n * @brief Replace pure black color with near-black\n */\nvoid replaceBlackColor(const char* color, char* output, size_t output_size) {\n if (color && (strcasecmp(color, \"#000000\") == 0)) {\n strncpy(output, \"#000001\", output_size);\n output[output_size - 1] = '\\0';\n } else {\n strncpy(output, color, output_size);\n output[output_size - 1] = '\\0';\n }\n}"], ["/Catime/src/log.c", "/**\n * @file log.c\n * @brief Log recording functionality implementation\n * \n * Implements logging functionality, including file writing, error code retrieval, etc.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/log.h\"\n#include \"../include/config.h\"\n#include \"../resource/resource.h\"\n\n// Add check for ARM64 macro\n#ifndef PROCESSOR_ARCHITECTURE_ARM64\n#define PROCESSOR_ARCHITECTURE_ARM64 12\n#endif\n\n// Log file path\nstatic char LOG_FILE_PATH[MAX_PATH] = {0};\nstatic FILE* logFile = NULL;\nstatic CRITICAL_SECTION logCS;\n\n// Log level string representations\nstatic const char* LOG_LEVEL_STRINGS[] = {\n \"DEBUG\",\n \"INFO\",\n \"WARNING\",\n \"ERROR\",\n \"FATAL\"\n};\n\n/**\n * @brief Get operating system version information\n * \n * Use Windows API to get operating system version, version number, build and other information\n */\nstatic void LogSystemInformation(void) {\n // Get system information\n SYSTEM_INFO si;\n GetNativeSystemInfo(&si);\n \n // Use RtlGetVersion to get system version more accurately, because GetVersionEx was changed in newer Windows versions\n typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);\n HMODULE hNtdll = GetModuleHandleW(L\"ntdll.dll\");\n \n DWORD major = 0, minor = 0, build = 0;\n BOOL isWorkstation = TRUE;\n BOOL isServer = FALSE;\n \n if (hNtdll) {\n RtlGetVersionPtr pRtlGetVersion = (RtlGetVersionPtr)GetProcAddress(hNtdll, \"RtlGetVersion\");\n if (pRtlGetVersion) {\n RTL_OSVERSIONINFOW rovi = { 0 };\n rovi.dwOSVersionInfoSize = sizeof(rovi);\n if (pRtlGetVersion(&rovi) == 0) { // STATUS_SUCCESS = 0\n major = rovi.dwMajorVersion;\n minor = rovi.dwMinorVersion;\n build = rovi.dwBuildNumber;\n }\n }\n }\n \n // If the above method fails, try the method below\n if (major == 0) {\n OSVERSIONINFOEXA osvi;\n ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA));\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA);\n \n typedef LONG (WINAPI* PRTLGETVERSION)(OSVERSIONINFOEXW*);\n PRTLGETVERSION pRtlGetVersion;\n pRtlGetVersion = (PRTLGETVERSION)GetProcAddress(GetModuleHandle(TEXT(\"ntdll.dll\")), \"RtlGetVersion\");\n \n if (pRtlGetVersion) {\n pRtlGetVersion((OSVERSIONINFOEXW*)&osvi);\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n // Finally try using GetVersionExA, although it may not be accurate\n if (GetVersionExA((OSVERSIONINFOA*)&osvi)) {\n major = osvi.dwMajorVersion;\n minor = osvi.dwMinorVersion;\n build = osvi.dwBuildNumber;\n isWorkstation = (osvi.wProductType == VER_NT_WORKSTATION);\n isServer = !isWorkstation;\n } else {\n WriteLog(LOG_LEVEL_WARNING, \"Unable to get operating system version information\");\n }\n }\n }\n \n // Detect specific Windows version\n const char* windowsVersion = \"Unknown version\";\n \n // Determine specific version based on version number\n if (major == 10) {\n if (build >= 22000) {\n windowsVersion = \"Windows 11\";\n } else {\n windowsVersion = \"Windows 10\";\n }\n } else if (major == 6) {\n if (minor == 3) {\n windowsVersion = \"Windows 8.1\";\n } else if (minor == 2) {\n windowsVersion = \"Windows 8\";\n } else if (minor == 1) {\n windowsVersion = \"Windows 7\";\n } else if (minor == 0) {\n windowsVersion = \"Windows Vista\";\n }\n } else if (major == 5) {\n if (minor == 2) {\n windowsVersion = \"Windows Server 2003\";\n if (isWorkstation && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {\n windowsVersion = \"Windows XP Professional x64\";\n }\n } else if (minor == 1) {\n windowsVersion = \"Windows XP\";\n } else if (minor == 0) {\n windowsVersion = \"Windows 2000\";\n }\n }\n \n WriteLog(LOG_LEVEL_INFO, \"Operating System: %s (%d.%d) Build %d %s\", \n windowsVersion,\n major, minor, \n build, \n isWorkstation ? \"Workstation\" : \"Server\");\n \n // CPU architecture\n const char* arch;\n switch (si.wProcessorArchitecture) {\n case PROCESSOR_ARCHITECTURE_AMD64:\n arch = \"x64 (AMD64)\";\n break;\n case PROCESSOR_ARCHITECTURE_INTEL:\n arch = \"x86 (Intel)\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM:\n arch = \"ARM\";\n break;\n case PROCESSOR_ARCHITECTURE_ARM64:\n arch = \"ARM64\";\n break;\n default:\n arch = \"Unknown\";\n break;\n }\n WriteLog(LOG_LEVEL_INFO, \"CPU Architecture: %s\", arch);\n \n // System memory information\n MEMORYSTATUSEX memInfo;\n memInfo.dwLength = sizeof(MEMORYSTATUSEX);\n if (GlobalMemoryStatusEx(&memInfo)) {\n WriteLog(LOG_LEVEL_INFO, \"Physical Memory: %.2f GB / %.2f GB (%d%% used)\", \n (memInfo.ullTotalPhys - memInfo.ullAvailPhys) / (1024.0 * 1024 * 1024), \n memInfo.ullTotalPhys / (1024.0 * 1024 * 1024),\n memInfo.dwMemoryLoad);\n }\n \n // Don't get screen resolution information as it's not accurate and not necessary for debugging\n \n // Check if UAC is enabled\n BOOL uacEnabled = FALSE;\n HANDLE hToken;\n if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {\n TOKEN_ELEVATION_TYPE elevationType;\n DWORD dwSize;\n if (GetTokenInformation(hToken, TokenElevationType, &elevationType, sizeof(elevationType), &dwSize)) {\n uacEnabled = (elevationType != TokenElevationTypeDefault);\n }\n CloseHandle(hToken);\n }\n WriteLog(LOG_LEVEL_INFO, \"UAC Status: %s\", uacEnabled ? \"Enabled\" : \"Disabled\");\n \n // Check if running as administrator\n BOOL isAdmin = FALSE;\n SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;\n PSID AdministratorsGroup;\n if (AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup)) {\n if (CheckTokenMembership(NULL, AdministratorsGroup, &isAdmin)) {\n WriteLog(LOG_LEVEL_INFO, \"Administrator Privileges: %s\", isAdmin ? \"Yes\" : \"No\");\n }\n FreeSid(AdministratorsGroup);\n }\n}\n\n/**\n * @brief Get log file path\n * \n * Build log filename based on config file path\n * \n * @param logPath Log path buffer\n * @param size Buffer size\n */\nstatic void GetLogFilePath(char* logPath, size_t size) {\n char configPath[MAX_PATH] = {0};\n \n // Get directory containing config file\n GetConfigPath(configPath, MAX_PATH);\n \n // Determine config file directory\n char* lastSeparator = strrchr(configPath, '\\\\');\n if (lastSeparator) {\n size_t dirLen = lastSeparator - configPath + 1;\n \n // Copy directory part\n strncpy(logPath, configPath, dirLen);\n \n // Use simple log filename\n _snprintf_s(logPath + dirLen, size - dirLen, _TRUNCATE, \"Catime_Logs.log\");\n } else {\n // If config directory can't be determined, use current directory\n _snprintf_s(logPath, size, _TRUNCATE, \"Catime_Logs.log\");\n }\n}\n\nBOOL InitializeLogSystem(void) {\n InitializeCriticalSection(&logCS);\n \n GetLogFilePath(LOG_FILE_PATH, MAX_PATH);\n \n // Open file in write mode each startup, which clears existing content\n logFile = fopen(LOG_FILE_PATH, \"w\");\n if (!logFile) {\n // Failed to create log file\n return FALSE;\n }\n \n // Record log system initialization information\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n // First record software version\n WriteLog(LOG_LEVEL_INFO, \"Catime Version: %s\", CATIME_VERSION);\n // Then record system environment information (before any possible errors)\n WriteLog(LOG_LEVEL_INFO, \"-----------------System Information-----------------\");\n LogSystemInformation();\n WriteLog(LOG_LEVEL_INFO, \"-----------------Application Information-----------------\");\n WriteLog(LOG_LEVEL_INFO, \"Log system initialization complete, Catime started\");\n \n return TRUE;\n}\n\nvoid WriteLog(LogLevel level, const char* format, ...) {\n if (!logFile) {\n return;\n }\n \n EnterCriticalSection(&logCS);\n \n // Get current time\n time_t now;\n struct tm local_time;\n char timeStr[32] = {0};\n \n time(&now);\n localtime_s(&local_time, &now);\n strftime(timeStr, sizeof(timeStr), \"%Y-%m-%d %H:%M:%S\", &local_time);\n \n // Write log header\n fprintf(logFile, \"[%s] [%s] \", timeStr, LOG_LEVEL_STRINGS[level]);\n \n // Format and write log content\n va_list args;\n va_start(args, format);\n vfprintf(logFile, format, args);\n va_end(args);\n \n // New line\n fprintf(logFile, \"\\n\");\n \n // Flush buffer immediately to ensure logs are saved even if program crashes\n fflush(logFile);\n \n LeaveCriticalSection(&logCS);\n}\n\nvoid GetLastErrorDescription(DWORD errorCode, char* buffer, int bufferSize) {\n if (!buffer || bufferSize <= 0) {\n return;\n }\n \n LPSTR messageBuffer = NULL;\n DWORD size = FormatMessageA(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | \n FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL,\n errorCode,\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n (LPSTR)&messageBuffer,\n 0, NULL);\n \n if (size > 0) {\n // Remove trailing newlines\n if (size >= 2 && messageBuffer[size-2] == '\\r' && messageBuffer[size-1] == '\\n') {\n messageBuffer[size-2] = '\\0';\n }\n \n strncpy_s(buffer, bufferSize, messageBuffer, _TRUNCATE);\n LocalFree(messageBuffer);\n } else {\n _snprintf_s(buffer, bufferSize, _TRUNCATE, \"Unknown error (code: %lu)\", errorCode);\n }\n}\n\n// Signal handler function - used to handle various C standard signals\nvoid SignalHandler(int signal) {\n char errorMsg[256] = {0};\n \n switch (signal) {\n case SIGFPE:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Floating point exception\");\n break;\n case SIGILL:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Illegal instruction\");\n break;\n case SIGSEGV:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Segmentation fault/memory access error\");\n break;\n case SIGTERM:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Termination signal\");\n break;\n case SIGABRT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Abnormal termination/abort\");\n break;\n case SIGINT:\n strcpy_s(errorMsg, sizeof(errorMsg), \"User interrupt\");\n break;\n default:\n strcpy_s(errorMsg, sizeof(errorMsg), \"Unknown signal\");\n break;\n }\n \n // Record exception information\n if (logFile) {\n fprintf(logFile, \"[FATAL] Fatal signal occurred: %s (signal number: %d)\\n\", \n errorMsg, signal);\n fflush(logFile);\n \n // Close log file\n fclose(logFile);\n logFile = NULL;\n }\n \n // Display error message box\n MessageBox(NULL, \"The program encountered a serious error. Please check the log file for detailed information.\", \"Fatal Error\", MB_ICONERROR | MB_OK);\n \n // Terminate program\n exit(signal);\n}\n\nvoid SetupExceptionHandler(void) {\n // Set up standard C signal handlers\n signal(SIGFPE, SignalHandler); // Floating point exception\n signal(SIGILL, SignalHandler); // Illegal instruction\n signal(SIGSEGV, SignalHandler); // Segmentation fault\n signal(SIGTERM, SignalHandler); // Termination signal\n signal(SIGABRT, SignalHandler); // Abnormal termination\n signal(SIGINT, SignalHandler); // User interrupt\n}\n\n// Call this function when program exits to clean up log resources\nvoid CleanupLogSystem(void) {\n if (logFile) {\n WriteLog(LOG_LEVEL_INFO, \"Catime exited normally\");\n WriteLog(LOG_LEVEL_INFO, \"==================================================\");\n fclose(logFile);\n logFile = NULL;\n }\n \n DeleteCriticalSection(&logCS);\n}\n"], ["/Catime/src/startup.c", "/**\n * @file startup.c\n * @brief Implementation of auto-start functionality\n * \n * This file implements the application's auto-start related functionality,\n * including checking if auto-start is enabled, creating and deleting auto-start shortcuts.\n */\n\n#include \"../include/startup.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../include/config.h\"\n#include \"../include/timer.h\"\n\n#ifndef CSIDL_STARTUP\n#define CSIDL_STARTUP 0x0007\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n/// @name External variable declarations\n/// @{\nextern BOOL CLOCK_SHOW_CURRENT_TIME;\nextern BOOL CLOCK_COUNT_UP;\nextern BOOL CLOCK_IS_PAUSED;\nextern int CLOCK_TOTAL_TIME;\nextern int countdown_elapsed_time;\nextern int countup_elapsed_time;\nextern int CLOCK_DEFAULT_START_TIME;\nextern char CLOCK_STARTUP_MODE[20];\n/// @}\n\n/**\n * @brief Check if the application is set to auto-start at system boot\n * @return BOOL Returns TRUE if auto-start is enabled, otherwise FALSE\n */\nBOOL IsAutoStartEnabled(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n return GetFileAttributesW(startupPath) != INVALID_FILE_ATTRIBUTES;\n }\n return FALSE;\n}\n\n/**\n * @brief Create auto-start shortcut\n * @return BOOL Returns TRUE if creation was successful, otherwise FALSE\n */\nBOOL CreateShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n wchar_t exePath[MAX_PATH];\n IShellLinkW* pShellLink = NULL;\n IPersistFile* pPersistFile = NULL;\n BOOL success = FALSE;\n \n GetModuleFileNameW(NULL, exePath, MAX_PATH);\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n HRESULT hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkW, (void**)&pShellLink);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->SetPath(pShellLink, exePath);\n if (SUCCEEDED(hr)) {\n hr = pShellLink->lpVtbl->QueryInterface(pShellLink,\n &IID_IPersistFile,\n (void**)&pPersistFile);\n if (SUCCEEDED(hr)) {\n hr = pPersistFile->lpVtbl->Save(pPersistFile, startupPath, TRUE);\n if (SUCCEEDED(hr)) {\n success = TRUE;\n }\n pPersistFile->lpVtbl->Release(pPersistFile);\n }\n }\n pShellLink->lpVtbl->Release(pShellLink);\n }\n }\n \n return success;\n}\n\n/**\n * @brief Delete auto-start shortcut\n * @return BOOL Returns TRUE if deletion was successful, otherwise FALSE\n */\nBOOL RemoveShortcut(void) {\n wchar_t startupPath[MAX_PATH];\n \n if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath))) {\n wcscat(startupPath, L\"\\\\Catime.lnk\");\n \n return DeleteFileW(startupPath);\n }\n return FALSE;\n}\n\n/**\n * @brief Update auto-start shortcut\n * \n * Check if auto-start is enabled, if so, delete the old shortcut and create a new one,\n * ensuring that the auto-start functionality works correctly even if the application location changes.\n * \n * @return BOOL Returns TRUE if update was successful, otherwise FALSE\n */\nBOOL UpdateStartupShortcut(void) {\n // If auto-start is already enabled\n if (IsAutoStartEnabled()) {\n // First delete the existing shortcut\n RemoveShortcut();\n // Create a new shortcut\n return CreateShortcut();\n }\n return TRUE; // Auto-start not enabled, considered successful\n}\n\n/**\n * @brief Apply startup mode settings\n * @param hwnd Window handle\n * \n * Initialize the application's display state according to the startup mode settings in the configuration file\n */\nvoid ApplyStartupMode(HWND hwnd) {\n // Read startup mode from configuration file\n char configPath[MAX_PATH];\n GetConfigPath(configPath, MAX_PATH);\n \n FILE *configFile = fopen(configPath, \"r\");\n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", CLOCK_STARTUP_MODE);\n break;\n }\n }\n fclose(configFile);\n \n // Apply startup mode\n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n // Set to count-up mode\n CLOCK_COUNT_UP = TRUE;\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n // Set to current time display mode\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_COUNT_UP = FALSE;\n \n // Start timer\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n \n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n // Set to no display mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n CLOCK_TOTAL_TIME = 0;\n countdown_elapsed_time = 0;\n \n // Stop timer\n KillTimer(hwnd, 1);\n \n } else { // Default to countdown mode \"COUNTDOWN\"\n // Set to countdown mode\n CLOCK_SHOW_CURRENT_TIME = FALSE;\n CLOCK_COUNT_UP = FALSE;\n \n // Read default countdown time\n CLOCK_TOTAL_TIME = CLOCK_DEFAULT_START_TIME;\n countdown_elapsed_time = 0;\n \n // If countdown is set, start the timer\n if (CLOCK_TOTAL_TIME > 0) {\n KillTimer(hwnd, 1);\n SetTimer(hwnd, 1, 1000, NULL);\n }\n }\n \n // Refresh display\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n"], ["/Catime/src/drawing.c", "/**\n * @file drawing.c\n * @brief Window drawing functionality implementation\n * \n * This file implements the drawing-related functionality of the application window,\n * including text rendering, color settings, and window content drawing.\n */\n\n#include \n#include \n#include \n#include \n#include \"../include/drawing.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/timer.h\"\n#include \"../include/config.h\"\n\n// Variable imported from window_procedure.c\nextern int elapsed_time;\n\n// Using window drawing related constants defined in resource.h\n\nvoid HandleWindowPaint(HWND hwnd, PAINTSTRUCT *ps) {\n static char time_text[50];\n HDC hdc = ps->hdc;\n RECT rect;\n GetClientRect(hwnd, &rect);\n\n HDC memDC = CreateCompatibleDC(hdc);\n HBITMAP memBitmap = CreateCompatibleBitmap(hdc, rect.right, rect.bottom);\n HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);\n\n SetGraphicsMode(memDC, GM_ADVANCED);\n SetBkMode(memDC, TRANSPARENT);\n SetStretchBltMode(memDC, HALFTONE);\n SetBrushOrgEx(memDC, 0, 0, NULL);\n\n // Generate display text based on different modes\n if (CLOCK_SHOW_CURRENT_TIME) {\n time_t now = time(NULL);\n struct tm *tm_info = localtime(&now);\n int hour = tm_info->tm_hour;\n \n if (!CLOCK_USE_24HOUR) {\n if (hour == 0) {\n hour = 12;\n } else if (hour > 12) {\n hour -= 12;\n }\n }\n\n if (CLOCK_SHOW_SECONDS) {\n sprintf(time_text, \"%d:%02d:%02d\", \n hour, tm_info->tm_min, tm_info->tm_sec);\n } else {\n sprintf(time_text, \"%d:%02d\", \n hour, tm_info->tm_min);\n }\n } else if (CLOCK_COUNT_UP) {\n // Count-up mode\n int hours = countup_elapsed_time / 3600;\n int minutes = (countup_elapsed_time % 3600) / 60;\n int seconds = countup_elapsed_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n } else {\n // Countdown mode\n int remaining_time = CLOCK_TOTAL_TIME - countdown_elapsed_time;\n if (remaining_time <= 0) {\n // Timeout reached, decide whether to display content based on conditions\n if (CLOCK_TOTAL_TIME == 0 && countdown_elapsed_time == 0) {\n // This is the case after sleep operation, don't display anything\n time_text[0] = '\\0';\n } else if (strcmp(CLOCK_TIMEOUT_TEXT, \"0\") == 0) {\n time_text[0] = '\\0';\n } else if (strlen(CLOCK_TIMEOUT_TEXT) > 0) {\n strncpy(time_text, CLOCK_TIMEOUT_TEXT, sizeof(time_text) - 1);\n time_text[sizeof(time_text) - 1] = '\\0';\n } else {\n time_text[0] = '\\0';\n }\n } else {\n int hours = remaining_time / 3600;\n int minutes = (remaining_time % 3600) / 60;\n int seconds = remaining_time % 60;\n\n if (hours > 0) {\n sprintf(time_text, \"%d:%02d:%02d\", hours, minutes, seconds);\n } else if (minutes > 0) {\n sprintf(time_text, \"%d:%02d\", minutes, seconds);\n } else {\n sprintf(time_text, \"%d\", seconds);\n }\n }\n }\n\n const char* fontToUse = IS_PREVIEWING ? PREVIEW_FONT_NAME : FONT_FILE_NAME;\n HFONT hFont = CreateFont(\n -CLOCK_BASE_FONT_SIZE * CLOCK_FONT_SCALE_FACTOR,\n 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,\n DEFAULT_CHARSET, OUT_TT_PRECIS,\n CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, \n VARIABLE_PITCH | FF_SWISS,\n IS_PREVIEWING ? PREVIEW_INTERNAL_NAME : FONT_INTERNAL_NAME\n );\n HFONT oldFont = (HFONT)SelectObject(memDC, hFont);\n\n SetTextAlign(memDC, TA_LEFT | TA_TOP);\n SetTextCharacterExtra(memDC, 0);\n SetMapMode(memDC, MM_TEXT);\n\n DWORD quality = SetICMMode(memDC, ICM_ON);\n SetLayout(memDC, 0);\n\n int r = 255, g = 255, b = 255;\n const char* colorToUse = IS_COLOR_PREVIEWING ? PREVIEW_COLOR : CLOCK_TEXT_COLOR;\n \n if (strlen(colorToUse) > 0) {\n if (colorToUse[0] == '#') {\n if (strlen(colorToUse) == 7) {\n sscanf(colorToUse + 1, \"%02x%02x%02x\", &r, &g, &b);\n }\n } else {\n sscanf(colorToUse, \"%d,%d,%d\", &r, &g, &b);\n }\n }\n SetTextColor(memDC, RGB(r, g, b));\n\n if (CLOCK_EDIT_MODE) {\n HBRUSH hBrush = CreateSolidBrush(RGB(20, 20, 20)); // Dark gray background\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n } else {\n HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0));\n FillRect(memDC, &rect, hBrush);\n DeleteObject(hBrush);\n }\n\n if (strlen(time_text) > 0) {\n SIZE textSize;\n GetTextExtentPoint32(memDC, time_text, strlen(time_text), &textSize);\n\n if (textSize.cx != (rect.right - rect.left) || \n textSize.cy != (rect.bottom - rect.top)) {\n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left, windowRect.top,\n textSize.cx + WINDOW_HORIZONTAL_PADDING, \n textSize.cy + WINDOW_VERTICAL_PADDING, \n SWP_NOZORDER | SWP_NOACTIVATE);\n GetClientRect(hwnd, &rect);\n }\n\n \n int x = (rect.right - textSize.cx) / 2;\n int y = (rect.bottom - textSize.cy) / 2;\n\n // If in edit mode, force white text and add outline effect\n if (CLOCK_EDIT_MODE) {\n SetTextColor(memDC, RGB(255, 255, 255));\n \n // Add black outline effect\n SetTextColor(memDC, RGB(0, 0, 0));\n TextOutA(memDC, x-1, y, time_text, strlen(time_text));\n TextOutA(memDC, x+1, y, time_text, strlen(time_text));\n TextOutA(memDC, x, y-1, time_text, strlen(time_text));\n TextOutA(memDC, x, y+1, time_text, strlen(time_text));\n \n // Set back to white for drawing text\n SetTextColor(memDC, RGB(255, 255, 255));\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n } else {\n SetTextColor(memDC, RGB(r, g, b));\n \n for (int i = 0; i < 8; i++) {\n TextOutA(memDC, x, y, time_text, strlen(time_text));\n }\n }\n }\n\n BitBlt(hdc, 0, 0, rect.right, rect.bottom, memDC, 0, 0, SRCCOPY);\n\n SelectObject(memDC, oldFont);\n DeleteObject(hFont);\n SelectObject(memDC, oldBitmap);\n DeleteObject(memBitmap);\n DeleteDC(memDC);\n}"], ["/Catime/src/main.c", "/**\n * @file main.c\n * @brief Application main entry module implementation file\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../resource/resource.h\"\n#include \"../include/language.h\"\n#include \"../include/font.h\"\n#include \"../include/color.h\"\n#include \"../include/tray.h\"\n#include \"../include/tray_menu.h\"\n#include \"../include/timer.h\"\n#include \"../include/window.h\"\n#include \"../include/startup.h\"\n#include \"../include/config.h\"\n#include \"../include/window_procedure.h\"\n#include \"../include/media.h\"\n#include \"../include/notification.h\"\n#include \"../include/async_update_checker.h\"\n#include \"../include/log.h\"\n#include \"../include/dialog_language.h\"\n#include \"../include/shortcut_checker.h\"\n\n// Required for older Windows SDK\n#ifndef CSIDL_STARTUP\n#endif\n\n#ifndef CLSID_ShellLink\nEXTERN_C const CLSID CLSID_ShellLink;\n#endif\n\n#ifndef IID_IShellLinkW\nEXTERN_C const IID IID_IShellLinkW;\n#endif\n\n// Compiler directives\n#pragma comment(lib, \"dwmapi.lib\")\n#pragma comment(lib, \"user32.lib\")\n#pragma comment(lib, \"gdi32.lib\")\n#pragma comment(lib, \"comdlg32.lib\")\n#pragma comment(lib, \"dbghelp.lib\")\n#pragma comment(lib, \"comctl32.lib\")\n\nextern void CleanupLogSystem(void);\n\nint default_countdown_time = 0;\nint CLOCK_DEFAULT_START_TIME = 300;\nint elapsed_time = 0;\nchar inputText[256] = {0};\nint message_shown = 0;\ntime_t last_config_time = 0;\nRecentFile CLOCK_RECENT_FILES[MAX_RECENT_FILES];\nint CLOCK_RECENT_FILES_COUNT = 0;\nchar CLOCK_TIMEOUT_WEBSITE_URL[MAX_PATH] = \"\";\n\nextern char CLOCK_TEXT_COLOR[10];\nextern char FONT_FILE_NAME[];\nextern char FONT_INTERNAL_NAME[];\nextern char PREVIEW_FONT_NAME[];\nextern char PREVIEW_INTERNAL_NAME[];\nextern BOOL IS_PREVIEWING;\n\nINT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);\nvoid ExitProgram(HWND hwnd);\n\n/**\n * @brief Handle application startup mode\n * @param hwnd Main window handle\n */\nstatic void HandleStartupMode(HWND hwnd) {\n LOG_INFO(\"Setting startup mode: %s\", CLOCK_STARTUP_MODE);\n \n if (strcmp(CLOCK_STARTUP_MODE, \"COUNT_UP\") == 0) {\n LOG_INFO(\"Setting to count-up mode\");\n CLOCK_COUNT_UP = TRUE;\n elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"NO_DISPLAY\") == 0) {\n LOG_INFO(\"Setting to hidden mode, window will be hidden\");\n ShowWindow(hwnd, SW_HIDE);\n KillTimer(hwnd, 1);\n elapsed_time = CLOCK_TOTAL_TIME;\n CLOCK_IS_PAUSED = TRUE;\n message_shown = TRUE;\n countdown_message_shown = TRUE;\n countup_message_shown = TRUE;\n countdown_elapsed_time = 0;\n countup_elapsed_time = 0;\n } else if (strcmp(CLOCK_STARTUP_MODE, \"SHOW_TIME\") == 0) {\n LOG_INFO(\"Setting to show current time mode\");\n CLOCK_SHOW_CURRENT_TIME = TRUE;\n CLOCK_LAST_TIME_UPDATE = 0;\n } else {\n LOG_INFO(\"Using default countdown mode\");\n }\n}\n\n/**\n * @brief Application main entry point\n */\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n // Initialize Common Controls\n InitCommonControls();\n \n // Initialize log system\n if (!InitializeLogSystem()) {\n // If log system initialization fails, continue running but without logging\n MessageBox(NULL, \"Log system initialization failed, the program will continue running but will not log.\", \"Warning\", MB_ICONWARNING);\n }\n\n // Set up exception handler\n SetupExceptionHandler();\n\n LOG_INFO(\"Catime is starting...\");\n // Initialize COM\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM initialization failed, error code: 0x%08X\", hr);\n MessageBox(NULL, \"COM initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"COM initialization successful\");\n\n // Initialize application\n LOG_INFO(\"Starting application initialization...\");\n if (!InitializeApplication(hInstance)) {\n LOG_ERROR(\"Application initialization failed\");\n MessageBox(NULL, \"Application initialization failed!\", \"Error\", MB_ICONERROR);\n return 1;\n }\n LOG_INFO(\"Application initialization successful\");\n\n // Check and create desktop shortcut (if necessary)\n LOG_INFO(\"Checking desktop shortcut...\");\n char exe_path[MAX_PATH];\n GetModuleFileNameA(NULL, exe_path, MAX_PATH);\n LOG_INFO(\"Current program path: %s\", exe_path);\n \n // Set log level to DEBUG to show detailed information\n WriteLog(LOG_LEVEL_DEBUG, \"Starting shortcut detection, checking path: %s\", exe_path);\n \n // Check if path contains WinGet identifier\n if (strstr(exe_path, \"WinGet\") != NULL) {\n WriteLog(LOG_LEVEL_DEBUG, \"Path contains WinGet keyword\");\n }\n \n // Additional test: directly test if file exists\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path))) {\n sprintf(shortcut_path, \"%s\\\\Catime.lnk\", desktop_path);\n WriteLog(LOG_LEVEL_DEBUG, \"Checking if desktop shortcut exists: %s\", shortcut_path);\n if (GetFileAttributesA(shortcut_path) == INVALID_FILE_ATTRIBUTES) {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut does not exist, need to create\");\n } else {\n WriteLog(LOG_LEVEL_DEBUG, \"Desktop shortcut already exists\");\n }\n }\n \n int shortcut_result = CheckAndCreateShortcut();\n if (shortcut_result == 0) {\n LOG_INFO(\"Desktop shortcut check completed\");\n } else {\n LOG_WARNING(\"Desktop shortcut creation failed, error code: %d\", shortcut_result);\n }\n\n // Initialize dialog multi-language support\n LOG_INFO(\"Starting dialog multi-language support initialization...\");\n if (!InitDialogLanguageSupport()) {\n LOG_WARNING(\"Dialog multi-language support initialization failed, but program will continue running\");\n }\n LOG_INFO(\"Dialog multi-language support initialization successful\");\n\n // Handle single instance\n LOG_INFO(\"Checking if another instance is running...\");\n HANDLE hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n DWORD mutexError = GetLastError();\n \n if (mutexError == ERROR_ALREADY_EXISTS) {\n LOG_INFO(\"Detected another instance is running, trying to close that instance\");\n HWND hwndExisting = FindWindow(\"CatimeWindow\", \"Catime\");\n if (hwndExisting) {\n // Close existing window instance\n LOG_INFO(\"Sending close message to existing instance\");\n SendMessage(hwndExisting, WM_CLOSE, 0, 0);\n // Wait for old instance to close\n Sleep(200);\n } else {\n LOG_WARNING(\"Could not find window handle of existing instance, but mutex exists\");\n }\n // Release old mutex\n ReleaseMutex(hMutex);\n CloseHandle(hMutex);\n \n // Create new mutex\n LOG_INFO(\"Creating new mutex\");\n hMutex = CreateMutex(NULL, TRUE, \"CatimeMutex\");\n if (GetLastError() == ERROR_ALREADY_EXISTS) {\n LOG_WARNING(\"Still have conflict after creating new mutex, possible race condition\");\n }\n }\n Sleep(50);\n\n // Create main window\n LOG_INFO(\"Starting main window creation...\");\n HWND hwnd = CreateMainWindow(hInstance, nCmdShow);\n if (!hwnd) {\n LOG_ERROR(\"Main window creation failed\");\n MessageBox(NULL, \"Window Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Main window creation successful, handle: 0x%p\", hwnd);\n\n // Set timer\n LOG_INFO(\"Setting main timer...\");\n if (SetTimer(hwnd, 1, 1000, NULL) == 0) {\n DWORD timerError = GetLastError();\n LOG_ERROR(\"Timer creation failed, error code: %lu\", timerError);\n MessageBox(NULL, \"Timer Creation Failed!\", \"Error\", MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n LOG_INFO(\"Timer set successfully\");\n\n // Handle startup mode\n LOG_INFO(\"Handling startup mode: %s\", CLOCK_STARTUP_MODE);\n HandleStartupMode(hwnd);\n \n // Automatic update check code has been removed\n\n // Message loop\n LOG_INFO(\"Entering main message loop\");\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0) > 0) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n // Clean up resources\n LOG_INFO(\"Program preparing to exit, starting resource cleanup\");\n \n // Clean up update check thread resources\n LOG_INFO(\"Preparing to clean up update check thread resources\");\n CleanupUpdateThread();\n \n CloseHandle(hMutex);\n CoUninitialize();\n \n // Close log system\n CleanupLogSystem();\n \n return (int)msg.wParam;\n // If execution reaches here, the program has exited normally\n}\n"], ["/Catime/src/shortcut_checker.c", "/**\n * @file shortcut_checker.c\n * @brief Implementation of desktop shortcut detection and creation\n *\n * Detects if the program is installed from the App Store or WinGet,\n * and creates a desktop shortcut when necessary.\n */\n\n#include \"../include/shortcut_checker.h\"\n#include \"../include/config.h\"\n#include \"../include/log.h\" // Include log header\n#include // For printf debug output\n#include \n#include \n#include \n#include \n#include \n#include \n\n// Import required COM interfaces\n#include \n\n// We don't need to manually define IID_IShellLinkA, it's already defined in system headers\n\n/**\n * @brief Check if a string starts with a specified prefix\n * \n * @param str The string to check\n * @param prefix The prefix string\n * @return bool true if the string starts with the specified prefix, false otherwise\n */\nstatic bool StartsWith(const char* str, const char* prefix) {\n size_t prefix_len = strlen(prefix);\n size_t str_len = strlen(str);\n \n if (str_len < prefix_len) {\n return false;\n }\n \n return strncmp(str, prefix, prefix_len) == 0;\n}\n\n/**\n * @brief Check if a string contains a specified substring\n * \n * @param str The string to check\n * @param substring The substring\n * @return bool true if the string contains the specified substring, false otherwise\n */\nstatic bool Contains(const char* str, const char* substring) {\n return strstr(str, substring) != NULL;\n}\n\n/**\n * @brief Check if the program is installed from the App Store or WinGet\n * \n * @param exe_path Buffer to output the program path\n * @param path_size Buffer size\n * @return bool true if installed from the App Store or WinGet, false otherwise\n */\nstatic bool IsStoreOrWingetInstall(char* exe_path, size_t path_size) {\n // Get program path\n if (GetModuleFileNameA(NULL, exe_path, path_size) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n return false;\n }\n \n LOG_DEBUG(\"Checking program path: %s\", exe_path);\n \n // Check if it's an App Store installation path (starts with C:\\Program Files\\WindowsApps)\n if (StartsWith(exe_path, \"C:\\\\Program Files\\\\WindowsApps\")) {\n LOG_DEBUG(\"Detected App Store installation path\");\n return true;\n }\n \n // Check if it's a WinGet installation path\n // 1. Regular path containing \\AppData\\Local\\Microsoft\\WinGet\\Packages\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\WinGet\\\\Packages\")) {\n LOG_DEBUG(\"Detected WinGet installation path (regular)\");\n return true;\n }\n \n // 2. Possible custom WinGet installation path (if in C:\\Users\\username\\AppData\\Local\\Microsoft\\*)\n if (Contains(exe_path, \"\\\\AppData\\\\Local\\\\Microsoft\\\\\") && Contains(exe_path, \"WinGet\")) {\n LOG_DEBUG(\"Detected possible WinGet installation path (custom)\");\n return true;\n }\n \n // Force test: When the path contains specific strings, consider it a path that needs to create shortcuts\n // This test path matches the installation path seen in user logs\n if (Contains(exe_path, \"\\\\WinGet\\\\catime.exe\")) {\n LOG_DEBUG(\"Detected specific WinGet installation path\");\n return true;\n }\n \n LOG_DEBUG(\"Not a Store or WinGet installation path\");\n return false;\n}\n\n/**\n * @brief Check if the desktop already has a shortcut and if the shortcut points to the current program\n * \n * @param exe_path Program path\n * @param shortcut_path_out If a shortcut is found, output the shortcut path\n * @param shortcut_path_size Shortcut path buffer size\n * @param target_path_out If a shortcut is found, output the shortcut target path\n * @param target_path_size Target path buffer size\n * @return int 0=shortcut not found, 1=shortcut found and points to current program, 2=shortcut found but points to another path\n */\nstatic int CheckShortcutTarget(const char* exe_path, char* shortcut_path_out, size_t shortcut_path_size, \n char* target_path_out, size_t target_path_size) {\n char desktop_path[MAX_PATH];\n char public_desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char link_target[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n WIN32_FIND_DATAA find_data;\n int result = 0;\n \n // Get user desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n LOG_DEBUG(\"User desktop path: %s\", desktop_path);\n \n // Get public desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_COMMON_DESKTOPDIRECTORY, NULL, 0, public_desktop_path);\n if (FAILED(hr)) {\n LOG_WARNING(\"Failed to get public desktop path, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_DEBUG(\"Public desktop path: %s\", public_desktop_path);\n }\n \n // First check user desktop - build complete shortcut path (Catime.lnk)\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n LOG_DEBUG(\"Checking user desktop shortcut: %s\", shortcut_path);\n \n // Check if the user desktop shortcut file exists\n bool file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n \n // If not found on user desktop, check public desktop\n if (!file_exists && SUCCEEDED(hr)) {\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", public_desktop_path);\n LOG_DEBUG(\"Checking public desktop shortcut: %s\", shortcut_path);\n \n file_exists = (GetFileAttributesA(shortcut_path) != INVALID_FILE_ATTRIBUTES);\n }\n \n // If no shortcut file is found, return 0 directly\n if (!file_exists) {\n LOG_DEBUG(\"No shortcut files found\");\n return 0;\n }\n \n // Save the found shortcut path to the output parameter\n if (shortcut_path_out && shortcut_path_size > 0) {\n strncpy(shortcut_path_out, shortcut_path, shortcut_path_size);\n shortcut_path_out[shortcut_path_size - 1] = '\\0';\n }\n \n // Found shortcut file, get its target\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return 0;\n }\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Convert to wide character\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_ACP, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Load shortcut\n hr = ppf->lpVtbl->Load(ppf, wide_path, STGM_READ);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to load shortcut, hr=0x%08X\", (unsigned int)hr);\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n return 0;\n }\n \n // Get shortcut target path\n hr = psl->lpVtbl->GetPath(psl, link_target, MAX_PATH, &find_data, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get shortcut target path, hr=0x%08X\", (unsigned int)hr);\n result = 0;\n } else {\n LOG_DEBUG(\"Shortcut target path: %s\", link_target);\n LOG_DEBUG(\"Current program path: %s\", exe_path);\n \n // Save target path to output parameter\n if (target_path_out && target_path_size > 0) {\n strncpy(target_path_out, link_target, target_path_size);\n target_path_out[target_path_size - 1] = '\\0';\n }\n \n // Check if the shortcut points to the current program\n if (_stricmp(link_target, exe_path) == 0) {\n LOG_DEBUG(\"Shortcut points to current program\");\n result = 1;\n } else {\n LOG_DEBUG(\"Shortcut points to another path\");\n result = 2;\n }\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return result;\n}\n\n/**\n * @brief Create or update desktop shortcut\n * \n * @param exe_path Program path\n * @param existing_shortcut_path Existing shortcut path, create new one if NULL\n * @return bool true for successful creation/update, false for failure\n */\nstatic bool CreateOrUpdateDesktopShortcut(const char* exe_path, const char* existing_shortcut_path) {\n char desktop_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char icon_path[MAX_PATH];\n HRESULT hr;\n IShellLinkA* psl = NULL;\n IPersistFile* ppf = NULL;\n bool success = false;\n \n // If an existing shortcut path is provided, use it; otherwise create a new shortcut on the user's desktop\n if (existing_shortcut_path && *existing_shortcut_path) {\n LOG_INFO(\"Starting to update desktop shortcut: %s pointing to: %s\", existing_shortcut_path, exe_path);\n strcpy(shortcut_path, existing_shortcut_path);\n } else {\n LOG_INFO(\"Starting to create desktop shortcut, program path: %s\", exe_path);\n \n // Get desktop path\n hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get desktop path, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n LOG_DEBUG(\"Desktop path: %s\", desktop_path);\n \n // Build complete shortcut path\n snprintf(shortcut_path, sizeof(shortcut_path), \"%s\\\\Catime.lnk\", desktop_path);\n }\n \n LOG_DEBUG(\"Shortcut path: %s\", shortcut_path);\n \n // Use program path as icon path\n strcpy(icon_path, exe_path);\n \n // Create IShellLink interface\n hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n &IID_IShellLinkA, (void**)&psl);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to create IShellLink interface, hr=0x%08X\", (unsigned int)hr);\n return false;\n }\n \n // Set target path\n hr = psl->lpVtbl->SetPath(psl, exe_path);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set shortcut target path, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Set working directory (use the directory where the executable is located)\n char work_dir[MAX_PATH];\n strcpy(work_dir, exe_path);\n char* last_slash = strrchr(work_dir, '\\\\');\n if (last_slash) {\n *last_slash = '\\0';\n }\n LOG_DEBUG(\"Working directory: %s\", work_dir);\n \n hr = psl->lpVtbl->SetWorkingDirectory(psl, work_dir);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set working directory, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set icon\n hr = psl->lpVtbl->SetIconLocation(psl, icon_path, 0);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set icon, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set description\n hr = psl->lpVtbl->SetDescription(psl, \"A very useful timer (Pomodoro Clock)\");\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to set description, hr=0x%08X\", (unsigned int)hr);\n }\n \n // Set window style (normal window)\n psl->lpVtbl->SetShowCmd(psl, SW_SHOWNORMAL);\n \n // Get IPersistFile interface\n hr = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void**)&ppf);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to get IPersistFile interface, hr=0x%08X\", (unsigned int)hr);\n psl->lpVtbl->Release(psl);\n return false;\n }\n \n // Convert to wide characters\n WCHAR wide_path[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, shortcut_path, -1, wide_path, MAX_PATH);\n \n // Save shortcut\n hr = ppf->lpVtbl->Save(ppf, wide_path, TRUE);\n if (FAILED(hr)) {\n LOG_ERROR(\"Failed to save shortcut, hr=0x%08X\", (unsigned int)hr);\n } else {\n LOG_INFO(\"Desktop shortcut %s successful: %s\", existing_shortcut_path ? \"update\" : \"creation\", shortcut_path);\n success = true;\n }\n \n // Release interfaces\n ppf->lpVtbl->Release(ppf);\n psl->lpVtbl->Release(psl);\n \n return success;\n}\n\n/**\n * @brief Check and create desktop shortcut\n * \n * All installation types will check if the desktop shortcut exists and points to the current program.\n * If the shortcut already exists but points to another program, it will be updated to the current path.\n * But only versions installed from the Windows App Store or WinGet will create a new shortcut.\n * If SHORTCUT_CHECK_DONE=TRUE is marked in the configuration file, no new shortcut will be created even if the shortcut is deleted.\n * \n * @return int 0 means no need to create/update or create/update successful, 1 means failure\n */\nint CheckAndCreateShortcut(void) {\n char exe_path[MAX_PATH];\n char config_path[MAX_PATH];\n char shortcut_path[MAX_PATH];\n char target_path[MAX_PATH];\n bool shortcut_check_done = false;\n bool isStoreInstall = false;\n \n // Initialize COM library, needed for creating shortcuts later\n HRESULT hr = CoInitialize(NULL);\n if (FAILED(hr)) {\n LOG_ERROR(\"COM library initialization failed, hr=0x%08X\", (unsigned int)hr);\n return 1;\n }\n \n LOG_DEBUG(\"Starting shortcut check\");\n \n // Read the flag from the configuration file to determine if it has been checked\n GetConfigPath(config_path, MAX_PATH);\n shortcut_check_done = IsShortcutCheckDone();\n \n LOG_DEBUG(\"Configuration path: %s, already checked: %d\", config_path, shortcut_check_done);\n \n // Get current program path\n if (GetModuleFileNameA(NULL, exe_path, MAX_PATH) == 0) {\n LOG_ERROR(\"Failed to get program path\");\n CoUninitialize();\n return 1;\n }\n LOG_DEBUG(\"Program path: %s\", exe_path);\n \n // Check if it's an App Store or WinGet installation (only affects the behavior of creating new shortcuts)\n isStoreInstall = IsStoreOrWingetInstall(exe_path, MAX_PATH);\n LOG_DEBUG(\"Is Store/WinGet installation: %d\", isStoreInstall);\n \n // Check if the shortcut exists and points to the current program\n // Return value: 0=does not exist, 1=exists and points to the current program, 2=exists but points to another path\n int shortcut_status = CheckShortcutTarget(exe_path, shortcut_path, MAX_PATH, target_path, MAX_PATH);\n \n if (shortcut_status == 0) {\n // Shortcut does not exist\n if (shortcut_check_done) {\n // If the configuration has already been marked as checked, don't create it even if there's no shortcut\n LOG_INFO(\"No shortcut found on desktop, but configuration marked as checked, not creating\");\n CoUninitialize();\n return 0;\n } else if (isStoreInstall) {\n // Only first-run Store or WinGet installations create shortcuts\n LOG_INFO(\"No shortcut found on desktop, first run of Store/WinGet installation, starting to create\");\n bool success = CreateOrUpdateDesktopShortcut(exe_path, NULL);\n \n // Mark as checked, regardless of whether creation was successful\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return success ? 0 : 1;\n } else {\n LOG_INFO(\"No shortcut found on desktop, not a Store/WinGet installation, not creating shortcut\");\n \n // Mark as checked\n SetShortcutCheckDone(true);\n \n CoUninitialize();\n return 0;\n }\n } else if (shortcut_status == 1) {\n // Shortcut exists and points to the current program, no action needed\n LOG_INFO(\"Desktop shortcut already exists and points to the current program\");\n \n // Mark as checked\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return 0;\n } else if (shortcut_status == 2) {\n // Shortcut exists but points to another program, any installation method will update it\n LOG_INFO(\"Desktop shortcut points to another path: %s, will update to: %s\", target_path, exe_path);\n bool success = CreateOrUpdateDesktopShortcut(exe_path, shortcut_path);\n \n // Mark as checked, regardless of whether the update was successful\n if (!shortcut_check_done) {\n SetShortcutCheckDone(true);\n }\n \n CoUninitialize();\n return success ? 0 : 1;\n }\n \n // Should not reach here\n LOG_ERROR(\"Unknown shortcut check status\");\n CoUninitialize();\n return 1;\n} "], ["/Catime/src/tray.c", "/**\n * @file tray.c\n * @brief System tray functionality implementation\n */\n\n#include \n#include \n#include \"../include/language.h\"\n#include \"../resource/resource.h\"\n#include \"../include/tray.h\"\n\nNOTIFYICONDATAW nid;\nUINT WM_TASKBARCREATED = 0;\n\n/**\n * @brief Register the TaskbarCreated message\n */\nvoid RegisterTaskbarCreatedMessage() {\n WM_TASKBARCREATED = RegisterWindowMessage(TEXT(\"TaskbarCreated\"));\n}\n\n/**\n * @brief Initialize the system tray icon\n * @param hwnd Window handle\n * @param hInstance Application instance handle\n */\nvoid InitTrayIcon(HWND hwnd, HINSTANCE hInstance) {\n memset(&nid, 0, sizeof(nid));\n nid.cbSize = sizeof(nid);\n nid.uID = CLOCK_ID_TRAY_APP_ICON;\n nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;\n nid.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CATIME));\n nid.hWnd = hwnd;\n nid.uCallbackMessage = CLOCK_WM_TRAYICON;\n \n wchar_t versionText[128] = {0};\n wchar_t versionWide[64] = {0};\n MultiByteToWideChar(CP_UTF8, 0, CATIME_VERSION, -1, versionWide, _countof(versionWide));\n swprintf_s(versionText, _countof(versionText), L\"Catime %s\", versionWide);\n wcscpy_s(nid.szTip, _countof(nid.szTip), versionText);\n \n Shell_NotifyIconW(NIM_ADD, &nid);\n if (WM_TASKBARCREATED == 0) {\n RegisterTaskbarCreatedMessage();\n }\n}\n\n/**\n * @brief Remove the system tray icon\n */\nvoid RemoveTrayIcon(void) {\n Shell_NotifyIconW(NIM_DELETE, &nid);\n}\n\n/**\n * @brief Display a notification in the system tray\n * @param hwnd Window handle\n * @param message Text message to display\n */\nvoid ShowTrayNotification(HWND hwnd, const char* message) {\n NOTIFYICONDATAW nid_notify = {0};\n nid_notify.cbSize = sizeof(NOTIFYICONDATAW);\n nid_notify.hWnd = hwnd;\n nid_notify.uID = CLOCK_ID_TRAY_APP_ICON;\n nid_notify.uFlags = NIF_INFO;\n nid_notify.dwInfoFlags = NIIF_NONE;\n nid_notify.uTimeout = 3000;\n \n MultiByteToWideChar(CP_UTF8, 0, message, -1, nid_notify.szInfo, sizeof(nid_notify.szInfo)/sizeof(WCHAR));\n nid_notify.szInfoTitle[0] = L'\\0';\n \n Shell_NotifyIconW(NIM_MODIFY, &nid_notify);\n}\n\n/**\n * @brief Recreate the taskbar icon\n * @param hwnd Window handle\n * @param hInstance Instance handle\n */\nvoid RecreateTaskbarIcon(HWND hwnd, HINSTANCE hInstance) {\n RemoveTrayIcon();\n InitTrayIcon(hwnd, hInstance);\n}\n\n/**\n * @brief Update the tray icon and menu\n * @param hwnd Window handle\n */\nvoid UpdateTrayIcon(HWND hwnd) {\n HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);\n RecreateTaskbarIcon(hwnd, hInstance);\n}"], ["/Catime/src/audio_player.c", "/**\n * @file audio_player.c\n * @brief Audio playback functionality handler\n */\n\n#include \n#include \n#include \n#include \"../libs/miniaudio/miniaudio.h\"\n\n#include \"config.h\"\n\nextern char NOTIFICATION_SOUND_FILE[MAX_PATH];\nextern int NOTIFICATION_SOUND_VOLUME;\n\ntypedef void (*AudioPlaybackCompleteCallback)(HWND hwnd);\n\nstatic ma_engine g_audioEngine;\nstatic ma_sound g_sound;\nstatic ma_bool32 g_engineInitialized = MA_FALSE;\nstatic ma_bool32 g_soundInitialized = MA_FALSE;\n\nstatic AudioPlaybackCompleteCallback g_audioCompleteCallback = NULL;\nstatic HWND g_audioCallbackHwnd = NULL;\nstatic UINT_PTR g_audioTimerId = 0;\n\nstatic ma_bool32 g_isPlaying = MA_FALSE;\nstatic ma_bool32 g_isPaused = MA_FALSE;\n\nstatic void CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime);\n\n/**\n * @brief Initialize audio engine\n */\nstatic BOOL InitializeAudioEngine() {\n if (g_engineInitialized) {\n return TRUE;\n }\n\n ma_result result = ma_engine_init(NULL, &g_audioEngine);\n if (result != MA_SUCCESS) {\n return FALSE;\n }\n\n g_engineInitialized = MA_TRUE;\n return TRUE;\n}\n\n/**\n * @brief Clean up audio engine resources\n */\nstatic void UninitializeAudioEngine() {\n if (g_engineInitialized) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n ma_engine_uninit(&g_audioEngine);\n g_engineInitialized = MA_FALSE;\n }\n}\n\n/**\n * @brief Check if a file exists\n */\nstatic BOOL FileExists(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2);\n\n DWORD dwAttrib = GetFileAttributesW(wFilePath);\n return (dwAttrib != INVALID_FILE_ATTRIBUTES &&\n !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));\n}\n\n/**\n * @brief Show error message dialog\n */\nstatic void ShowErrorMessage(HWND hwnd, const wchar_t* errorMsg) {\n MessageBoxW(hwnd, errorMsg, L\"Audio Playback Error\", MB_ICONERROR | MB_OK);\n}\n\n/**\n * @brief Timer callback to check if audio playback is complete\n */\nstatic void CALLBACK CheckAudioPlaybackComplete(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n if (g_engineInitialized && g_soundInitialized) {\n if (!ma_sound_is_playing(&g_sound) && !g_isPaused) {\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n } else {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n }\n}\n\n/**\n * @brief System beep playback completion callback timer function\n */\nstatic void CALLBACK SystemBeepDoneCallback(HWND hwnd, UINT message, UINT_PTR idEvent, DWORD dwTime) {\n KillTimer(hwnd, idEvent);\n g_audioTimerId = 0;\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n\n if (g_audioCompleteCallback) {\n g_audioCompleteCallback(g_audioCallbackHwnd);\n }\n}\n\n/**\n * @brief Set audio playback volume\n * @param volume Volume percentage (0-100)\n */\nvoid SetAudioVolume(int volume) {\n if (volume < 0) volume = 0;\n if (volume > 100) volume = 100;\n\n if (g_engineInitialized) {\n float volFloat = (float)volume / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volFloat);\n\n if (g_soundInitialized && g_isPlaying) {\n ma_sound_set_volume(&g_sound, volFloat);\n }\n }\n}\n\n/**\n * @brief Play audio file using miniaudio\n */\nstatic BOOL PlayAudioWithMiniaudio(HWND hwnd, const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (!g_engineInitialized) {\n if (!InitializeAudioEngine()) {\n return FALSE;\n }\n }\n\n float volume = (float)NOTIFICATION_SOUND_VOLUME / 100.0f;\n ma_engine_set_volume(&g_audioEngine, volume);\n\n if (g_soundInitialized) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n wchar_t wFilePath[MAX_PATH * 2] = {0};\n if (MultiByteToWideChar(CP_UTF8, 0, filePath, -1, wFilePath, MAX_PATH * 2) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (UTF-8->Unicode): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n wchar_t shortPath[MAX_PATH] = {0};\n DWORD shortPathLen = GetShortPathNameW(wFilePath, shortPath, MAX_PATH);\n if (shortPathLen == 0 || shortPathLen >= MAX_PATH) {\n DWORD error = GetLastError();\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Failed to get short path: %ls\\nError code: %lu\", wFilePath, error);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n\n char asciiPath[MAX_PATH] = {0};\n if (WideCharToMultiByte(CP_ACP, 0, shortPath, -1, asciiPath, MAX_PATH, NULL, NULL) == 0) {\n DWORD error = GetLastError();\n wchar_t errorMsg[256];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Path conversion error (Short Path->ASCII): %lu\", error);\n ShowErrorMessage(hwnd, errorMsg);\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n return FALSE;\n }\n\n ma_result result = ma_sound_init_from_file(&g_audioEngine, asciiPath, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n char utf8Path[MAX_PATH * 4] = {0};\n WideCharToMultiByte(CP_UTF8, 0, wFilePath, -1, utf8Path, sizeof(utf8Path), NULL, NULL);\n\n result = ma_sound_init_from_file(&g_audioEngine, utf8Path, 0, NULL, NULL, &g_sound);\n\n if (result != MA_SUCCESS) {\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n wchar_t errorMsg[512];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Unable to load audio file: %ls\\nError code: %d\", wFilePath, result);\n ShowErrorMessage(hwnd, errorMsg);\n return FALSE;\n }\n }\n\n g_soundInitialized = MA_TRUE;\n\n if (ma_sound_start(&g_sound) != MA_SUCCESS) {\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n\n if (PlaySoundW(wFilePath, NULL, SND_FILENAME | SND_ASYNC)) {\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1002, 3000, (TIMERPROC)SystemBeepDoneCallback);\n g_isPlaying = MA_TRUE;\n return TRUE;\n }\n\n ShowErrorMessage(hwnd, L\"Cannot start audio playback\");\n return FALSE;\n }\n\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1001, 500, (TIMERPROC)CheckAudioPlaybackComplete);\n\n return TRUE;\n}\n\n/**\n * @brief Validate if file path is legal\n */\nstatic BOOL IsValidFilePath(const char* filePath) {\n if (!filePath || filePath[0] == '\\0') return FALSE;\n\n if (strchr(filePath, '=') != NULL) return FALSE;\n\n if (strlen(filePath) >= MAX_PATH) return FALSE;\n\n return TRUE;\n}\n\n/**\n * @brief Clean up audio resources\n */\nvoid CleanupAudioResources(void) {\n PlaySound(NULL, NULL, SND_PURGE);\n\n if (g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n ma_sound_uninit(&g_sound);\n g_soundInitialized = MA_FALSE;\n }\n\n if (g_audioTimerId != 0 && g_audioCallbackHwnd != NULL) {\n KillTimer(g_audioCallbackHwnd, g_audioTimerId);\n g_audioTimerId = 0;\n }\n\n g_isPlaying = MA_FALSE;\n g_isPaused = MA_FALSE;\n}\n\n/**\n * @brief Set audio playback completion callback function\n */\nvoid SetAudioPlaybackCompleteCallback(HWND hwnd, AudioPlaybackCompleteCallback callback) {\n g_audioCallbackHwnd = hwnd;\n g_audioCompleteCallback = callback;\n}\n\n/**\n * @brief Play notification audio\n */\nBOOL PlayNotificationSound(HWND hwnd) {\n CleanupAudioResources();\n\n g_audioCallbackHwnd = hwnd;\n\n if (NOTIFICATION_SOUND_FILE[0] != '\\0') {\n if (strcmp(NOTIFICATION_SOUND_FILE, \"SYSTEM_BEEP\") == 0) {\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (!IsValidFilePath(NOTIFICATION_SOUND_FILE)) {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Invalid audio file path:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n\n if (FileExists(NOTIFICATION_SOUND_FILE)) {\n if (PlayAudioWithMiniaudio(hwnd, NOTIFICATION_SOUND_FILE)) {\n return TRUE;\n }\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n } else {\n wchar_t errorMsg[MAX_PATH + 64];\n StringCbPrintfW(errorMsg, sizeof(errorMsg), L\"Cannot find the configured audio file:\\n%hs\", NOTIFICATION_SOUND_FILE);\n ShowErrorMessage(hwnd, errorMsg);\n\n MessageBeep(MB_OK);\n g_isPlaying = MA_TRUE;\n\n if (g_audioTimerId != 0) {\n KillTimer(hwnd, g_audioTimerId);\n }\n g_audioTimerId = SetTimer(hwnd, 1003, 500, (TIMERPROC)SystemBeepDoneCallback);\n\n return TRUE;\n }\n }\n\n return TRUE;\n}\n\n/**\n * @brief Pause currently playing notification audio\n */\nBOOL PauseNotificationSound(void) {\n if (g_isPlaying && !g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_stop(&g_sound);\n g_isPaused = MA_TRUE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Resume previously paused notification audio\n */\nBOOL ResumeNotificationSound(void) {\n if (g_isPlaying && g_isPaused && g_engineInitialized && g_soundInitialized) {\n ma_sound_start(&g_sound);\n g_isPaused = MA_FALSE;\n return TRUE;\n }\n return FALSE;\n}\n\n/**\n * @brief Stop playing notification audio\n */\nvoid StopNotificationSound(void) {\n CleanupAudioResources();\n}"], ["/Catime/src/drag_scale.c", "/**\n * @file drag_scale.c\n * @brief Window dragging and scaling functionality implementation\n * \n * This file implements the dragging and scaling functionality of the application window,\n * including mouse dragging of the window and mouse wheel scaling of the window.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n\n// Add variable to record the topmost state before edit mode\nBOOL PREVIOUS_TOPMOST_STATE = FALSE;\n\nvoid StartDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_IS_DRAGGING = TRUE;\n SetCapture(hwnd);\n GetCursorPos(&CLOCK_LAST_MOUSE_POS);\n }\n}\n\nvoid StartEditMode(HWND hwnd) {\n // Record current topmost state\n PREVIOUS_TOPMOST_STATE = CLOCK_WINDOW_TOPMOST;\n \n // If currently not in topmost state, set to topmost\n if (!CLOCK_WINDOW_TOPMOST) {\n SetWindowTopmost(hwnd, TRUE);\n }\n \n // Then enable edit mode\n CLOCK_EDIT_MODE = TRUE;\n \n // Apply blur effect\n SetBlurBehind(hwnd, TRUE);\n \n // Disable click-through\n SetClickThrough(hwnd, FALSE);\n \n // Ensure mouse cursor is default arrow\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n}\n\nvoid EndEditMode(HWND hwnd) {\n if (CLOCK_EDIT_MODE) {\n CLOCK_EDIT_MODE = FALSE;\n \n // Remove blur effect\n SetBlurBehind(hwnd, FALSE);\n SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 255, LWA_COLORKEY);\n \n // Restore click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // If previously not in topmost state, restore to non-topmost\n if (!PREVIOUS_TOPMOST_STATE) {\n SetWindowTopmost(hwnd, FALSE);\n }\n \n // Refresh window, add immediate update\n InvalidateRect(hwnd, NULL, TRUE);\n UpdateWindow(hwnd); // Ensure immediate refresh\n }\n}\n\nvoid EndDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n CLOCK_IS_DRAGGING = FALSE;\n ReleaseCapture();\n // In edit mode, don't force window to stay on screen, allow dragging out\n AdjustWindowPosition(hwnd, FALSE);\n InvalidateRect(hwnd, NULL, TRUE);\n }\n}\n\nBOOL HandleDragWindow(HWND hwnd) {\n if (CLOCK_EDIT_MODE && CLOCK_IS_DRAGGING) {\n POINT currentPos;\n GetCursorPos(¤tPos);\n \n int deltaX = currentPos.x - CLOCK_LAST_MOUSE_POS.x;\n int deltaY = currentPos.y - CLOCK_LAST_MOUSE_POS.y;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n \n SetWindowPos(hwnd, NULL,\n windowRect.left + deltaX,\n windowRect.top + deltaY,\n windowRect.right - windowRect.left, \n windowRect.bottom - windowRect.top, \n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW \n );\n \n CLOCK_LAST_MOUSE_POS = currentPos;\n \n UpdateWindow(hwnd);\n \n // Update position variables and save settings\n CLOCK_WINDOW_POS_X = windowRect.left + deltaX;\n CLOCK_WINDOW_POS_Y = windowRect.top + deltaY;\n SaveWindowSettings(hwnd);\n \n return TRUE;\n }\n return FALSE;\n}\n\nBOOL HandleScaleWindow(HWND hwnd, int delta) {\n if (CLOCK_EDIT_MODE) {\n float old_scale = CLOCK_FONT_SCALE_FACTOR;\n \n RECT windowRect;\n GetWindowRect(hwnd, &windowRect);\n int oldWidth = windowRect.right - windowRect.left;\n int oldHeight = windowRect.bottom - windowRect.top;\n \n float scaleFactor = 1.1f;\n if (delta > 0) {\n CLOCK_FONT_SCALE_FACTOR *= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n } else {\n CLOCK_FONT_SCALE_FACTOR /= scaleFactor;\n CLOCK_WINDOW_SCALE = CLOCK_FONT_SCALE_FACTOR;\n }\n \n // Maintain scale range limits\n if (CLOCK_FONT_SCALE_FACTOR < MIN_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MIN_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MIN_SCALE_FACTOR;\n }\n if (CLOCK_FONT_SCALE_FACTOR > MAX_SCALE_FACTOR) {\n CLOCK_FONT_SCALE_FACTOR = MAX_SCALE_FACTOR;\n CLOCK_WINDOW_SCALE = MAX_SCALE_FACTOR;\n }\n \n if (old_scale != CLOCK_FONT_SCALE_FACTOR) {\n // Calculate new dimensions\n int newWidth = (int)(oldWidth * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n int newHeight = (int)(oldHeight * (CLOCK_FONT_SCALE_FACTOR / old_scale));\n \n // Keep window center position unchanged\n int newX = windowRect.left + (oldWidth - newWidth)/2;\n int newY = windowRect.top + (oldHeight - newHeight)/2;\n \n SetWindowPos(hwnd, NULL, \n newX, newY,\n newWidth, newHeight,\n SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);\n \n // Trigger redraw\n InvalidateRect(hwnd, NULL, FALSE);\n UpdateWindow(hwnd);\n \n // Save settings\n SaveWindowSettings(hwnd);\n return TRUE;\n }\n }\n return FALSE;\n}"], ["/Catime/src/async_update_checker.c", "/**\n * @file async_update_checker.c\n * @brief Asynchronous application update checking functionality\n */\n\n#include \n#include \n#include \"../include/async_update_checker.h\"\n#include \"../include/update_checker.h\"\n#include \"../include/log.h\"\n\ntypedef struct {\n HWND hwnd;\n BOOL silentCheck;\n} UpdateThreadParams;\n\nstatic HANDLE g_hUpdateThread = NULL;\nstatic BOOL g_bUpdateThreadRunning = FALSE;\n\n/**\n * @brief Clean up update check thread resources\n */\nvoid CleanupUpdateThread() {\n LOG_INFO(\"Cleaning up update check thread resources\");\n if (g_hUpdateThread != NULL) {\n DWORD waitResult = WaitForSingleObject(g_hUpdateThread, 1000);\n if (waitResult == WAIT_TIMEOUT) {\n LOG_WARNING(\"Wait for thread end timed out, forcibly closing thread handle\");\n } else if (waitResult == WAIT_OBJECT_0) {\n LOG_INFO(\"Thread has ended normally\");\n } else {\n LOG_WARNING(\"Wait for thread returned unexpected result: %lu\", waitResult);\n }\n\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n g_bUpdateThreadRunning = FALSE;\n LOG_INFO(\"Thread resources have been cleaned up\");\n } else {\n LOG_INFO(\"Update check thread not running, no cleanup needed\");\n }\n}\n\n/**\n * @brief Update check thread function\n * @param param Thread parameters\n */\nunsigned __stdcall UpdateCheckThreadProc(void* param) {\n LOG_INFO(\"Update check thread started\");\n\n UpdateThreadParams* threadParams = (UpdateThreadParams*)param;\n if (!threadParams) {\n LOG_ERROR(\"Thread parameters are null, cannot perform update check\");\n g_bUpdateThreadRunning = FALSE;\n _endthreadex(1);\n return 1;\n }\n\n HWND hwnd = threadParams->hwnd;\n BOOL silentCheck = threadParams->silentCheck;\n\n LOG_INFO(\"Thread parameters parsed successfully, window handle: 0x%p, silent check mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n\n free(threadParams);\n LOG_INFO(\"Thread parameter memory freed\");\n\n LOG_INFO(\"Starting update check\");\n CheckForUpdateSilent(hwnd, silentCheck);\n LOG_INFO(\"Update check completed\");\n\n g_bUpdateThreadRunning = FALSE;\n\n _endthreadex(0);\n return 0;\n}\n\n/**\n * @brief Check for application updates asynchronously\n * @param hwnd Window handle\n * @param silentCheck Whether to perform a silent check\n */\nvoid CheckForUpdateAsync(HWND hwnd, BOOL silentCheck) {\n LOG_INFO(\"Asynchronous update check requested, window handle: 0x%p, silent mode: %s\",\n hwnd, silentCheck ? \"yes\" : \"no\");\n\n if (g_bUpdateThreadRunning) {\n LOG_INFO(\"Update check thread already running, skipping this check request\");\n return;\n }\n\n if (g_hUpdateThread != NULL) {\n LOG_INFO(\"Found old thread handle, cleaning up...\");\n CloseHandle(g_hUpdateThread);\n g_hUpdateThread = NULL;\n LOG_INFO(\"Old thread handle closed\");\n }\n\n LOG_INFO(\"Allocating memory for thread parameters\");\n UpdateThreadParams* threadParams = (UpdateThreadParams*)malloc(sizeof(UpdateThreadParams));\n if (!threadParams) {\n LOG_ERROR(\"Thread parameter memory allocation failed, cannot start update check thread\");\n return;\n }\n\n threadParams->hwnd = hwnd;\n threadParams->silentCheck = silentCheck;\n LOG_INFO(\"Thread parameters set up\");\n\n g_bUpdateThreadRunning = TRUE;\n\n LOG_INFO(\"Preparing to create update check thread\");\n HANDLE hThread = (HANDLE)_beginthreadex(\n NULL,\n 0,\n UpdateCheckThreadProc,\n threadParams,\n 0,\n NULL\n );\n\n if (hThread) {\n LOG_INFO(\"Update check thread created successfully, thread handle: 0x%p\", hThread);\n g_hUpdateThread = hThread;\n } else {\n DWORD errorCode = GetLastError();\n char errorMsg[256] = {0};\n GetLastErrorDescription(errorCode, errorMsg, sizeof(errorMsg));\n LOG_ERROR(\"Update check thread creation failed, error code: %lu, error message: %s\", errorCode, errorMsg);\n\n free(threadParams);\n g_bUpdateThreadRunning = FALSE;\n }\n}"], ["/Catime/src/window_events.c", "/**\n * @file window_events.c\n * @brief Implementation of basic window event handling\n * \n * This file implements the basic event handling functionality for the application window,\n * including window creation, destruction, resizing, and position adjustment.\n */\n\n#include \n#include \"../include/window.h\"\n#include \"../include/tray.h\"\n#include \"../include/config.h\"\n#include \"../include/drag_scale.h\"\n#include \"../include/window_events.h\"\n\n/**\n * @brief Handle window creation event\n * @param hwnd Window handle\n * @return BOOL Processing result\n */\nBOOL HandleWindowCreate(HWND hwnd) {\n HWND hwndParent = GetParent(hwnd);\n if (hwndParent != NULL) {\n EnableWindow(hwndParent, TRUE);\n }\n \n // Load window settings\n LoadWindowSettings(hwnd);\n \n // Set click-through\n SetClickThrough(hwnd, !CLOCK_EDIT_MODE);\n \n // Ensure window is in topmost state\n SetWindowTopmost(hwnd, CLOCK_WINDOW_TOPMOST);\n \n return TRUE;\n}\n\n/**\n * @brief Handle window destruction event\n * @param hwnd Window handle\n */\nvoid HandleWindowDestroy(HWND hwnd) {\n SaveWindowSettings(hwnd); // Save window settings\n KillTimer(hwnd, 1);\n RemoveTrayIcon();\n \n // Clean up update check thread\n extern void CleanupUpdateThread(void);\n CleanupUpdateThread();\n \n PostQuitMessage(0);\n}\n\n/**\n * @brief Handle window reset event\n * @param hwnd Window handle\n */\nvoid HandleWindowReset(HWND hwnd) {\n // Unconditionally apply topmost setting from configuration\n // Regardless of the current CLOCK_WINDOW_TOPMOST value, force it to TRUE and apply\n CLOCK_WINDOW_TOPMOST = TRUE;\n SetWindowTopmost(hwnd, TRUE);\n WriteConfigTopmost(\"TRUE\");\n \n // Ensure window is always visible - solves the issue of timer not being visible after reset\n ShowWindow(hwnd, SW_SHOW);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowResize(HWND hwnd, int delta) {\n return HandleScaleWindow(hwnd, delta);\n}\n\n// This function has been moved to drag_scale.c\nBOOL HandleWindowMove(HWND hwnd) {\n return HandleDragWindow(hwnd);\n}\n"], ["/Catime/src/media.c", "/**\n * @file media.c\n * @brief Media control functionality implementation\n * \n * This file implements the application's media control related functions,\n * including pause, play and other media control operations.\n */\n\n#include \n#include \"../include/media.h\"\n\n/**\n * @brief Pause media playback\n * \n * Pauses currently playing media by simulating media control key press events.\n * Includes a combination of stop and pause/play operations to ensure the media is properly paused.\n */\nvoid PauseMediaPlayback(void) {\n keybd_event(VK_MEDIA_STOP, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_STOP, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(50);\n\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, 0);\n Sleep(50);\n keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, 0);\n Sleep(100);\n}"], ["/Catime/libs/miniaudio/miniaudio.c", "#define MINIAUDIO_IMPLEMENTATION\n#include \"miniaudio.h\"\n"]], "task_instance_info": {"created_time": "2025-08-20 17:54:33", "created_task_model": "DeepSeek-R1", "function_skeleton": "void ShowColorMenu(HWND hwnd) {}", "code_description": "This code segment functions to: Construct and display a hierarchical system tray configuration menu with dynamic state management for application settings including edit mode toggling, timeout action selection, font customization, color scheme adjustment, language preferences, and help navigation."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nvoid ShowColorMenu(HWND hwnd) {\n HMENU hMenu = CreatePopupMenu();\n \n // Edit mode toggle\n AppendMenuW(hMenu, MF_STRING | (CLOCK_EDIT_MODE ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_EDIT_MODE, \n GetLocalizedString(L\"编辑模式\", L\"Edit Mode\"));\n \n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n\n // Timeout action menu\n HMENU hTimeoutMenu = CreatePopupMenu();\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_NONE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_NONE, \n GetLocalizedString(L\"无操作\", L\"No Action\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_BEEP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_BEEP, \n GetLocalizedString(L\"蜂鸣提示\", L\"Beep\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_MESSAGE, \n GetLocalizedString(L\"显示消息\", L\"Show Message\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_OPEN_FILE, \n GetLocalizedString(L\"打开文件\", L\"Open File\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_WEBSITE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_OPEN_WEBSITE, \n GetLocalizedString(L\"打开网页\", L\"Open Website\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeoutMenu, \n GetLocalizedString(L\"超时操作\", L\"Timeout Action\"));\n\n // Preset times management\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_MANAGE_PRESETS, \n GetLocalizedString(L\"预设时间管理\", L\"Manage Presets\"));\n\n // Startup mode menu\n HMENU hStartupMenu = CreatePopupMenu();\n AppendMenuW(hStartupMenu, MF_STRING | (strcmp(CLOCK_STARTUP_MODE, \"Normal\") == 0 ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_STARTUP_NORMAL, \n GetLocalizedString(L\"普通模式\", L\"Normal Mode\"));\n AppendMenuW(hStartupMenu, MF_STRING | (strcmp(CLOCK_STARTUP_MODE, \"Maximized\") == 0 ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_STARTUP_MAXIMIZED, \n GetLocalizedString(L\"最大化\", L\"Maximized\"));\n AppendMenuW(hStartupMenu, MF_STRING | (strcmp(CLOCK_STARTUP_MODE, \"Minimized\") == 0 ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_STARTUP_MINIMIZED, \n GetLocalizedString(L\"最小化\", L\"Minimized\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hStartupMenu, \n GetLocalizedString(L\"启动模式\", L\"Startup Mode\"));\n\n // Font menu\n HMENU hFontMenu = CreatePopupMenu();\n AppendMenuW(hFontMenu, MF_STRING, CLOCK_IDM_SELECT_FONT, \n GetLocalizedString(L\"选择字体\", L\"Select Font\"));\n AppendMenuW(hFontMenu, MF_STRING | (IS_PREVIEWING ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_PREVIEW_FONT, \n GetLocalizedString(L\"预览字体\", L\"Preview Font\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hFontMenu, \n GetLocalizedString(L\"字体设置\", L\"Font Settings\"));\n\n // Color menu\n HMENU hColorMenu = CreatePopupMenu();\n ClearColorOptions();\n AddColorOption(\"White\"); AddColorOption(\"Black\"); AddColorOption(\"Red\");\n AddColorOption(\"Green\"); AddColorOption(\"Blue\"); AddColorOption(\"Yellow\");\n AddColorOption(\"Custom...\");\n \n for (int i = 0; i < GetColorOptionCount(); i++) {\n const char* color = GetColorOption(i);\n BOOL isChecked = (strcmp(color, CLOCK_TEXT_COLOR) == 0);\n AppendMenuA(hColorMenu, MF_STRING | (isChecked ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_COLOR_BASE + i, color);\n }\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hColorMenu, \n GetLocalizedString(L\"文字颜色\", L\"Text Color\"));\n\n // Language menu\n HMENU hLangMenu = CreatePopupMenu();\n AppendMenuW(hLangMenu, MF_STRING | (GetCurrentLanguage() == LANG_ENGLISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_ENGLISH, L\"English\");\n AppendMenuW(hLangMenu, MF_STRING | (GetCurrentLanguage() == LANG_CHINESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE, L\"中文\");\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hLangMenu, \n GetLocalizedString(L\"语言\", L\"Language\"));\n\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_HELP, \n GetLocalizedString(L\"帮助\", L\"Help\"));\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_ABOUT, \n GetLocalizedString(L\"关于\", L\"About\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_EXIT, \n GetLocalizedString(L\"退出\", L\"Exit\"));\n\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN, pt.x, pt.y, 0, hwnd, NULL);\n DestroyMenu(hMenu);\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 17-55-35"}, "editdistance_info": {"edit_distance": 21.989, "calculate_time": "2025-08-20 17:55:35", "true_code_clean": "void ShowColorMenu(HWND hwnd) {\n ReadTimeoutActionFromConfig();\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n HMENU hMenu = CreatePopupMenu();\n AppendMenuW(hMenu, MF_STRING | (CLOCK_EDIT_MODE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_EDIT_MODE, \n GetLocalizedString(L\"编辑模式\", L\"Edit Mode\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n HMENU hTimeoutMenu = CreatePopupMenu();\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_SHOW_MESSAGE, \n GetLocalizedString(L\"显示消息\", L\"Show Message\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHOW_TIME ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_SHOW_TIME, \n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_COUNT_UP ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_TIMEOUT_COUNT_UP, \n GetLocalizedString(L\"正计时\", L\"Count Up\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_LOCK ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LOCK_SCREEN,\n GetLocalizedString(L\"锁定屏幕\", L\"Lock Screen\"));\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n HMENU hFileMenu = CreatePopupMenu();\n for (int i = 0; i < CLOCK_RECENT_FILES_COUNT; i++) {\n wchar_t wFileName[MAX_PATH];\n MultiByteToWideChar(CP_UTF8, 0, CLOCK_RECENT_FILES[i].name, -1, wFileName, MAX_PATH);\n wchar_t truncatedName[MAX_PATH];\n TruncateFileName(wFileName, truncatedName, 25); \n BOOL isCurrentFile = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE && \n strlen(CLOCK_TIMEOUT_FILE_PATH) > 0 && \n strcmp(CLOCK_RECENT_FILES[i].path, CLOCK_TIMEOUT_FILE_PATH) == 0);\n AppendMenuW(hFileMenu, MF_STRING | (isCurrentFile ? MF_CHECKED : 0), \n CLOCK_IDM_RECENT_FILE_1 + i, truncatedName);\n }\n if (CLOCK_RECENT_FILES_COUNT > 0) {\n AppendMenuW(hFileMenu, MF_SEPARATOR, 0, NULL);\n }\n AppendMenuW(hFileMenu, MF_STRING, CLOCK_IDM_BROWSE_FILE,\n GetLocalizedString(L\"浏览...\", L\"Browse...\"));\n AppendMenuW(hTimeoutMenu, MF_POPUP | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE ? MF_CHECKED : MF_UNCHECKED), \n (UINT_PTR)hFileMenu, \n GetLocalizedString(L\"打开文件/软件\", L\"Open File/Software\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_WEBSITE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_OPEN_WEBSITE,\n GetLocalizedString(L\"打开网站\", L\"Open Website\"));\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hTimeoutMenu, MF_STRING | MF_GRAYED | MF_DISABLED, \n 0, \n GetLocalizedString(L\"以下超时动作为一次性\", L\"Following actions are one-time only\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SHUTDOWN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SHUTDOWN,\n GetLocalizedString(L\"关机\", L\"Shutdown\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RESTART ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RESTART,\n GetLocalizedString(L\"重启\", L\"Restart\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_SLEEP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_SLEEP,\n GetLocalizedString(L\"睡眠\", L\"Sleep\"));\n AppendMenuW(hTimeoutMenu, MF_SEPARATOR, 0, NULL);\n HMENU hAdvancedMenu = CreatePopupMenu();\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_RUN_COMMAND,\n GetLocalizedString(L\"运行命令\", L\"Run Command\"));\n AppendMenuW(hAdvancedMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_HTTP_REQUEST,\n GetLocalizedString(L\"HTTP 请求\", L\"HTTP Request\"));\n BOOL isAdvancedOptionSelected = (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_RUN_COMMAND ||\n CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_HTTP_REQUEST);\n AppendMenuW(hTimeoutMenu, MF_POPUP | (isAdvancedOptionSelected ? MF_CHECKED : MF_UNCHECKED),\n (UINT_PTR)hAdvancedMenu,\n GetLocalizedString(L\"高级\", L\"Advanced\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeoutMenu, \n GetLocalizedString(L\"超时动作\", L\"Timeout Action\"));\n HMENU hTimeOptionsMenu = CreatePopupMenu();\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDC_MODIFY_TIME_OPTIONS,\n GetLocalizedString(L\"倒计时预设\", L\"Modify Quick Countdown Options\"));\n HMENU hStartupSettingsMenu = CreatePopupMenu();\n char currentStartupMode[20] = \"COUNTDOWN\";\n char configPath[MAX_PATH]; \n GetConfigPath(configPath, MAX_PATH);\n FILE *configFile = fopen(configPath, \"r\"); \n if (configFile) {\n char line[256];\n while (fgets(line, sizeof(line), configFile)) {\n if (strncmp(line, \"STARTUP_MODE=\", 13) == 0) {\n sscanf(line, \"STARTUP_MODE=%19s\", currentStartupMode);\n break;\n }\n }\n fclose(configFile);\n }\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNTDOWN\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_SET_COUNTDOWN_TIME,\n GetLocalizedString(L\"倒计时\", L\"Countdown\"));\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"COUNT_UP\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_COUNT_UP,\n GetLocalizedString(L\"正计时\", L\"Stopwatch\"));\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"SHOW_TIME\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_SHOW_TIME,\n GetLocalizedString(L\"显示当前时间\", L\"Show Current Time\"));\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (strcmp(currentStartupMode, \"NO_DISPLAY\") == 0 ? MF_CHECKED : 0),\n CLOCK_IDC_START_NO_DISPLAY,\n GetLocalizedString(L\"不显示\", L\"No Display\"));\n AppendMenuW(hStartupSettingsMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hStartupSettingsMenu, MF_STRING | \n (IsAutoStartEnabled() ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDC_AUTO_START,\n GetLocalizedString(L\"开机自启动\", L\"Start with Windows\"));\n AppendMenuW(hTimeOptionsMenu, MF_POPUP, (UINT_PTR)hStartupSettingsMenu,\n GetLocalizedString(L\"启动设置\", L\"Startup Settings\"));\n AppendMenuW(hTimeOptionsMenu, MF_STRING, CLOCK_IDM_NOTIFICATION_SETTINGS,\n GetLocalizedString(L\"通知设置\", L\"Notification Settings\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeOptionsMenu,\n GetLocalizedString(L\"预设管理\", L\"Preset Management\"));\n AppendMenuW(hTimeOptionsMenu, MF_STRING | (CLOCK_WINDOW_TOPMOST ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TOPMOST,\n GetLocalizedString(L\"置顶\", L\"Always on Top\"));\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_HOTKEY_SETTINGS,\n GetLocalizedString(L\"热键设置\", L\"Hotkey Settings\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n HMENU hMoreFontsMenu = CreatePopupMenu();\n HMENU hFontSubMenu = CreatePopupMenu();\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayName[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayName, 100);\n wchar_t* dot = wcsstr(wDisplayName, L\".ttf\");\n if (dot) *dot = L'\\0';\n AppendMenuW(hFontSubMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayName);\n }\n }\n AppendMenuW(hFontSubMenu, MF_SEPARATOR, 0, NULL);\n for (int i = 0; i < FONT_RESOURCES_COUNT; i++) {\n if (strcmp(fontResources[i].fontName, \"Terminess Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"DaddyTimeMono Nerd Font Propo Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Foldit SemiBold Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Jacquarda Bastarda 9 Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Moirai One Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Silkscreen Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pixelify Sans Medium Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Burned Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Rubik Glitch Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ProFont IIx Nerd Font Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Wallpoet Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Yesteryear Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"Pinyon Script Essence.ttf\") == 0 ||\n strcmp(fontResources[i].fontName, \"ZCOOL KuaiLe Essence.ttf\") == 0) {\n continue;\n }\n BOOL isCurrentFont = strcmp(FONT_FILE_NAME, fontResources[i].fontName) == 0;\n wchar_t wDisplayNameMore[100];\n MultiByteToWideChar(CP_UTF8, 0, fontResources[i].fontName, -1, wDisplayNameMore, 100);\n wchar_t* dot = wcsstr(wDisplayNameMore, L\".ttf\");\n if (dot) *dot = L'\\0';\n AppendMenuW(hMoreFontsMenu, MF_STRING | (isCurrentFont ? MF_CHECKED : MF_UNCHECKED),\n fontResources[i].menuId, wDisplayNameMore);\n }\n AppendMenuW(hFontSubMenu, MF_POPUP, (UINT_PTR)hMoreFontsMenu, GetLocalizedString(L\"更多\", L\"More\"));\n HMENU hColorSubMenu = CreatePopupMenu();\n for (int i = 0; i < COLOR_OPTIONS_COUNT; i++) {\n const char* hexColor = COLOR_OPTIONS[i].hexColor;\n MENUITEMINFO mii = { sizeof(MENUITEMINFO) };\n mii.fMask = MIIM_STRING | MIIM_ID | MIIM_STATE | MIIM_FTYPE;\n mii.fType = MFT_STRING | MFT_OWNERDRAW;\n mii.fState = strcmp(CLOCK_TEXT_COLOR, hexColor) == 0 ? MFS_CHECKED : MFS_UNCHECKED;\n mii.wID = 201 + i; \n mii.dwTypeData = (LPSTR)hexColor;\n InsertMenuItem(hColorSubMenu, i, TRUE, &mii);\n }\n AppendMenuW(hColorSubMenu, MF_SEPARATOR, 0, NULL);\n HMENU hCustomizeMenu = CreatePopupMenu();\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_VALUE, \n GetLocalizedString(L\"颜色值\", L\"Color Value\"));\n AppendMenuW(hCustomizeMenu, MF_STRING, CLOCK_IDC_COLOR_PANEL, \n GetLocalizedString(L\"颜色面板\", L\"Color Panel\"));\n AppendMenuW(hColorSubMenu, MF_POPUP, (UINT_PTR)hCustomizeMenu, \n GetLocalizedString(L\"自定义\", L\"Customize\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hFontSubMenu, \n GetLocalizedString(L\"字体\", L\"Font\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hColorSubMenu, \n GetLocalizedString(L\"颜色\", L\"Color\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n HMENU hAboutMenu = CreatePopupMenu();\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_ABOUT, GetLocalizedString(L\"关于\", L\"About\"));\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_SUPPORT, GetLocalizedString(L\"支持\", L\"Support\"));\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_FEEDBACK, GetLocalizedString(L\"反馈\", L\"Feedback\"));\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_HELP, GetLocalizedString(L\"使用指南\", L\"User Guide\"));\n AppendMenuW(hAboutMenu, MF_STRING, CLOCK_IDM_CHECK_UPDATE, \n GetLocalizedString(L\"检查更新\", L\"Check for Updates\"));\n HMENU hLangMenu = CreatePopupMenu();\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_SIMP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE, L\"简体中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_CHINESE_TRAD ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE_TRAD, L\"繁體中文\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_ENGLISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_ENGLISH, L\"English\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_SPANISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_SPANISH, L\"Español\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_FRENCH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_FRENCH, L\"Français\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_GERMAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_GERMAN, L\"Deutsch\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_RUSSIAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_RUSSIAN, L\"Русский\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_PORTUGUESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_PORTUGUESE, L\"Português\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_JAPANESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_JAPANESE, L\"日本語\");\n AppendMenuW(hLangMenu, MF_STRING | (CURRENT_LANGUAGE == APP_LANG_KOREAN ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_KOREAN, L\"한국어\");\n AppendMenuW(hAboutMenu, MF_POPUP, (UINT_PTR)hLangMenu, GetLocalizedString(L\"语言\", L\"Language\"));\n AppendMenuW(hAboutMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hAboutMenu, MF_STRING, 200,\n GetLocalizedString(L\"重置\", L\"Reset\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hAboutMenu,\n GetLocalizedString(L\"帮助\", L\"Help\"));\n AppendMenuW(hMenu, MF_STRING, 109,\n GetLocalizedString(L\"退出\", L\"Exit\"));\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, NULL);\n PostMessage(hwnd, WM_NULL, 0, 0); \n DestroyMenu(hMenu);\n}", "predict_code_clean": "void ShowColorMenu(HWND hwnd) {\n HMENU hMenu = CreatePopupMenu();\n AppendMenuW(hMenu, MF_STRING | (CLOCK_EDIT_MODE ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_EDIT_MODE, \n GetLocalizedString(L\"编辑模式\", L\"Edit Mode\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n HMENU hTimeoutMenu = CreatePopupMenu();\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_NONE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_NONE, \n GetLocalizedString(L\"无操作\", L\"No Action\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_BEEP ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_BEEP, \n GetLocalizedString(L\"蜂鸣提示\", L\"Beep\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_MESSAGE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_MESSAGE, \n GetLocalizedString(L\"显示消息\", L\"Show Message\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_FILE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_OPEN_FILE, \n GetLocalizedString(L\"打开文件\", L\"Open File\"));\n AppendMenuW(hTimeoutMenu, MF_STRING | (CLOCK_TIMEOUT_ACTION == TIMEOUT_ACTION_OPEN_WEBSITE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_TIMEOUT_OPEN_WEBSITE, \n GetLocalizedString(L\"打开网页\", L\"Open Website\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hTimeoutMenu, \n GetLocalizedString(L\"超时操作\", L\"Timeout Action\"));\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_MANAGE_PRESETS, \n GetLocalizedString(L\"预设时间管理\", L\"Manage Presets\"));\n HMENU hStartupMenu = CreatePopupMenu();\n AppendMenuW(hStartupMenu, MF_STRING | (strcmp(CLOCK_STARTUP_MODE, \"Normal\") == 0 ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_STARTUP_NORMAL, \n GetLocalizedString(L\"普通模式\", L\"Normal Mode\"));\n AppendMenuW(hStartupMenu, MF_STRING | (strcmp(CLOCK_STARTUP_MODE, \"Maximized\") == 0 ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_STARTUP_MAXIMIZED, \n GetLocalizedString(L\"最大化\", L\"Maximized\"));\n AppendMenuW(hStartupMenu, MF_STRING | (strcmp(CLOCK_STARTUP_MODE, \"Minimized\") == 0 ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_STARTUP_MINIMIZED, \n GetLocalizedString(L\"最小化\", L\"Minimized\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hStartupMenu, \n GetLocalizedString(L\"启动模式\", L\"Startup Mode\"));\n HMENU hFontMenu = CreatePopupMenu();\n AppendMenuW(hFontMenu, MF_STRING, CLOCK_IDM_SELECT_FONT, \n GetLocalizedString(L\"选择字体\", L\"Select Font\"));\n AppendMenuW(hFontMenu, MF_STRING | (IS_PREVIEWING ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_PREVIEW_FONT, \n GetLocalizedString(L\"预览字体\", L\"Preview Font\"));\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hFontMenu, \n GetLocalizedString(L\"字体设置\", L\"Font Settings\"));\n HMENU hColorMenu = CreatePopupMenu();\n ClearColorOptions();\n AddColorOption(\"White\"); AddColorOption(\"Black\"); AddColorOption(\"Red\");\n AddColorOption(\"Green\"); AddColorOption(\"Blue\"); AddColorOption(\"Yellow\");\n AddColorOption(\"Custom...\");\n for (int i = 0; i < GetColorOptionCount(); i++) {\n const char* color = GetColorOption(i);\n BOOL isChecked = (strcmp(color, CLOCK_TEXT_COLOR) == 0);\n AppendMenuA(hColorMenu, MF_STRING | (isChecked ? MF_CHECKED : MF_UNCHECKED), \n CLOCK_IDM_COLOR_BASE + i, color);\n }\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hColorMenu, \n GetLocalizedString(L\"文字颜色\", L\"Text Color\"));\n HMENU hLangMenu = CreatePopupMenu();\n AppendMenuW(hLangMenu, MF_STRING | (GetCurrentLanguage() == LANG_ENGLISH ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_ENGLISH, L\"English\");\n AppendMenuW(hLangMenu, MF_STRING | (GetCurrentLanguage() == LANG_CHINESE ? MF_CHECKED : MF_UNCHECKED),\n CLOCK_IDM_LANG_CHINESE, L\"中文\");\n AppendMenuW(hMenu, MF_POPUP, (UINT_PTR)hLangMenu, \n GetLocalizedString(L\"语言\", L\"Language\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_HELP, \n GetLocalizedString(L\"帮助\", L\"Help\"));\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_ABOUT, \n GetLocalizedString(L\"关于\", L\"About\"));\n AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);\n AppendMenuW(hMenu, MF_STRING, CLOCK_IDM_EXIT, \n GetLocalizedString(L\"退出\", L\"Exit\"));\n POINT pt;\n GetCursorPos(&pt);\n SetForegroundWindow(hwnd);\n TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN, pt.x, pt.y, 0, hwnd, NULL);\n DestroyMenu(hMenu);\n}"}}