使用 GPT5.6 制作的轻量级程序。使用 -std=c++11 -O2 -mwindows -lgdi32 -luser32 -lshell32 -lcomdlg32 -lgdiplus -lole32 编译即可。
https://www.luogu.com.cn/paste/7ze799ar
#define WINVER 0x0601
#define _WIN32_WINNT 0x0601
#define UNICODE
#define _UNICODE
#define NOMINMAX
// GlassCountdown.cpp
// Windows 7+ / Win32 + GDI + GDI+
// MinGW / TDM-GCC:
// g++ GlassCountdown.cpp -std=c++11 -O2 -mwindows \
// -lgdi32 -luser32 -lshell32 -lcomdlg32 -lgdiplus -lole32 \
// -o GlassCountdown.exe
// MSVC (Developer Command Prompt):
// cl /std:c++14 /O2 /EHsc GlassCountdown.cpp /link /SUBSYSTEM:WINDOWS \
// user32.lib gdi32.lib shell32.lib comdlg32.lib gdiplus.lib ole32.lib
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0602
#elif _WIN32_WINNT < 0x0602
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0602
#endif
#ifndef WINVER
#define WINVER 0x0602
#elif WINVER < 0x0602
#undef WINVER
#define WINVER 0x0602
#endif
#include <windows.h>
#include <windowsx.h>
#include <shellapi.h>
#include <commdlg.h>
#include <shlobj.h>
#include <gdiplus.h>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <cwchar>
#include <cwctype>
#include <cstring>
#include <sstream>
#include <iomanip>
using namespace std;
using namespace Gdiplus;
#ifndef GET_X_LPARAM
#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#endif
#ifndef GET_Y_LPARAM
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
#endif
// ============================================================
// Constants / IDs
// ============================================================
static const int BASE_CONTENT_W = 720;
static const int BASE_CONTENT_H = 292;
static const int BASE_SHADOW = 24;
static const int BASE_RADIUS = 28;
static const UINT TIMER_REFRESH = 1;
static const UINT WM_TRAYICON = WM_APP + 11;
static const UINT TRAY_ICON_ID = 1;
static const int MENU_SET_TIME = 1001;
static const int MENU_TOGGLE = 1002;
static const int MENU_RESET = 1003;
static const int MENU_RESTART = 1004;
static const int MENU_FULLSCREEN = 1005;
static const int MENU_TOPMOST = 1006;
static const int MENU_HIDE = 1007;
static const int MENU_SHOW = 1008;
static const int MENU_EXIT = 1099;
static const int MENU_PRESET_BASE = 1200; // 1200..1249
static const int MENU_PRESET_ADD_CURRENT = 1250;
static const int MENU_PRESET_CLEAR = 1251;
static const int MENU_HISTORY_BASE = 1300; // 1300..1349
static const int MENU_HISTORY_CLEAR = 1350;
static const int MENU_THEME_BASE = 1400;
static const int MENU_THEME_CUSTOM_BG = 1410;
static const int MENU_TEXT_AUTO = 1420;
static const int MENU_TEXT_PICK = 1421;
static const int MENU_BG_THEME = 1500;
static const int MENU_BG_GLASS = 1501;
static const int MENU_BG_IMAGE = 1502;
static const int MENU_BG_IMAGE_PICK = 1503;
static const int MENU_BG_IMAGE_CLEAR = 1504;
static const int MENU_BG_SOLID_PICK = 1505;
static const int MENU_BLUR_OFF = 1510;
static const int MENU_BLUR_SOFT = 1511;
static const int MENU_BLUR_STRONG = 1512;
static const int MENU_OPACITY_BASE = 1530; // 0,20,40,60,80,100 -> +0..5
static const int MENU_ZONE_LOCAL = 1600;
static const int MENU_ZONE_UTC = 1601;
static const int MENU_ZONE_BEIJING = 1602;
static const int MENU_ZONE_LONDON = 1603;
static const int MENU_ZONE_NEWYORK = 1604;
static const int MENU_ZONE_TOKYO = 1605;
static const int MENU_SCALE_80 = 1700;
static const int MENU_SCALE_100 = 1701;
static const int MENU_SCALE_120 = 1702;
static const int MENU_SCALE_140 = 1703;
static const int HOTKEY_TOGGLE = 2001;
static const int HOTKEY_RESET = 2002;
static const int HOTKEY_FULLSCREEN = 2003;
static const int HOTKEY_SET_TIME = 2004;
static const int HOTKEY_EXIT = 2005;
static const int IDC_INPUT_LABEL = 3001;
static const int IDC_INPUT_HOUR = 3002;
static const int IDC_INPUT_MINUTE = 3003;
static const int IDC_INPUT_SECOND = 3004;
static const int IDC_INPUT_START = 3010;
static const int IDC_INPUT_CANCEL = 3011;
// ============================================================
// Utility
// ============================================================
static ULONGLONG NowMs()
{
static LARGE_INTEGER freq = {};
static bool init = false;
if(!init)
{
QueryPerformanceFrequency(&freq);
init = true;
}
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return (ULONGLONG)(now.QuadPart * 1000LL / freq.QuadPart);
}
static int ClampInt(int v, int lo, int hi)
{
return v < lo ? lo : (v > hi ? hi : v);
}
static double ClampDouble(double v, double lo, double hi)
{
return v < lo ? lo : (v > hi ? hi : v);
}
static COLORREF BlendColor(COLORREF a, COLORREF b, double t)
{
t = ClampDouble(t, 0.0, 1.0);
int r = (int)(GetRValue(a) * (1.0 - t) + GetRValue(b) * t + 0.5);
int g = (int)(GetGValue(a) * (1.0 - t) + GetGValue(b) * t + 0.5);
int bl = (int)(GetBValue(a) * (1.0 - t) + GetBValue(b) * t + 0.5);
return RGB(r, g, bl);
}
static wstring ToWString(long long v)
{
wchar_t b[64];
swprintf(b, 64, L"%lld", v);
return b;
}
static wstring FormatDurationSeconds(long long totalSeconds)
{
if(totalSeconds < 0) totalSeconds = 0;
long long h = totalSeconds / 3600;
long long m = (totalSeconds % 3600) / 60;
long long s = totalSeconds % 60;
wchar_t buf[64];
if(h > 0)
swprintf(buf, 64, L"%02lld:%02lld:%02lld", h, m, s);
else
swprintf(buf, 64, L"%02lld:%02lld", m, s);
return buf;
}
static wstring FormatRemainingMs(long long ms)
{
if(ms < 0) ms = 0;
// 向上取整到秒,避免刚开始立刻少 1 秒。
long long sec = (ms + 999) / 1000;
return FormatDurationSeconds(sec);
}
static wstring Trim(const wstring& s)
{
size_t a = 0, b = s.size();
while(a < b && iswspace(s[a])) ++a;
while(b > a && iswspace(s[b - 1])) --b;
return s.substr(a, b - a);
}
static bool FileExists(const wstring& p)
{
DWORD a = GetFileAttributesW(p.c_str());
return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
}
// ============================================================
// State
// ============================================================
struct Palette
{
COLORREF bgTop;
COLORREF bgBottom;
COLORREF primary;
COLORREF secondary;
COLORREF muted;
COLORREF accent;
COLORREF track;
COLORREF border;
COLORREF shadow;
};
enum ThemeMode
{
THEME_MIDNIGHT = 0,
THEME_FROST,
THEME_OCEAN,
THEME_MATCHA,
THEME_SUNSET,
THEME_SAKURA,
THEME_AMOLED,
THEME_COUNT
};
enum BackgroundMode
{
BG_THEME = 0,
BG_GLASS,
BG_IMAGE,
BG_SOLID
};
enum WorldZone
{
ZONE_LOCAL = 0,
ZONE_UTC,
ZONE_BEIJING,
ZONE_LONDON,
ZONE_NEWYORK,
ZONE_TOKYO
};
struct TimerItem
{
wstring label;
long long seconds;
};
static HWND g_hwnd = NULL;
static HWND g_inputWnd = NULL;
static HINSTANCE g_hInstance = NULL;
static NOTIFYICONDATAW g_tray = {};
static ULONG_PTR g_gdiplusToken = 0;
static Bitmap* g_bgImage = NULL;
static ThemeMode g_theme = THEME_MIDNIGHT;
static BackgroundMode g_bgMode = BG_GLASS;
static WorldZone g_zone = ZONE_LOCAL;
static int g_bgOpacity = 86; // 背景不透明度,文字独立保持清晰
static int g_blurStrength = 1; // 0 off, 1 soft, 2 strong
static int g_scalePercent = 100;
static bool g_autoText = true;
static COLORREF g_customText = RGB(247, 249, 255);
static COLORREF g_customBg = RGB(21, 24, 33);
static wstring g_bgImagePath;
static bool g_fullscreen = false;
static bool g_topmost = true;
static long long g_durationMs = 25LL * 60LL * 1000LL;
static long long g_pausedRemainingMs = g_durationMs;
static ULONGLONG g_endTickMs = 0;
static bool g_running = false;
static bool g_finished = false;
static bool g_finishNotified = false;
static FILETIME g_completedFileTime = {};
static wstring g_label = L"专注倒计时";
static vector<TimerItem> g_presets;
static vector<TimerItem> g_history;
static RECT g_restoreRect = {};
static bool g_dragging = false;
static POINT g_dragStartMouse = {};
static POINT g_dragStartWindow = {};
static RECT g_playRect = {};
static RECT g_resetRect = {};
static RECT g_closeRect = {};
static vector<BYTE> g_backdropCache;
static int g_cacheW = 0;
static int g_cacheH = 0;
static int g_cacheX = 0;
static int g_cacheY = 0;
static ULONGLONG g_cacheTime = 0;
static bool g_backdropDirty = true;
static HFONT g_fontTitle = NULL;
static HFONT g_fontTimer = NULL;
static HFONT g_fontMeta = NULL;
static HFONT g_fontSmall = NULL;
static HFONT g_fontButton = NULL;
static int g_fontKeyW = 0;
static int g_fontKeyH = 0;
static bool g_fontKeyFullscreen = false;
static wstring g_iniPath;
// ============================================================
// Theme
// ============================================================
static const wchar_t* ThemeName(ThemeMode t)
{
switch(t)
{
case THEME_MIDNIGHT: return L"午夜黑";
case THEME_FROST: return L"霜白";
case THEME_OCEAN: return L"深海蓝";
case THEME_MATCHA: return L"抹茶绿";
case THEME_SUNSET: return L"日落橙";
case THEME_SAKURA: return L"樱花粉";
case THEME_AMOLED: return L"AMOLED 纯黑";
default: return L"主题";
}
}
static Palette GetPalette()
{
Palette p = {};
switch(g_theme)
{
default:
case THEME_MIDNIGHT:
p.bgTop = RGB(23, 27, 38); p.bgBottom = RGB(12, 15, 23);
p.primary = RGB(246, 248, 255); p.secondary = RGB(184, 193, 214);
p.muted = RGB(132, 143, 166); p.accent = RGB(108, 142, 255);
p.track = RGB(52, 59, 77); p.border = RGB(72, 82, 108); p.shadow = RGB(4, 7, 12);
break;
case THEME_FROST:
p.bgTop = RGB(247, 250, 255); p.bgBottom = RGB(224, 233, 244);
p.primary = RGB(25, 32, 44); p.secondary = RGB(67, 80, 99);
p.muted = RGB(108, 121, 139); p.accent = RGB(58, 116, 218);
p.track = RGB(194, 207, 225); p.border = RGB(182, 197, 216); p.shadow = RGB(67, 78, 93);
break;
case THEME_OCEAN:
p.bgTop = RGB(12, 48, 71); p.bgBottom = RGB(6, 24, 38);
p.primary = RGB(238, 251, 255); p.secondary = RGB(172, 222, 235);
p.muted = RGB(116, 177, 195); p.accent = RGB(63, 206, 238);
p.track = RGB(26, 80, 102); p.border = RGB(44, 109, 132); p.shadow = RGB(2, 13, 20);
break;
case THEME_MATCHA:
p.bgTop = RGB(31, 57, 48); p.bgBottom = RGB(15, 31, 26);
p.primary = RGB(244, 251, 239); p.secondary = RGB(193, 220, 183);
p.muted = RGB(137, 176, 128); p.accent = RGB(151, 216, 116);
p.track = RGB(57, 88, 68); p.border = RGB(74, 111, 85); p.shadow = RGB(5, 15, 10);
break;
case THEME_SUNSET:
p.bgTop = RGB(82, 42, 34); p.bgBottom = RGB(36, 20, 30);
p.primary = RGB(255, 247, 237); p.secondary = RGB(248, 200, 166);
p.muted = RGB(211, 148, 132); p.accent = RGB(255, 142, 82);
p.track = RGB(104, 61, 52); p.border = RGB(130, 73, 60); p.shadow = RGB(20, 7, 10);
break;
case THEME_SAKURA:
p.bgTop = RGB(70, 40, 60); p.bgBottom = RGB(33, 22, 37);
p.primary = RGB(255, 244, 250); p.secondary = RGB(245, 190, 220);
p.muted = RGB(201, 137, 174); p.accent = RGB(255, 126, 190);
p.track = RGB(94, 57, 81); p.border = RGB(119, 71, 101); p.shadow = RGB(17, 8, 15);
break;
case THEME_AMOLED:
p.bgTop = RGB(0, 0, 0); p.bgBottom = RGB(0, 0, 0);
p.primary = RGB(255, 255, 255); p.secondary = RGB(190, 190, 196);
p.muted = RGB(125, 125, 132); p.accent = RGB(125, 159, 255);
p.track = RGB(34, 34, 38); p.border = RGB(55, 55, 62); p.shadow = RGB(0, 0, 0);
break;
}
return p;
}
// ============================================================
// Persistence
// ============================================================
static void EnsureConfigPath()
{
wchar_t appData[MAX_PATH] = {};
if(SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appData)))
{
wstring dir = wstring(appData) + L"\\GlassCountdown";
CreateDirectoryW(dir.c_str(), NULL);
g_iniPath = dir + L"\\settings.ini";
}
else
{
g_iniPath = L"GlassCountdown.ini";
}
}
static void IniWrite(const wchar_t* section, const wchar_t* key, const wstring& value)
{
WritePrivateProfileStringW(section, key, value.c_str(), g_iniPath.c_str());
}
static wstring IniRead(const wchar_t* section, const wchar_t* key, const wchar_t* fallback)
{
wchar_t buf[2048] = {};
GetPrivateProfileStringW(section, key, fallback, buf, 2048, g_iniPath.c_str());
return buf;
}
static int IniReadInt(const wchar_t* section, const wchar_t* key, int fallback)
{
return GetPrivateProfileIntW(section, key, fallback, g_iniPath.c_str());
}
static wstring EscapeItemName(wstring s)
{
replace(s.begin(), s.end(), L'|', L' ');
return s;
}
static bool ParseTimerItem(const wstring& s, TimerItem& out)
{
size_t p = s.rfind(L'|');
if(p == wstring::npos) return false;
wstring name = Trim(s.substr(0, p));
wstring secText = Trim(s.substr(p + 1));
if(secText.empty()) return false;
long long sec = _wtoi64(secText.c_str());
if(sec <= 0 || sec > 35999999LL) return false;
out.label = name.empty() ? FormatDurationSeconds(sec) : name;
out.seconds = sec;
return true;
}
static void SaveState()
{
if(g_iniPath.empty()) return;
IniWrite(L"Main", L"Theme", ToWString((int)g_theme));
IniWrite(L"Main", L"BackgroundMode", ToWString((int)g_bgMode));
IniWrite(L"Main", L"WorldZone", ToWString((int)g_zone));
IniWrite(L"Main", L"BackgroundOpacity", ToWString(g_bgOpacity));
IniWrite(L"Main", L"BlurStrength", ToWString(g_blurStrength));
IniWrite(L"Main", L"Scale", ToWString(g_scalePercent));
IniWrite(L"Main", L"AutoText", g_autoText ? L"1" : L"0");
IniWrite(L"Main", L"CustomText", ToWString((long long)g_customText));
IniWrite(L"Main", L"CustomBackground", ToWString((long long)g_customBg));
IniWrite(L"Main", L"BackgroundImage", g_bgImagePath);
IniWrite(L"Main", L"Topmost", g_topmost ? L"1" : L"0");
IniWrite(L"Main", L"DurationSeconds", ToWString(g_durationMs / 1000));
IniWrite(L"Main", L"Label", g_label);
RECT r = {};
if(g_hwnd && !g_fullscreen && GetWindowRect(g_hwnd, &r))
{
IniWrite(L"Window", L"X", ToWString(r.left));
IniWrite(L"Window", L"Y", ToWString(r.top));
}
IniWrite(L"Presets", L"Count", ToWString((long long)g_presets.size()));
for(size_t i = 0; i < g_presets.size(); ++i)
{
wchar_t key[32]; swprintf(key, 32, L"Item%u", (unsigned)i);
IniWrite(L"Presets", key, EscapeItemName(g_presets[i].label) + L"|" + ToWString(g_presets[i].seconds));
}
for(size_t i = g_presets.size(); i < 32; ++i)
{
wchar_t key[32]; swprintf(key, 32, L"Item%u", (unsigned)i);
WritePrivateProfileStringW(L"Presets", key, NULL, g_iniPath.c_str());
}
IniWrite(L"History", L"Count", ToWString((long long)g_history.size()));
for(size_t i = 0; i < g_history.size(); ++i)
{
wchar_t key[32]; swprintf(key, 32, L"Item%u", (unsigned)i);
IniWrite(L"History", key, EscapeItemName(g_history[i].label) + L"|" + ToWString(g_history[i].seconds));
}
for(size_t i = g_history.size(); i < 32; ++i)
{
wchar_t key[32]; swprintf(key, 32, L"Item%u", (unsigned)i);
WritePrivateProfileStringW(L"History", key, NULL, g_iniPath.c_str());
}
}
static void LoadState()
{
g_theme = (ThemeMode)ClampInt(IniReadInt(L"Main", L"Theme", THEME_MIDNIGHT), 0, THEME_COUNT - 1);
g_bgMode = (BackgroundMode)ClampInt(IniReadInt(L"Main", L"BackgroundMode", BG_GLASS), 0, 3);
g_zone = (WorldZone)ClampInt(IniReadInt(L"Main", L"WorldZone", ZONE_LOCAL), 0, 5);
g_bgOpacity = ClampInt(IniReadInt(L"Main", L"BackgroundOpacity", 86), 0, 100);
g_blurStrength = ClampInt(IniReadInt(L"Main", L"BlurStrength", 1), 0, 2);
g_scalePercent = ClampInt(IniReadInt(L"Main", L"Scale", 100), 80, 140);
g_autoText = IniReadInt(L"Main", L"AutoText", 1) != 0;
g_customText = (COLORREF)_wtoi64(IniRead(L"Main", L"CustomText", L"16775671").c_str());
g_customBg = (COLORREF)_wtoi64(IniRead(L"Main", L"CustomBackground", L"2177045").c_str());
g_bgImagePath = IniRead(L"Main", L"BackgroundImage", L"");
g_topmost = IniReadInt(L"Main", L"Topmost", 1) != 0;
long long durationSec = _wtoi64(IniRead(L"Main", L"DurationSeconds", L"1500").c_str());
if(durationSec <= 0) durationSec = 1500;
g_durationMs = durationSec * 1000LL;
g_pausedRemainingMs = g_durationMs;
g_label = IniRead(L"Main", L"Label", L"专注倒计时");
if(Trim(g_label).empty()) g_label = L"专注倒计时";
g_presets.clear();
int pc = ClampInt(IniReadInt(L"Presets", L"Count", 0), 0, 20);
for(int i = 0; i < pc; ++i)
{
wchar_t key[32]; swprintf(key, 32, L"Item%d", i);
TimerItem item;
if(ParseTimerItem(IniRead(L"Presets", key, L""), item)) g_presets.push_back(item);
}
if(g_presets.empty())
{
g_presets.push_back({L"番茄钟", 25 * 60});
g_presets.push_back({L"短休息", 5 * 60});
g_presets.push_back({L"长休息", 15 * 60});
g_presets.push_back({L"1 小时", 60 * 60});
}
g_history.clear();
int hc = ClampInt(IniReadInt(L"History", L"Count", 0), 0, 12);
for(int i = 0; i < hc; ++i)
{
wchar_t key[32]; swprintf(key, 32, L"Item%d", i);
TimerItem item;
if(ParseTimerItem(IniRead(L"History", key, L""), item)) g_history.push_back(item);
}
}
// ============================================================
// Countdown core
// ============================================================
static long long RemainingMs()
{
if(g_running)
{
ULONGLONG now = NowMs();
if(now >= g_endTickMs) return 0;
return (long long)(g_endTickMs - now);
}
return g_pausedRemainingMs;
}
static void AddHistory(const wstring& label, long long seconds)
{
TimerItem item = { Trim(label).empty() ? FormatDurationSeconds(seconds) : Trim(label), seconds };
g_history.erase(remove_if(g_history.begin(), g_history.end(), [&](const TimerItem& x)
{
return x.seconds == item.seconds && _wcsicmp(x.label.c_str(), item.label.c_str()) == 0;
}), g_history.end());
g_history.insert(g_history.begin(), item);
if(g_history.size() > 12) g_history.resize(12);
}
static void StartCountdown(long long seconds, const wstring& label)
{
seconds = max(1LL, min(seconds, 35999999LL));
g_durationMs = seconds * 1000LL;
g_pausedRemainingMs = g_durationMs;
g_endTickMs = NowMs() + (ULONGLONG)g_durationMs;
g_running = true;
g_finished = false;
g_finishNotified = false;
ZeroMemory(&g_completedFileTime, sizeof(g_completedFileTime));
g_label = Trim(label).empty() ? L"倒计时" : Trim(label);
AddHistory(g_label, seconds);
SaveState();
if(g_hwnd) InvalidateRect(g_hwnd, NULL, FALSE);
}
static void ToggleCountdown()
{
long long rem = RemainingMs();
if(g_running)
{
g_pausedRemainingMs = rem;
g_running = false;
}
else if(rem > 0)
{
g_endTickMs = NowMs() + (ULONGLONG)rem;
g_running = true;
g_finished = false;
g_finishNotified = false;
ZeroMemory(&g_completedFileTime, sizeof(g_completedFileTime));
}
else
{
g_pausedRemainingMs = g_durationMs;
g_endTickMs = NowMs() + (ULONGLONG)g_durationMs;
g_running = true;
g_finished = false;
g_finishNotified = false;
ZeroMemory(&g_completedFileTime, sizeof(g_completedFileTime));
}
if(g_hwnd) InvalidateRect(g_hwnd, NULL, FALSE);
}
static void ResetCountdown(bool startNow)
{
g_pausedRemainingMs = g_durationMs;
g_running = startNow;
g_finished = false;
g_finishNotified = false;
ZeroMemory(&g_completedFileTime, sizeof(g_completedFileTime));
if(startNow) g_endTickMs = NowMs() + (ULONGLONG)g_durationMs;
if(g_hwnd) InvalidateRect(g_hwnd, NULL, FALSE);
}
static void UpdateFinishState()
{
if(g_running && RemainingMs() <= 0)
{
g_running = false;
g_pausedRemainingMs = 0;
g_finished = true;
if(!g_finishNotified)
{
g_finishNotified = true;
GetSystemTimeAsFileTime(&g_completedFileTime);
MessageBeep(MB_ICONASTERISK);
}
}
}
// ============================================================
// World clock / finish time
// ============================================================
static const wchar_t* ZoneLabel(WorldZone z)
{
switch(z)
{
case ZONE_LOCAL: return L"本地";
case ZONE_UTC: return L"UTC";
case ZONE_BEIJING: return L"北京";
case ZONE_LONDON: return L"伦敦";
case ZONE_NEWYORK: return L"纽约";
case ZONE_TOKYO: return L"东京";
default: return L"本地";
}
}
static const wchar_t* ZoneKey(WorldZone z)
{
switch(z)
{
case ZONE_BEIJING: return L"China Standard Time";
case ZONE_LONDON: return L"GMT Standard Time";
case ZONE_NEWYORK: return L"Eastern Standard Time";
case ZONE_TOKYO: return L"Tokyo Standard Time";
default: return NULL;
}
}
static bool ConvertUtcToZone(const SYSTEMTIME& utc, WorldZone zone, SYSTEMTIME& out)
{
if(zone == ZONE_UTC)
{
out = utc;
return true;
}
if(zone == ZONE_LOCAL)
return SystemTimeToTzSpecificLocalTime(NULL, &utc, &out) != FALSE;
const wchar_t* wanted = ZoneKey(zone);
if(!wanted) return false;
DYNAMIC_TIME_ZONE_INFORMATION info = {};
for(DWORD index = 0;; ++index)
{
DWORD r = EnumDynamicTimeZoneInformation(index, &info);
if(r == ERROR_NO_MORE_ITEMS) break;
if(r != ERROR_SUCCESS) break;
if(_wcsicmp(info.TimeZoneKeyName, wanted) == 0)
return SystemTimeToTzSpecificLocalTimeEx(&info, &utc, &out) != FALSE;
}
return false;
}
static SYSTEMTIME FinishUtcTime()
{
FILETIME ft = {};
if(g_finished && (g_completedFileTime.dwLowDateTime || g_completedFileTime.dwHighDateTime))
{
SYSTEMTIME done = {};
FileTimeToSystemTime(&g_completedFileTime, &done);
return done;
}
GetSystemTimeAsFileTime(&ft);
ULARGE_INTEGER ui = {};
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
ui.QuadPart += (ULONGLONG)max(0LL, RemainingMs()) * 10000ULL;
ft.dwLowDateTime = ui.LowPart;
ft.dwHighDateTime = ui.HighPart;
SYSTEMTIME st = {};
FileTimeToSystemTime(&ft, &st);
return st;
}
static wstring FormatSystemTime(const SYSTEMTIME& st)
{
wchar_t buf[96];
swprintf(buf, 96, L"%04u-%02u-%02u %02u:%02u:%02u",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buf;
}
// ============================================================
// Background image / backdrop cache
// ============================================================
static void InvalidateBackdrop()
{
g_backdropDirty = true;
if(g_hwnd) InvalidateRect(g_hwnd, NULL, FALSE);
}
static void LoadBackgroundImage()
{
if(g_bgImage)
{
delete g_bgImage;
g_bgImage = NULL;
}
if(!g_bgImagePath.empty() && FileExists(g_bgImagePath))
{
Bitmap* bmp = new Bitmap(g_bgImagePath.c_str(), FALSE);
if(bmp && bmp->GetLastStatus() == Ok)
g_bgImage = bmp;
else
delete bmp;
}
InvalidateBackdrop();
}
static void FillGradient32(BYTE* bits, int width, int height, COLORREF top, COLORREF bottom)
{
for(int y = 0; y < height; ++y)
{
double t = height > 1 ? (double)y / (double)(height - 1) : 0.0;
t = t * t * (3.0 - 2.0 * t);
int r = (int)(GetRValue(top) + (GetRValue(bottom) - GetRValue(top)) * t + 0.5);
int g = (int)(GetGValue(top) + (GetGValue(bottom) - GetGValue(top)) * t + 0.5);
int b = (int)(GetBValue(top) + (GetBValue(bottom) - GetBValue(top)) * t + 0.5);
BYTE* row = bits + (size_t)y * width * 4;
for(int x = 0; x < width; ++x)
{
row[x * 4 + 0] = (BYTE)b;
row[x * 4 + 1] = (BYTE)g;
row[x * 4 + 2] = (BYTE)r;
row[x * 4 + 3] = 255;
}
}
}
static void BoxBlur32(BYTE* bits, int width, int height, int radius)
{
if(radius <= 0 || width <= 1 || height <= 1) return;
radius = min(radius, 24);
vector<BYTE> temp((size_t)width * height * 4);
int window = radius * 2 + 1;
for(int y = 0; y < height; ++y)
{
long sb = 0, sg = 0, sr = 0;
for(int k = -radius; k <= radius; ++k)
{
int sx = ClampInt(k, 0, width - 1);
BYTE* p = bits + ((size_t)y * width + sx) * 4;
sb += p[0]; sg += p[1]; sr += p[2];
}
for(int x = 0; x < width; ++x)
{
BYTE* o = &temp[((size_t)y * width + x) * 4];
o[0] = (BYTE)(sb / window); o[1] = (BYTE)(sg / window); o[2] = (BYTE)(sr / window); o[3] = 255;
int rx = ClampInt(x - radius, 0, width - 1);
int ax = ClampInt(x + radius + 1, 0, width - 1);
BYTE* rp = bits + ((size_t)y * width + rx) * 4;
BYTE* ap = bits + ((size_t)y * width + ax) * 4;
sb += (long)ap[0] - rp[0]; sg += (long)ap[1] - rp[1]; sr += (long)ap[2] - rp[2];
}
}
for(int x = 0; x < width; ++x)
{
long sb = 0, sg = 0, sr = 0;
for(int k = -radius; k <= radius; ++k)
{
int sy = ClampInt(k, 0, height - 1);
BYTE* p = &temp[((size_t)sy * width + x) * 4];
sb += p[0]; sg += p[1]; sr += p[2];
}
for(int y = 0; y < height; ++y)
{
BYTE* o = bits + ((size_t)y * width + x) * 4;
o[0] = (BYTE)(sb / window); o[1] = (BYTE)(sg / window); o[2] = (BYTE)(sr / window); o[3] = 255;
int ry = ClampInt(y - radius, 0, height - 1);
int ay = ClampInt(y + radius + 1, 0, height - 1);
BYTE* rp = &temp[((size_t)ry * width + x) * 4];
BYTE* ap = &temp[((size_t)ay * width + x) * 4];
sb += (long)ap[0] - rp[0]; sg += (long)ap[1] - rp[1]; sr += (long)ap[2] - rp[2];
}
}
}
static void ForceOpaqueAlpha(BYTE* bits, int width, int height)
{
size_t n = (size_t)width * height;
for(size_t i = 0; i < n; ++i) bits[i * 4 + 3] = 255;
}
static void Tint32(BYTE* bits, int width, int height, COLORREF tint, double amount)
{
amount = ClampDouble(amount, 0.0, 1.0);
int tr = GetRValue(tint), tg = GetGValue(tint), tb = GetBValue(tint);
size_t n = (size_t)width * height;
for(size_t i = 0; i < n; ++i)
{
BYTE* p = bits + i * 4;
p[0] = (BYTE)(p[0] * (1.0 - amount) + tb * amount + 0.5);
p[1] = (BYTE)(p[1] * (1.0 - amount) + tg * amount + 0.5);
p[2] = (BYTE)(p[2] * (1.0 - amount) + tr * amount + 0.5);
p[3] = 255;
}
}
static void DrawImageCover(HDC dc, int width, int height)
{
if(!g_bgImage) return;
UINT iw = g_bgImage->GetWidth();
UINT ih = g_bgImage->GetHeight();
if(iw == 0 || ih == 0) return;
double target = (double)width / max(1, height);
double source = (double)iw / ih;
REAL sx = 0, sy = 0, sw = (REAL)iw, sh = (REAL)ih;
if(source > target)
{
sw = (REAL)(ih * target);
sx = ((REAL)iw - sw) / 2.0f;
}
else
{
sh = (REAL)(iw / target);
sy = ((REAL)ih - sh) / 2.0f;
}
Graphics gr(dc);
gr.SetInterpolationMode(InterpolationModeHighQualityBicubic);
gr.SetPixelOffsetMode(PixelOffsetModeHighQuality);
gr.DrawImage(g_bgImage, Rect(0, 0, width, height), sx, sy, sw, sh, UnitPixel);
}
static void BuildBackdrop(HWND hwnd, HDC memDC, HDC screenDC, BYTE* bits, int width, int height, const RECT& wr)
{
bool cacheMatches = !g_backdropDirty && g_cacheW == width && g_cacheH == height &&
g_cacheX == wr.left && g_cacheY == wr.top &&
g_backdropCache.size() == (size_t)width * height * 4;
if(g_bgMode == BG_GLASS && cacheMatches && NowMs() - g_cacheTime > 1200)
cacheMatches = false;
if(cacheMatches)
{
memcpy(bits, g_backdropCache.data(), g_backdropCache.size());
return;
}
Palette p = GetPalette();
FillGradient32(bits, width, height, p.bgTop, p.bgBottom);
if(g_bgMode == BG_GLASS)
{
if(BitBlt(memDC, 0, 0, width, height, screenDC, wr.left, wr.top, SRCCOPY))
{
ForceOpaqueAlpha(bits, width, height);
if(g_blurStrength > 0)
{
int radius = g_blurStrength == 1 ? 7 : 15;
if(g_fullscreen) radius = g_blurStrength == 1 ? 5 : 10;
BoxBlur32(bits, width, height, radius);
if(g_blurStrength == 2) BoxBlur32(bits, width, height, max(3, radius / 2));
}
COLORREF tint = BlendColor(p.bgTop, p.bgBottom, 0.5);
Tint32(bits, width, height, tint, g_theme == THEME_FROST ? 0.48 : 0.56);
}
}
else if(g_bgMode == BG_IMAGE && g_bgImage)
{
DrawImageCover(memDC, width, height);
ForceOpaqueAlpha(bits, width, height);
if(g_blurStrength > 0)
{
int radius = g_blurStrength == 1 ? 5 : 11;
if(g_fullscreen) radius = g_blurStrength == 1 ? 4 : 8;
BoxBlur32(bits, width, height, radius);
if(g_blurStrength == 2) BoxBlur32(bits, width, height, max(3, radius / 2));
}
// 极轻的主题染色,保证文字区统一。
Tint32(bits, width, height, BlendColor(p.bgTop, p.bgBottom, 0.5), 0.16);
}
else if(g_bgMode == BG_SOLID)
{
FillGradient32(bits, width, height, g_customBg, g_customBg);
}
else if(g_bgMode == BG_THEME)
{
// 保留内置主题本身的渐变。
}
g_backdropCache.assign(bits, bits + (size_t)width * height * 4);
g_cacheW = width; g_cacheH = height; g_cacheX = wr.left; g_cacheY = wr.top;
g_cacheTime = NowMs();
g_backdropDirty = false;
}
static double AverageLuma(const BYTE* bits, int width, int height)
{
if(width <= 0 || height <= 0) return 80.0;
long long sum = 0, count = 0;
int stepX = max(1, width / 48);
int stepY = max(1, height / 24);
int x0 = width / 8, x1 = width - width / 8;
int y0 = height / 8, y1 = height - height / 8;
for(int y = y0; y < y1; y += stepY)
{
for(int x = x0; x < x1; x += stepX)
{
const BYTE* p = bits + ((size_t)y * width + x) * 4;
int b = p[0], g = p[1], r = p[2];
sum += (long long)(r * 299 + g * 587 + b * 114) / 1000;
++count;
}
}
return count ? (double)sum / count : 80.0;
}
// ============================================================
// Window geometry / fonts
// ============================================================
static int Scaled(int v)
{
return MulDiv(v, g_scalePercent, 100);
}
static int CompactWindowW() { return Scaled(BASE_CONTENT_W + BASE_SHADOW * 2); }
static int CompactWindowH() { return Scaled(BASE_CONTENT_H + BASE_SHADOW * 2); }
static RECT ContentRectFor(int width, int height)
{
RECT r = {};
if(g_fullscreen)
{
r.left = 0; r.top = 0; r.right = width; r.bottom = height;
}
else
{
int m = Scaled(BASE_SHADOW);
r.left = m; r.top = m; r.right = width - m; r.bottom = height - m;
}
return r;
}
static void DeleteFonts()
{
if(g_fontTitle) DeleteObject(g_fontTitle);
if(g_fontTimer) DeleteObject(g_fontTimer);
if(g_fontMeta) DeleteObject(g_fontMeta);
if(g_fontSmall) DeleteObject(g_fontSmall);
if(g_fontButton) DeleteObject(g_fontButton);
g_fontTitle = g_fontTimer = g_fontMeta = g_fontSmall = g_fontButton = NULL;
}
static HFONT MakeFont(int px, int weight)
{
return CreateFontW(-px, 0, 0, 0, weight, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, L"Segoe UI Variable Display");
}
static void EnsureFonts(int width, int height)
{
if(g_fontTitle && g_fontKeyW == width && g_fontKeyH == height && g_fontKeyFullscreen == g_fullscreen)
return;
DeleteFonts();
g_fontKeyW = width; g_fontKeyH = height; g_fontKeyFullscreen = g_fullscreen;
int timerPx, titlePx, metaPx, smallPx, buttonPx;
if(g_fullscreen)
{
int base = min(width, height * 16 / 9);
timerPx = ClampInt(base / 7, 96, 280);
titlePx = ClampInt(base / 38, 26, 62);
metaPx = ClampInt(base / 46, 22, 46);
smallPx = ClampInt(base / 62, 18, 32);
buttonPx = smallPx;
}
else
{
timerPx = Scaled(82);
titlePx = Scaled(20);
metaPx = Scaled(16);
smallPx = Scaled(13);
buttonPx = Scaled(14);
}
g_fontTitle = MakeFont(titlePx, FW_SEMIBOLD);
g_fontTimer = MakeFont(timerPx, FW_SEMIBOLD);
g_fontMeta = MakeFont(metaPx, FW_MEDIUM);
g_fontSmall = MakeFont(smallPx, FW_NORMAL);
g_fontButton = MakeFont(buttonPx, FW_SEMIBOLD);
}
static void RoundedRectFill(HDC dc, const RECT& r, COLORREF c, int radius)
{
HBRUSH b = CreateSolidBrush(c);
HPEN p = CreatePen(PS_NULL, 0, c);
HBRUSH ob = (HBRUSH)SelectObject(dc, b);
HPEN op = (HPEN)SelectObject(dc, p);
RoundRect(dc, r.left, r.top, r.right, r.bottom, radius * 2, radius * 2);
SelectObject(dc, ob); SelectObject(dc, op);
DeleteObject(b); DeleteObject(p);
}
static void DrawCenteredText(HDC dc, const wstring& text, RECT r, HFONT font, COLORREF color, UINT flags)
{
HFONT old = (HFONT)SelectObject(dc, font);
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, color);
DrawTextW(dc, text.c_str(), (int)text.size(), &r, flags | DT_NOPREFIX);
SelectObject(dc, old);
}
static void DrawButton(HDC dc, RECT r, const wchar_t* text, COLORREF fg, COLORREF bg, int radius)
{
RoundedRectFill(dc, r, bg, radius);
DrawCenteredText(dc, text, r, g_fontButton, fg, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
}
static COLORREF AutoPrimaryFromBackdrop(const BYTE* baseline, int width, int height, const Palette& p)
{
if(!g_autoText) return g_customText;
double l = AverageLuma(baseline, width, height);
return l > 158.0 ? RGB(18, 22, 30) : RGB(248, 250, 255);
}
static void DrawContent(HDC dc, int width, int height, const BYTE* baseline)
{
EnsureFonts(width, height);
Palette p = GetPalette();
COLORREF primary = AutoPrimaryFromBackdrop(baseline, width, height, p);
bool darkText = (GetRValue(primary) + GetGValue(primary) + GetBValue(primary)) < 360;
COLORREF secondary = darkText ? RGB(62, 70, 83) : RGB(207, 214, 229);
COLORREF muted = darkText ? RGB(100, 108, 120) : RGB(150, 160, 180);
COLORREF buttonBg = darkText ? RGB(222, 227, 236) : RGB(48, 56, 72);
COLORREF buttonFg = darkText ? RGB(25, 31, 41) : RGB(246, 248, 255);
RECT c = ContentRectFor(width, height);
int cw = c.right - c.left, ch = c.bottom - c.top;
int pad = g_fullscreen ? max(40, width / 22) : Scaled(28);
SetBkMode(dc, TRANSPARENT);
// subtle border for compact mode
if(!g_fullscreen)
{
HPEN pen = CreatePen(PS_SOLID, max(1, Scaled(1)), p.border);
HBRUSH hb = (HBRUSH)GetStockObject(HOLLOW_BRUSH);
HPEN op = (HPEN)SelectObject(dc, pen);
HBRUSH ob = (HBRUSH)SelectObject(dc, hb);
int rr = Scaled(BASE_RADIUS);
RoundRect(dc, c.left, c.top, c.right, c.bottom, rr * 2, rr * 2);
SelectObject(dc, ob); SelectObject(dc, op); DeleteObject(pen);
}
// title + status dot
int dot = g_fullscreen ? max(10, width / 180) : Scaled(9);
int titleY = g_fullscreen ? c.top + ch / 13 : c.top + Scaled(20);
int titleX = c.left + pad;
HBRUSH ab = CreateSolidBrush(g_finished ? RGB(255, 100, 92) : p.accent);
HPEN ap = CreatePen(PS_NULL, 0, p.accent);
HBRUSH ob = (HBRUSH)SelectObject(dc, ab); HPEN op = (HPEN)SelectObject(dc, ap);
Ellipse(dc, titleX, titleY + dot / 2, titleX + dot, titleY + dot + dot / 2);
SelectObject(dc, ob); SelectObject(dc, op); DeleteObject(ab); DeleteObject(ap);
RECT titleRect = { titleX + dot + (g_fullscreen ? 18 : Scaled(12)), titleY - 5,
c.right - pad, titleY + (g_fullscreen ? 60 : Scaled(32)) };
DrawCenteredText(dc, g_label, titleRect, g_fontTitle, primary, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
// Close button only compact. Fullscreen is exited by right click / hotkey.
if(!g_fullscreen)
{
int s = Scaled(30);
g_closeRect = { c.right - pad - s, c.top + Scaled(14), c.right - pad, c.top + Scaled(14) + s };
DrawCenteredText(dc, L"×", g_closeRect, g_fontTitle, secondary, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
}
else SetRectEmpty(&g_closeRect);
long long rem = RemainingMs();
wstring timerText = FormatRemainingMs(rem);
RECT timerRect;
if(g_fullscreen)
timerRect = { c.left + pad, c.top + ch * 20 / 100, c.right - pad, c.top + ch * 56 / 100 };
else
timerRect = { c.left + pad, c.top + Scaled(48), c.right - pad, c.top + Scaled(155) };
DrawCenteredText(dc, timerText, timerRect, g_fontTimer, primary, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
SYSTEMTIME utc = FinishUtcTime();
SYSTEMTIME local = {}, world = {};
ConvertUtcToZone(utc, ZONE_LOCAL, local);
if(!ConvertUtcToZone(utc, g_zone, world)) world = local;
wstring localLine = L"终到 · 本地 " + FormatSystemTime(local);
wstring worldLine = wstring(L"世界时钟 · ") + ZoneLabel(g_zone) + L" " + FormatSystemTime(world);
RECT meta1, meta2;
if(g_fullscreen)
{
meta1 = { c.left + pad, c.top + ch * 58 / 100, c.right - pad, c.top + ch * 65 / 100 };
meta2 = { c.left + pad, c.top + ch * 65 / 100, c.right - pad, c.top + ch * 72 / 100 };
}
else
{
meta1 = { c.left + pad, c.top + Scaled(158), c.right - pad, c.top + Scaled(185) };
meta2 = { c.left + pad, c.top + Scaled(184), c.right - pad, c.top + Scaled(211) };
}
DrawCenteredText(dc, localLine, meta1, g_fontMeta, secondary, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
DrawCenteredText(dc, worldLine, meta2, g_fontMeta, muted, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
// progress
int barH = g_fullscreen ? max(5, height / 180) : Scaled(5);
int barY = g_fullscreen ? c.top + ch * 79 / 100 : c.top + Scaled(222);
RECT track = { c.left + pad, barY, c.right - pad, barY + barH };
RoundedRectFill(dc, track, p.track, barH);
double ratio = g_durationMs > 0 ? (double)rem / (double)g_durationMs : 0.0;
ratio = ClampDouble(ratio, 0.0, 1.0);
int fillW = (int)((track.right - track.left) * ratio + 0.5);
if(fillW > 0)
{
RECT fill = track; fill.right = fill.left + fillW;
RoundedRectFill(dc, fill, g_finished ? RGB(255, 100, 92) : p.accent, barH);
}
// action buttons / hint
if(g_fullscreen)
{
int bw = ClampInt(width / 10, 140, 260);
int bh = ClampInt(height / 15, 48, 78);
int gap = max(16, width / 120);
int y = c.top + ch * 84 / 100;
int center = (c.left + c.right) / 2;
g_playRect = { center - gap / 2 - bw, y, center - gap / 2, y + bh };
g_resetRect = { center + gap / 2, y, center + gap / 2 + bw, y + bh };
DrawButton(dc, g_playRect, g_running ? L"暂停" : (rem > 0 ? L"继续" : L"重来"), buttonFg, buttonBg, bh / 2);
DrawButton(dc, g_resetRect, L"重置", buttonFg, buttonBg, bh / 2);
RECT hint = { c.left + pad, c.bottom - max(60, height / 14), c.right - pad, c.bottom - 12 };
DrawCenteredText(dc, L"右键设置 · Ctrl+Alt+Space 暂停/继续 · Ctrl+Alt+F 全屏/退出全屏", hint, g_fontSmall, muted,
DT_CENTER | DT_VCENTER | DT_SINGLELINE);
}
else
{
int bh = Scaled(32), bw = Scaled(84), gap = Scaled(10);
int y = c.top + Scaled(242);
g_playRect = { c.left + pad, y, c.left + pad + bw, y + bh };
g_resetRect = { g_playRect.right + gap, y, g_playRect.right + gap + bw, y + bh };
DrawButton(dc, g_playRect, g_running ? L"暂停" : (rem > 0 ? L"继续" : L"重来"), buttonFg, buttonBg, bh / 2);
DrawButton(dc, g_resetRect, L"重置", buttonFg, buttonBg, bh / 2);
RECT hint = { g_resetRect.right + Scaled(16), y, c.right - pad, y + bh };
DrawCenteredText(dc, L"右键设置 · 背景/主题/常用倒计时/世界时钟", hint, g_fontSmall, muted,
DT_RIGHT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
}
}
static double RoundedRectSignedDistance(double px, double py, const RECT& r, double radius)
{
double cx = (r.left + r.right) * 0.5;
double cy = (r.top + r.bottom) * 0.5;
double hx = (r.right - r.left) * 0.5;
double hy = (r.bottom - r.top) * 0.5;
radius = min(radius, min(hx, hy));
double qx = fabs(px - cx) - (hx - radius);
double qy = fabs(py - cy) - (hy - radius);
double ox = max(qx, 0.0), oy = max(qy, 0.0);
return sqrt(ox * ox + oy * oy) + min(max(qx, qy), 0.0) - radius;
}
static void ApplyAlpha(BYTE* bits, const BYTE* baseline, int width, int height, const Palette& p)
{
RECT c = ContentRectFor(width, height);
double radius = g_fullscreen ? 0.0 : (double)Scaled(BASE_RADIUS);
double edge = g_fullscreen ? 0.0 : max(1.0, (double)Scaled(1));
double bgAlpha = g_bgOpacity / 100.0;
double sigma = g_fullscreen ? 0.0 : max(4.0, (double)Scaled(9));
for(int y = 0; y < height; ++y)
{
for(int x = 0; x < width; ++x)
{
size_t idx = ((size_t)y * width + x) * 4;
double coverage = 1.0;
double d = -1.0;
if(!g_fullscreen)
{
d = RoundedRectSignedDistance(x + 0.5, y + 0.5, c, radius);
if(d <= -edge) coverage = 1.0;
else if(d >= edge) coverage = 0.0;
else
{
double t = ClampDouble(0.5 - d / (2.0 * edge), 0.0, 1.0);
coverage = t * t * (3.0 - 2.0 * t);
}
}
bool uiChanged = false;
if(baseline)
{
int db = abs((int)bits[idx + 0] - (int)baseline[idx + 0]);
int dg = abs((int)bits[idx + 1] - (int)baseline[idx + 1]);
int dr = abs((int)bits[idx + 2] - (int)baseline[idx + 2]);
uiChanged = (db + dg + dr) >= 8;
}
double alpha = coverage * (uiChanged ? 1.0 : bgAlpha);
if(!g_fullscreen && coverage < 1.0)
{
double outside = d > 0.0 ? d : 0.0;
double shadow = exp(-(outside * outside) / (2.0 * sigma * sigma)) * 0.30;
if(shadow > alpha)
{
double mix = 1.0 - coverage;
bits[idx + 2] = (BYTE)(GetRValue(p.shadow) * mix + bits[idx + 2] * coverage + 0.5);
bits[idx + 1] = (BYTE)(GetGValue(p.shadow) * mix + bits[idx + 1] * coverage + 0.5);
bits[idx + 0] = (BYTE)(GetBValue(p.shadow) * mix + bits[idx + 0] * coverage + 0.5);
alpha = shadow;
}
}
int a = ClampInt((int)(alpha * 255.0 + 0.5), 0, 255);
bits[idx + 0] = (BYTE)((bits[idx + 0] * a + 127) / 255);
bits[idx + 1] = (BYTE)((bits[idx + 1] * a + 127) / 255);
bits[idx + 2] = (BYTE)((bits[idx + 2] * a + 127) / 255);
bits[idx + 3] = (BYTE)a;
}
}
}
static void RenderLayeredWindow(HWND hwnd)
{
if(!hwnd) return;
RECT wr = {}; GetWindowRect(hwnd, &wr);
int width = wr.right - wr.left, height = wr.bottom - wr.top;
if(width <= 0 || height <= 0) return;
HDC screenDC = GetDC(NULL);
if(!screenDC) return;
HDC memDC = CreateCompatibleDC(screenDC);
if(!memDC) { ReleaseDC(NULL, screenDC); return; }
BITMAPINFO bmi = {};
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = -height;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
BYTE* bits = NULL;
HBITMAP bmp = CreateDIBSection(screenDC, &bmi, DIB_RGB_COLORS, (void**)&bits, NULL, 0);
if(!bmp || !bits)
{
if(bmp) DeleteObject(bmp);
DeleteDC(memDC); ReleaseDC(NULL, screenDC); return;
}
HBITMAP old = (HBITMAP)SelectObject(memDC, bmp);
BuildBackdrop(hwnd, memDC, screenDC, bits, width, height, wr);
vector<BYTE> baseline(bits, bits + (size_t)width * height * 4);
DrawContent(memDC, width, height, baseline.data());
ApplyAlpha(bits, baseline.data(), width, height, GetPalette());
POINT dst = { wr.left, wr.top }, src = { 0, 0 };
SIZE sz = { width, height };
BLENDFUNCTION bf = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
UpdateLayeredWindow(hwnd, screenDC, &dst, &sz, memDC, &src, 0, &bf, ULW_ALPHA);
SelectObject(memDC, old); DeleteObject(bmp); DeleteDC(memDC); ReleaseDC(NULL, screenDC);
}
// ============================================================
// Tray / positioning / fullscreen
// ============================================================
static void AddTrayIcon(HWND hwnd)
{
ZeroMemory(&g_tray, sizeof(g_tray));
g_tray.cbSize = sizeof(g_tray);
g_tray.hWnd = hwnd;
g_tray.uID = TRAY_ICON_ID;
g_tray.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
g_tray.uCallbackMessage = WM_TRAYICON;
g_tray.hIcon = LoadIconW(NULL, IDI_APPLICATION);
lstrcpynW(g_tray.szTip, L"Glass Countdown - 倒计时", 128);
Shell_NotifyIconW(NIM_ADD, &g_tray);
}
static void RemoveTrayIcon()
{
if(g_tray.hWnd) Shell_NotifyIconW(NIM_DELETE, &g_tray);
ZeroMemory(&g_tray, sizeof(g_tray));
}
static HMONITOR MonitorForWindowSafe(HWND hwnd)
{
return MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
}
static void PutBottomRight(HWND hwnd)
{
HMONITOR mon = MonitorForWindowSafe(hwnd);
MONITORINFO mi = { sizeof(mi) };
GetMonitorInfoW(mon, &mi);
int w = CompactWindowW(), h = CompactWindowH();
int x = mi.rcWork.right - w - 20;
int y = mi.rcWork.bottom - h - 20;
SetWindowPos(hwnd, g_topmost ? HWND_TOPMOST : HWND_NOTOPMOST, x, y, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW);
InvalidateBackdrop();
}
static void ClampCompactPosition(int& x, int& y)
{
POINT pt = { x + CompactWindowW() / 2, y + CompactWindowH() / 2 };
HMONITOR mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
MONITORINFO mi = { sizeof(mi) }; GetMonitorInfoW(mon, &mi);
int w = CompactWindowW(), h = CompactWindowH();
x = max(mi.rcWork.left - w + 80, min((long) x, mi.rcWork.right - 80));
y = max(mi.rcWork.top - h + 60, min((long )y, mi.rcWork.bottom - 60));
}
static void ApplyTopmost()
{
if(!g_hwnd) return;
SetWindowPos(g_hwnd, g_topmost ? HWND_TOPMOST : HWND_NOTOPMOST, 0,0,0,0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
static void ToggleFullscreen()
{
if(!g_hwnd) return;
if(!g_fullscreen)
{
GetWindowRect(g_hwnd, &g_restoreRect);
HMONITOR mon = MonitorForWindowSafe(g_hwnd);
MONITORINFO mi = { sizeof(mi) }; GetMonitorInfoW(mon, &mi);
g_fullscreen = true;
SetWindowPos(g_hwnd, g_topmost ? HWND_TOPMOST : HWND_NOTOPMOST,
mi.rcMonitor.left, mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
}
else
{
g_fullscreen = false;
RECT r = g_restoreRect;
if(IsRectEmpty(&r))
{
PutBottomRight(g_hwnd);
return;
}
SetWindowPos(g_hwnd, g_topmost ? HWND_TOPMOST : HWND_NOTOPMOST,
r.left, r.top, r.right - r.left, r.bottom - r.top,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
}
DeleteFonts();
InvalidateBackdrop();
}
static void HideToTray(HWND hwnd) { ShowWindow(hwnd, SW_HIDE); }
static void ShowFromTray(HWND hwnd)
{
ShowWindow(hwnd, SW_SHOWNOACTIVATE);
ApplyTopmost();
InvalidateBackdrop();
}
// ============================================================
// Input window
// ============================================================
static void SetControlFont(HWND h, int px, int weight = FW_NORMAL)
{
HFONT f = CreateFontW(-px, 0,0,0, weight, FALSE,FALSE,FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, L"Segoe UI");
SendMessageW(h, WM_SETFONT, (WPARAM)f, TRUE);
SetPropW(h, L"GlassCountdownOwnedFont", f);
}
static void DeleteOwnedControlFonts(HWND hwnd)
{
HWND child = GetWindow(hwnd, GW_CHILD);
while(child)
{
HFONT f = (HFONT)GetPropW(child, L"GlassCountdownOwnedFont");
if(f) { RemovePropW(child, L"GlassCountdownOwnedFont"); DeleteObject(f); }
child = GetWindow(child, GW_HWNDNEXT);
}
}
static LRESULT CALLBACK InputWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CREATE:
{
HFONT labelFont = MakeFont(16, FW_NORMAL);
SetPropW(hwnd, L"GlassCountdownLabelFont", labelFont);
HWND title = CreateWindowW(L"STATIC", L"设置倒计时", WS_CHILD | WS_VISIBLE,
24, 18, 380, 28, hwnd, NULL, g_hInstance, NULL);
SetControlFont(title, 20, FW_SEMIBOLD);
HWND l1 = CreateWindowW(L"STATIC", L"名称", WS_CHILD | WS_VISIBLE,
24, 62, 64, 24, hwnd, NULL, g_hInstance, NULL);
SetControlFont(l1, 14);
HWND editLabel = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", g_label.c_str(),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
90, 58, 296, 30, hwnd, (HMENU)IDC_INPUT_LABEL, g_hInstance, NULL);
SetControlFont(editLabel, 15);
HWND l2 = CreateWindowW(L"STATIC", L"时 分 秒", WS_CHILD | WS_VISIBLE,
90, 102, 280, 22, hwnd, NULL, g_hInstance, NULL);
SetControlFont(l2, 13);
long long sec = max(0LL, RemainingMs() / 1000);
if(sec == 0) sec = g_durationMs / 1000;
int hh = (int)(sec / 3600), mm = (int)((sec % 3600) / 60), ss = (int)(sec % 60);
wchar_t b1[16], b2[16], b3[16];
swprintf(b1,16,L"%d",hh); swprintf(b2,16,L"%d",mm); swprintf(b3,16,L"%d",ss);
HWND eh = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", b1, WS_CHILD|WS_VISIBLE|WS_TABSTOP|ES_NUMBER|ES_CENTER,
90, 126, 74, 34, hwnd, (HMENU)IDC_INPUT_HOUR, g_hInstance, NULL);
HWND em = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", b2, WS_CHILD|WS_VISIBLE|WS_TABSTOP|ES_NUMBER|ES_CENTER,
182, 126, 74, 34, hwnd, (HMENU)IDC_INPUT_MINUTE, g_hInstance, NULL);
HWND es = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", b3, WS_CHILD|WS_VISIBLE|WS_TABSTOP|ES_NUMBER|ES_CENTER,
274, 126, 74, 34, hwnd, (HMENU)IDC_INPUT_SECOND, g_hInstance, NULL);
SetControlFont(eh,16,FW_SEMIBOLD); SetControlFont(em,16,FW_SEMIBOLD); SetControlFont(es,16,FW_SEMIBOLD);
SendMessageW(eh, EM_SETLIMITTEXT, 4, 0); SendMessageW(em, EM_SETLIMITTEXT, 2, 0); SendMessageW(es, EM_SETLIMITTEXT, 2, 0);
HWND hint = CreateWindowW(L"STATIC", L"分钟/秒可输入超过 59,程序会自动换算。", WS_CHILD|WS_VISIBLE,
90, 168, 300, 22, hwnd, NULL, g_hInstance, NULL);
SetControlFont(hint, 12);
HWND start = CreateWindowW(L"BUTTON", L"开始倒计时", WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_DEFPUSHBUTTON,
206, 205, 112, 36, hwnd, (HMENU)IDC_INPUT_START, g_hInstance, NULL);
HWND cancel = CreateWindowW(L"BUTTON", L"取消", WS_CHILD|WS_VISIBLE|WS_TABSTOP,
326, 205, 74, 36, hwnd, (HMENU)IDC_INPUT_CANCEL, g_hInstance, NULL);
SetControlFont(start,14,FW_SEMIBOLD); SetControlFont(cancel,14);
SetFocus(editLabel);
SendMessageW(editLabel, EM_SETSEL, 0, -1);
return 0;
}
case WM_COMMAND:
{
int id = LOWORD(wParam);
if(id == IDC_INPUT_CANCEL) { DestroyWindow(hwnd); return 0; }
if(id == IDC_INPUT_START)
{
wchar_t label[160] = {}, bh[32] = {}, bm[32] = {}, bs[32] = {};
GetDlgItemTextW(hwnd, IDC_INPUT_LABEL, label, 160);
GetDlgItemTextW(hwnd, IDC_INPUT_HOUR, bh, 32);
GetDlgItemTextW(hwnd, IDC_INPUT_MINUTE, bm, 32);
GetDlgItemTextW(hwnd, IDC_INPUT_SECOND, bs, 32);
long long h = _wtoi64(bh), m = _wtoi64(bm), s = _wtoi64(bs);
h = max(0LL, h); m = max(0LL, m); s = max(0LL, s);
long long total = h * 3600 + m * 60 + s;
if(total <= 0)
{
MessageBoxW(hwnd, L"请输入大于 0 的倒计时时间。", L"Glass Countdown", MB_OK | MB_ICONINFORMATION);
return 0;
}
StartCountdown(total, label);
DestroyWindow(hwnd);
return 0;
}
break;
}
case WM_CLOSE: DestroyWindow(hwnd); return 0;
case WM_DESTROY:
DeleteOwnedControlFonts(hwnd);
{
HFONT f = (HFONT)GetPropW(hwnd, L"GlassCountdownLabelFont");
if(f) { RemovePropW(hwnd, L"GlassCountdownLabelFont"); DeleteObject(f); }
}
g_inputWnd = NULL;
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
static void ShowTimeInput()
{
if(g_inputWnd)
{
ShowWindow(g_inputWnd, SW_SHOW); SetForegroundWindow(g_inputWnd); return;
}
RECT owner = {}; GetWindowRect(g_hwnd, &owner);
int w = 440, h = 300;
int x = (owner.left + owner.right - w) / 2;
int y = (owner.top + owner.bottom - h) / 2;
g_inputWnd = CreateWindowExW(WS_EX_TOOLWINDOW, L"GlassCountdownInputWindow", L"设置倒计时",
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU,
x, y, w, h, g_hwnd, NULL, g_hInstance, NULL);
if(g_inputWnd)
{
ShowWindow(g_inputWnd, SW_SHOW); UpdateWindow(g_inputWnd); SetForegroundWindow(g_inputWnd);
}
}
// ============================================================
// Color / image pickers
// ============================================================
static bool PickColor(HWND owner, COLORREF& c)
{
static COLORREF custom[16] = {};
CHOOSECOLORW cc = {};
cc.lStructSize = sizeof(cc); cc.hwndOwner = owner; cc.rgbResult = c;
cc.lpCustColors = custom; cc.Flags = CC_FULLOPEN | CC_RGBINIT;
if(ChooseColorW(&cc)) { c = cc.rgbResult; return true; }
return false;
}
static bool PickBackgroundFile(HWND owner, wstring& path)
{
wchar_t file[MAX_PATH] = {};
if(!path.empty()) lstrcpynW(file, path.c_str(), MAX_PATH);
OPENFILENAMEW ofn = {};
ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = owner;
ofn.lpstrFilter = L"图片文件\0*.png;*.jpg;*.jpeg;*.bmp;*.gif\0所有文件\0*.*\0\0";
ofn.lpstrFile = file; ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrTitle = L"选择倒计时背景图片";
if(GetOpenFileNameW(&ofn)) { path = file; return true; }
return false;
}
// ============================================================
// Context menu
// ============================================================
static UINT Checked(bool b) { return MF_STRING | (b ? MF_CHECKED : MF_UNCHECKED); }
static void ShowContextMenu(HWND hwnd, bool fromTray)
{
HMENU menu = CreatePopupMenu();
if(fromTray || !IsWindowVisible(hwnd))
{
AppendMenuW(menu, MF_STRING, MENU_SHOW, L"显示倒计时");
AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
}
AppendMenuW(menu, MF_STRING, MENU_SET_TIME, L"设置倒计时…\tCtrl+Alt+T");
AppendMenuW(menu, MF_STRING, MENU_TOGGLE, g_running ? L"暂停\tCtrl+Alt+Space" : L"继续 / 开始\tCtrl+Alt+Space");
AppendMenuW(menu, MF_STRING, MENU_RESET, L"重置\tCtrl+Alt+R");
AppendMenuW(menu, MF_STRING, MENU_RESTART, L"重新开始当前倒计时");
HMENU presets = CreatePopupMenu();
for(size_t i = 0; i < g_presets.size() && i < 50; ++i)
{
wstring text = g_presets[i].label + L" " + FormatDurationSeconds(g_presets[i].seconds);
AppendMenuW(presets, MF_STRING, MENU_PRESET_BASE + (UINT)i, text.c_str());
}
if(!g_presets.empty()) AppendMenuW(presets, MF_SEPARATOR, 0, NULL);
AppendMenuW(presets, MF_STRING, MENU_PRESET_ADD_CURRENT, L"将当前倒计时加入常用");
AppendMenuW(presets, MF_STRING, MENU_PRESET_CLEAR, L"清空常用倒计时");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)presets, L"常用倒计时");
HMENU history = CreatePopupMenu();
if(g_history.empty()) AppendMenuW(history, MF_GRAYED | MF_STRING, 0, L"暂无历史");
for(size_t i = 0; i < g_history.size() && i < 50; ++i)
{
wstring text = g_history[i].label + L" " + FormatDurationSeconds(g_history[i].seconds);
AppendMenuW(history, MF_STRING, MENU_HISTORY_BASE + (UINT)i, text.c_str());
}
if(!g_history.empty())
{
AppendMenuW(history, MF_SEPARATOR, 0, NULL);
AppendMenuW(history, MF_STRING, MENU_HISTORY_CLEAR, L"清空历史");
}
AppendMenuW(menu, MF_POPUP, (UINT_PTR)history, L"最近使用");
AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
HMENU zone = CreatePopupMenu();
AppendMenuW(zone, Checked(g_zone == ZONE_LOCAL), MENU_ZONE_LOCAL, L"本地时间");
AppendMenuW(zone, Checked(g_zone == ZONE_UTC), MENU_ZONE_UTC, L"UTC");
AppendMenuW(zone, Checked(g_zone == ZONE_BEIJING), MENU_ZONE_BEIJING, L"北京");
AppendMenuW(zone, Checked(g_zone == ZONE_LONDON), MENU_ZONE_LONDON, L"伦敦");
AppendMenuW(zone, Checked(g_zone == ZONE_NEWYORK), MENU_ZONE_NEWYORK, L"纽约");
AppendMenuW(zone, Checked(g_zone == ZONE_TOKYO), MENU_ZONE_TOKYO, L"东京");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)zone, L"世界时钟");
HMENU theme = CreatePopupMenu();
for(int i = 0; i < THEME_COUNT; ++i)
AppendMenuW(theme, Checked(g_theme == (ThemeMode)i), MENU_THEME_BASE + i, ThemeName((ThemeMode)i));
AppendMenuW(theme, MF_SEPARATOR, 0, NULL);
AppendMenuW(theme, MF_STRING, MENU_THEME_CUSTOM_BG, L"选择主题背景色…");
AppendMenuW(theme, Checked(g_autoText), MENU_TEXT_AUTO, L"文字颜色自动对比");
AppendMenuW(theme, MF_STRING, MENU_TEXT_PICK, L"选择固定文字颜色…");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)theme, L"主题与文字");
HMENU bg = CreatePopupMenu();
AppendMenuW(bg, Checked(g_bgMode == BG_THEME), MENU_BG_THEME, L"主题背景");
AppendMenuW(bg, Checked(g_bgMode == BG_GLASS), MENU_BG_GLASS, L"毛玻璃 / 桌面模糊");
AppendMenuW(bg, Checked(g_bgMode == BG_IMAGE), MENU_BG_IMAGE, L"本地图片背景");
AppendMenuW(bg, Checked(g_bgMode == BG_SOLID), MENU_BG_SOLID_PICK, L"自定义纯色背景…");
AppendMenuW(bg, MF_STRING, MENU_BG_IMAGE_PICK, L"选择本地图片…");
if(!g_bgImagePath.empty()) AppendMenuW(bg, MF_STRING, MENU_BG_IMAGE_CLEAR, L"清除背景图片");
HMENU blur = CreatePopupMenu();
AppendMenuW(blur, Checked(g_blurStrength == 0), MENU_BLUR_OFF, L"关闭模糊");
AppendMenuW(blur, Checked(g_blurStrength == 1), MENU_BLUR_SOFT, L"柔和模糊");
AppendMenuW(blur, Checked(g_blurStrength == 2), MENU_BLUR_STRONG, L"强模糊");
AppendMenuW(bg, MF_POPUP, (UINT_PTR)blur, L"模糊强度");
HMENU opacity = CreatePopupMenu();
const int opValues[6] = {0, 20, 40, 60, 80, 100};
for(int i = 0; i < 6; ++i)
{
wchar_t t[64]; swprintf(t, 64, L"%d%% 不透明", opValues[i]);
AppendMenuW(opacity, Checked(g_bgOpacity == opValues[i]), MENU_OPACITY_BASE + i, t);
}
AppendMenuW(bg, MF_POPUP, (UINT_PTR)opacity, L"背景透明度");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)bg, L"背景");
HMENU scale = CreatePopupMenu();
AppendMenuW(scale, Checked(g_scalePercent == 80), MENU_SCALE_80, L"80%");
AppendMenuW(scale, Checked(g_scalePercent == 100), MENU_SCALE_100, L"100%");
AppendMenuW(scale, Checked(g_scalePercent == 120), MENU_SCALE_120, L"120%");
AppendMenuW(scale, Checked(g_scalePercent == 140), MENU_SCALE_140, L"140%");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)scale, L"窗口缩放");
AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
AppendMenuW(menu, Checked(g_fullscreen), MENU_FULLSCREEN, L"全屏\tCtrl+Alt+F");
AppendMenuW(menu, Checked(g_topmost), MENU_TOPMOST, L"窗口置顶");
AppendMenuW(menu, MF_STRING, MENU_HIDE, L"隐藏到托盘");
AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
AppendMenuW(menu, MF_STRING, MENU_EXIT, L"退出\tCtrl+Alt+Q");
POINT pt; GetCursorPos(&pt);
SetForegroundWindow(hwnd);
UINT cmd = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, NULL);
DestroyMenu(menu);
if(cmd) SendMessageW(hwnd, WM_COMMAND, cmd, 0);
}
static void SetScale(int p)
{
if(g_fullscreen) return;
p = ClampInt(p, 80, 140);
if(g_scalePercent == p) return;
RECT r; GetWindowRect(g_hwnd, &r);
g_scalePercent = p;
int x = r.left, y = r.top; ClampCompactPosition(x, y);
DeleteFonts();
SetWindowPos(g_hwnd, NULL, x, y, CompactWindowW(), CompactWindowH(), SWP_NOZORDER | SWP_NOACTIVATE);
InvalidateBackdrop(); SaveState();
}
static void AddCurrentPreset()
{
long long sec = max(1LL, g_durationMs / 1000);
TimerItem item = { Trim(g_label).empty() ? FormatDurationSeconds(sec) : Trim(g_label), sec };
g_presets.erase(remove_if(g_presets.begin(), g_presets.end(), [&](const TimerItem& x)
{
return x.seconds == item.seconds && _wcsicmp(x.label.c_str(), item.label.c_str()) == 0;
}), g_presets.end());
g_presets.insert(g_presets.begin(), item);
if(g_presets.size() > 20) g_presets.resize(20);
SaveState();
}
// ============================================================
// Hotkeys
// ============================================================
static void RegisterHotkeys(HWND hwnd)
{
RegisterHotKey(hwnd, HOTKEY_TOGGLE, MOD_CONTROL | MOD_ALT, VK_SPACE);
RegisterHotKey(hwnd, HOTKEY_RESET, MOD_CONTROL | MOD_ALT, 'R');
RegisterHotKey(hwnd, HOTKEY_FULLSCREEN, MOD_CONTROL | MOD_ALT, 'F');
RegisterHotKey(hwnd, HOTKEY_SET_TIME, MOD_CONTROL | MOD_ALT, 'T');
RegisterHotKey(hwnd, HOTKEY_EXIT, MOD_CONTROL | MOD_ALT, 'Q');
}
static void UnregisterHotkeys(HWND hwnd)
{
UnregisterHotKey(hwnd, HOTKEY_TOGGLE);
UnregisterHotKey(hwnd, HOTKEY_RESET);
UnregisterHotKey(hwnd, HOTKEY_FULLSCREEN);
UnregisterHotKey(hwnd, HOTKEY_SET_TIME);
UnregisterHotKey(hwnd, HOTKEY_EXIT);
}
// ============================================================
// Main WndProc
// ============================================================
static bool PtIn(const RECT& r, POINT p) { return PtInRect(&r, p) != FALSE; }
static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CREATE:
g_hwnd = hwnd;
AddTrayIcon(hwnd);
RegisterHotkeys(hwnd);
SetTimer(hwnd, TIMER_REFRESH, 200, NULL);
return 0;
case WM_HOTKEY:
switch((int)wParam)
{
case HOTKEY_TOGGLE: ToggleCountdown(); break;
case HOTKEY_RESET: ResetCountdown(false); break;
case HOTKEY_FULLSCREEN: ToggleFullscreen(); break;
case HOTKEY_SET_TIME: ShowTimeInput(); break;
case HOTKEY_EXIT: DestroyWindow(hwnd); break;
}
return 0;
case WM_TRAYICON:
if(lParam == WM_LBUTTONDBLCLK) { ShowFromTray(hwnd); return 0; }
if(lParam == WM_RBUTTONUP || lParam == WM_CONTEXTMENU) { ShowContextMenu(hwnd, true); return 0; }
return 0;
case WM_NCHITTEST:
{
if(g_fullscreen) return HTCLIENT;
POINT p = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
ScreenToClient(hwnd, &p);
RECT wr = {}; GetClientRect(hwnd, &wr);
RECT c = ContentRectFor(wr.right - wr.left, wr.bottom - wr.top);
double d = RoundedRectSignedDistance(p.x + 0.5, p.y + 0.5, c, (double)Scaled(BASE_RADIUS));
return d <= 2.0 ? HTCLIENT : HTTRANSPARENT;
}
case WM_LBUTTONDOWN:
{
POINT p = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
if(PtIn(g_playRect, p)) { ToggleCountdown(); return 0; }
if(PtIn(g_resetRect, p)) { ResetCountdown(false); return 0; }
if(!IsRectEmpty(&g_closeRect) && PtIn(g_closeRect, p)) { DestroyWindow(hwnd); return 0; }
if(!g_fullscreen)
{
g_dragging = true; SetCapture(hwnd);
GetCursorPos(&g_dragStartMouse);
RECT r; GetWindowRect(hwnd, &r);
g_dragStartWindow.x = r.left; g_dragStartWindow.y = r.top;
}
return 0;
}
case WM_MOUSEMOVE:
if(g_dragging && !g_fullscreen)
{
POINT p; GetCursorPos(&p);
int x = g_dragStartWindow.x + (p.x - g_dragStartMouse.x);
int y = g_dragStartWindow.y + (p.y - g_dragStartMouse.y);
ClampCompactPosition(x, y);
SetWindowPos(hwnd, g_topmost ? HWND_TOPMOST : HWND_NOTOPMOST, x, y, 0, 0,
SWP_NOSIZE | SWP_NOACTIVATE);
InvalidateBackdrop();
}
return 0;
case WM_LBUTTONUP:
if(g_dragging) { g_dragging = false; ReleaseCapture(); SaveState(); }
return 0;
case WM_LBUTTONDBLCLK:
ToggleFullscreen();
return 0;
case WM_RBUTTONUP:
case WM_NCRBUTTONUP:
ShowContextMenu(hwnd, false);
return 0;
case WM_MOUSEWHEEL:
{
short d = GET_WHEEL_DELTA_WPARAM(wParam);
if(GetAsyncKeyState(VK_CONTROL) & 0x8000)
{
int next = g_scalePercent + (d > 0 ? 20 : -20);
if(next <= 80) next = 80; else if(next <= 100) next = 100; else if(next <= 120) next = 120; else next = 140;
SetScale(next);
}
else
{
g_bgOpacity = ClampInt(g_bgOpacity + (d > 0 ? 5 : -5), 0, 100);
SaveState(); InvalidateRect(hwnd, NULL, FALSE);
}
return 0;
}
case WM_COMMAND:
{
UINT id = LOWORD(wParam);
if(id >= MENU_PRESET_BASE && id < MENU_PRESET_BASE + 50)
{
size_t i = id - MENU_PRESET_BASE;
if(i < g_presets.size()) StartCountdown(g_presets[i].seconds, g_presets[i].label);
return 0;
}
if(id >= MENU_HISTORY_BASE && id < MENU_HISTORY_BASE + 50)
{
size_t i = id - MENU_HISTORY_BASE;
if(i < g_history.size()) StartCountdown(g_history[i].seconds, g_history[i].label);
return 0;
}
if(id >= MENU_THEME_BASE && id < MENU_THEME_BASE + THEME_COUNT)
{
g_theme = (ThemeMode)(id - MENU_THEME_BASE); SaveState(); InvalidateBackdrop(); return 0;
}
if(id >= MENU_OPACITY_BASE && id < MENU_OPACITY_BASE + 6)
{
const int op[6] = {0,20,40,60,80,100};
g_bgOpacity = op[id - MENU_OPACITY_BASE]; SaveState(); InvalidateRect(hwnd, NULL, FALSE); return 0;
}
switch(id)
{
case MENU_SET_TIME: ShowTimeInput(); break;
case MENU_TOGGLE: ToggleCountdown(); break;
case MENU_RESET: ResetCountdown(false); break;
case MENU_RESTART: ResetCountdown(true); AddHistory(g_label, g_durationMs / 1000); SaveState(); break;
case MENU_PRESET_ADD_CURRENT: AddCurrentPreset(); break;
case MENU_PRESET_CLEAR: g_presets.clear(); SaveState(); break;
case MENU_HISTORY_CLEAR: g_history.clear(); SaveState(); break;
case MENU_ZONE_LOCAL: g_zone = ZONE_LOCAL; SaveState(); InvalidateRect(hwnd,NULL,FALSE); break;
case MENU_ZONE_UTC: g_zone = ZONE_UTC; SaveState(); InvalidateRect(hwnd,NULL,FALSE); break;
case MENU_ZONE_BEIJING: g_zone = ZONE_BEIJING; SaveState(); InvalidateRect(hwnd,NULL,FALSE); break;
case MENU_ZONE_LONDON: g_zone = ZONE_LONDON; SaveState(); InvalidateRect(hwnd,NULL,FALSE); break;
case MENU_ZONE_NEWYORK: g_zone = ZONE_NEWYORK; SaveState(); InvalidateRect(hwnd,NULL,FALSE); break;
case MENU_ZONE_TOKYO: g_zone = ZONE_TOKYO; SaveState(); InvalidateRect(hwnd,NULL,FALSE); break;
case MENU_THEME_CUSTOM_BG:
if(PickColor(hwnd, g_customBg)) { g_bgMode = BG_SOLID; SaveState(); InvalidateBackdrop(); }
break;
case MENU_TEXT_AUTO:
g_autoText = !g_autoText; SaveState(); InvalidateRect(hwnd,NULL,FALSE); break;
case MENU_TEXT_PICK:
if(PickColor(hwnd, g_customText)) { g_autoText = false; SaveState(); InvalidateRect(hwnd,NULL,FALSE); }
break;
case MENU_BG_THEME: g_bgMode = BG_THEME; SaveState(); InvalidateBackdrop(); break;
case MENU_BG_GLASS: g_bgMode = BG_GLASS; SaveState(); InvalidateBackdrop(); break;
case MENU_BG_IMAGE:
if(!g_bgImage)
{
if(PickBackgroundFile(hwnd, g_bgImagePath)) LoadBackgroundImage();
}
if(g_bgImage) g_bgMode = BG_IMAGE;
SaveState(); InvalidateBackdrop(); break;
case MENU_BG_IMAGE_PICK:
if(PickBackgroundFile(hwnd, g_bgImagePath)) { LoadBackgroundImage(); g_bgMode = BG_IMAGE; SaveState(); }
break;
case MENU_BG_SOLID_PICK:
if(PickColor(hwnd, g_customBg)) { g_bgMode = BG_SOLID; SaveState(); InvalidateBackdrop(); }
break;
case MENU_BG_IMAGE_CLEAR:
g_bgImagePath.clear(); LoadBackgroundImage(); if(g_bgMode == BG_IMAGE) g_bgMode = BG_GLASS; SaveState(); break;
case MENU_BLUR_OFF: g_blurStrength = 0; SaveState(); InvalidateBackdrop(); break;
case MENU_BLUR_SOFT: g_blurStrength = 1; SaveState(); InvalidateBackdrop(); break;
case MENU_BLUR_STRONG: g_blurStrength = 2; SaveState(); InvalidateBackdrop(); break;
case MENU_SCALE_80: SetScale(80); break;
case MENU_SCALE_100: SetScale(100); break;
case MENU_SCALE_120: SetScale(120); break;
case MENU_SCALE_140: SetScale(140); break;
case MENU_FULLSCREEN: ToggleFullscreen(); break;
case MENU_TOPMOST: g_topmost = !g_topmost; ApplyTopmost(); SaveState(); break;
case MENU_HIDE: HideToTray(hwnd); break;
case MENU_SHOW: ShowFromTray(hwnd); break;
case MENU_EXIT: DestroyWindow(hwnd); break;
}
return 0;
}
case WM_TIMER:
if(wParam == TIMER_REFRESH)
{
UpdateFinishState();
if(IsWindowVisible(hwnd)) InvalidateRect(hwnd, NULL, FALSE);
}
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps; BeginPaint(hwnd, &ps); EndPaint(hwnd, &ps);
RenderLayeredWindow(hwnd); return 0;
}
case WM_ERASEBKGND: return 1;
case WM_DISPLAYCHANGE:
case WM_SETTINGCHANGE:
if(g_fullscreen)
{
HMONITOR mon = MonitorForWindowSafe(hwnd);
MONITORINFO mi = { sizeof(mi) }; GetMonitorInfoW(mon, &mi);
SetWindowPos(hwnd, g_topmost ? HWND_TOPMOST : HWND_NOTOPMOST,
mi.rcMonitor.left, mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
SWP_NOACTIVATE);
}
InvalidateBackdrop(); return 0;
case WM_SIZE:
DeleteFonts(); InvalidateBackdrop(); return 0;
case WM_DESTROY:
KillTimer(hwnd, TIMER_REFRESH);
UnregisterHotkeys(hwnd);
RemoveTrayIcon();
SaveState();
DeleteFonts();
if(g_inputWnd) DestroyWindow(g_inputWnd);
if(g_bgImage) { delete g_bgImage; g_bgImage = NULL; }
g_hwnd = NULL;
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
// ============================================================
// WinMain: GUI subsystem, no console window
// ============================================================
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
g_hInstance = hInstance;
EnsureConfigPath();
LoadState();
GdiplusStartupInput gdiplusStartupInput;
if(GdiplusStartup(&g_gdiplusToken, &gdiplusStartupInput, NULL) != Ok)
return 1;
LoadBackgroundImage();
WNDCLASSEXW wc = {};
wc.cbSize = sizeof(wc);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
wc.hIcon = LoadIconW(NULL, IDI_APPLICATION);
wc.hIconSm = LoadIconW(NULL, IDI_APPLICATION);
wc.hbrBackground = NULL;
wc.lpszClassName = L"GlassCountdownMainWindow";
if(!RegisterClassExW(&wc)) { GdiplusShutdown(g_gdiplusToken); return 1; }
WNDCLASSEXW iwc = {};
iwc.cbSize = sizeof(iwc);
iwc.style = CS_HREDRAW | CS_VREDRAW;
iwc.lpfnWndProc = InputWndProc;
iwc.hInstance = hInstance;
iwc.hCursor = LoadCursorW(NULL, IDC_ARROW);
iwc.hIcon = LoadIconW(NULL, IDI_APPLICATION);
iwc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
iwc.lpszClassName = L"GlassCountdownInputWindow";
RegisterClassExW(&iwc);
DWORD exStyle = WS_EX_TOOLWINDOW | WS_EX_LAYERED | WS_EX_NOACTIVATE;
if(g_topmost) exStyle |= WS_EX_TOPMOST;
int x = IniReadInt(L"Window", L"X", CW_USEDEFAULT);
int y = IniReadInt(L"Window", L"Y", CW_USEDEFAULT);
HWND hwnd = CreateWindowExW(exStyle, L"GlassCountdownMainWindow", L"Glass Countdown",
WS_POPUP, x, y, CompactWindowW(), CompactWindowH(),
NULL, NULL, hInstance, NULL);
if(!hwnd)
{
GdiplusShutdown(g_gdiplusToken);
return 1;
}
g_hwnd = hwnd;
if(x == CW_USEDEFAULT || y == CW_USEDEFAULT)
PutBottomRight(hwnd);
else
{
int px = x, py = y; ClampCompactPosition(px, py);
SetWindowPos(hwnd, g_topmost ? HWND_TOPMOST : HWND_NOTOPMOST,
px, py, CompactWindowW(), CompactWindowH(), SWP_NOACTIVATE);
}
ShowWindow(hwnd, SW_SHOWNOACTIVATE);
UpdateWindow(hwnd);
RenderLayeredWindow(hwnd);
MSG msg;
while(GetMessageW(&msg, NULL, 0, 0) > 0)
{
if(g_inputWnd && IsDialogMessageW(g_inputWnd, &msg)) continue;
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
if(g_gdiplusToken) GdiplusShutdown(g_gdiplusToken);
return (int)msg.wParam;
}