-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtray_icon_win.cpp
More file actions
2246 lines (2046 loc) · 81.5 KB
/
Copy pathtray_icon_win.cpp
File metadata and controls
2246 lines (2046 loc) · 81.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Windows 系统托盘图标实现。
//
// 设计 / 决策见:
// - openspec/changes/enhance-desktop-tray-menu/design.md(小图标 / 双击 / Codex 菜单)
#include "tray_icon_win.hpp"
#include "tray_menu_layout.hpp"
#include "tray_menu_popup_model.hpp"
#include "../utils/encoding.hpp"
#include "../utils/logger.hpp"
#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <windows.h>
# include <shellapi.h>
#endif
#ifdef __APPLE__
# import <AppKit/AppKit.h>
#endif
#include <algorithm>
#include <cmath>
#include <memory>
#include <mutex>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#if !defined(_WIN32) && !defined(__APPLE__)
# include <dlfcn.h>
# include <filesystem>
# include <limits.h>
# include <unistd.h>
#endif
#ifdef __APPLE__
namespace acecode::desktop {
void mac_tray_menu_item_activated(long tag);
void mac_tray_status_item_activated();
void mac_tray_menu_needs_update(NSMenu* menu);
}
@interface ACECodeTrayMenuTarget : NSObject <NSMenuDelegate>
- (void)menuItemActivated:(id)sender;
- (void)statusItemActivated:(id)sender;
@end
@implementation ACECodeTrayMenuTarget
- (void)menuItemActivated:(id)sender {
if (![sender respondsToSelector:@selector(tag)]) return;
acecode::desktop::mac_tray_menu_item_activated([sender tag]);
}
- (void)statusItemActivated:(id)sender {
(void)sender;
acecode::desktop::mac_tray_status_item_activated();
}
- (void)menuNeedsUpdate:(NSMenu*)menu {
acecode::desktop::mac_tray_menu_needs_update(menu);
}
@end
#endif
namespace acecode::desktop {
namespace {
// 菜单 payload + handlers,主线程读 + 多线程写,统一上锁。Win32 和 Linux
// 后端共享这份状态,避免复制 pinned/recent/new/open/quit 的分发规则。
std::mutex g_payload_mu;
TrayMenuPayload g_payload;
TraySessionClickHandler g_session_click_handler;
TrayClickHandler g_new_chat_handler;
TrayClickHandler g_open_app_handler;
TrayClickHandler g_on_show;
TrayClickHandler g_on_quit;
TrayMenuPayload snapshot_payload() {
std::lock_guard<std::mutex> lk(g_payload_mu);
return g_payload;
}
TraySessionClickHandler get_session_click_handler() {
std::lock_guard<std::mutex> lk(g_payload_mu);
return g_session_click_handler;
}
TrayClickHandler get_new_chat_handler() {
std::lock_guard<std::mutex> lk(g_payload_mu);
return g_new_chat_handler;
}
TrayClickHandler get_open_app_handler() {
std::lock_guard<std::mutex> lk(g_payload_mu);
return g_open_app_handler;
}
bool dispatch_session_click(const TrayMenuLayout& layout, unsigned cmd) {
for (const auto& e : layout.entries) {
if (e.id == cmd && (e.kind == TrayMenuEntryKind::PinnedItem ||
e.kind == TrayMenuEntryKind::RecentItem ||
e.kind == TrayMenuEntryKind::MoreSubmenuItem)) {
auto handler = get_session_click_handler();
if (handler) handler(e.workspace_hash, e.session_id);
return true;
}
}
return false;
}
void dispatch_menu_command(const TrayMenuLayout& layout, unsigned cmd) {
if (cmd == 0) return;
if (cmd == kMenuIdShow || cmd == kMenuIdOpenApp) {
auto h = get_open_app_handler();
if (h) h();
else if (g_on_show) g_on_show();
} else if (cmd == kMenuIdQuit) {
if (g_on_quit) g_on_quit();
} else if (cmd == kMenuIdNewChat) {
auto h = get_new_chat_handler();
if (h) h();
} else {
dispatch_session_click(layout, cmd);
}
}
void reset_tray_state() {
g_on_show = nullptr;
g_on_quit = nullptr;
std::lock_guard<std::mutex> lk(g_payload_mu);
g_payload = TrayMenuPayload{};
g_session_click_handler = nullptr;
g_new_chat_handler = nullptr;
g_open_app_handler = nullptr;
}
} // namespace
#ifdef _WIN32
namespace {
constexpr wchar_t kTrayWndClass[] = L"ACECodeDesktopTrayWindow";
constexpr UINT kTrayIconUid = 0xACEC; // 任意常量,保持稳定即可
constexpr wchar_t kAppIconResourceName[] = L"IDI_ICON1";
constexpr int kAppIconResourceId = 1;
UINT g_tray_callback_msg = 0; // 由 RegisterWindowMessageW 注册,避免与其他 WM_USER 撞号
HWND g_tray_window = nullptr;
NOTIFYICONDATAW g_nid{};
bool g_icon_added = false;
constexpr wchar_t kTrayPopupWndClass[] = L"ACECodeDesktopTrayPopupWindow";
constexpr UINT kTrayPopupDismissMessage = WM_APP + 0x351;
constexpr int kTrayPopupWidthDip = 280;
constexpr int kTrayPopupRowHeightHalfDip = 55;
// Match Windows menu metrics (~9pt Segoe UI = 12 device px at 96 DPI).
// 13 made the custom tray menu read heavier than shell menus at 100%.
constexpr int kTrayPopupFontHeightDip = 12;
constexpr int kTrayPopupChromeInsetDip = 16;
constexpr int kTrayPopupShadowBlurDip = 12;
constexpr int kTrayPopupShadowOffsetYDip = 2;
constexpr int kTrayPopupShadowMaxAlpha = 46;
struct TrayPopupDpiApi {
using SetThreadDpiAwarenessContextFn = HANDLE(WINAPI*)(HANDLE);
using GetThreadDpiAwarenessContextFn = HANDLE(WINAPI*)();
using GetWindowDpiAwarenessContextFn = HANDLE(WINAPI*)(HWND);
using GetAwarenessFromDpiAwarenessContextFn = int(WINAPI*)(HANDLE);
using GetDpiForSystemFn = UINT(WINAPI*)();
using GetDpiForWindowFn = UINT(WINAPI*)(HWND);
SetThreadDpiAwarenessContextFn set_thread_context = nullptr;
GetThreadDpiAwarenessContextFn get_thread_context = nullptr;
GetWindowDpiAwarenessContextFn get_window_context = nullptr;
GetAwarenessFromDpiAwarenessContextFn get_awareness = nullptr;
GetDpiForSystemFn get_system_dpi = nullptr;
GetDpiForWindowFn get_window_dpi = nullptr;
TrayPopupDpiApi() {
HMODULE user32 = ::GetModuleHandleW(L"user32.dll");
if (!user32) return;
set_thread_context =
reinterpret_cast<SetThreadDpiAwarenessContextFn>(
::GetProcAddress(user32, "SetThreadDpiAwarenessContext"));
get_thread_context =
reinterpret_cast<GetThreadDpiAwarenessContextFn>(
::GetProcAddress(user32, "GetThreadDpiAwarenessContext"));
get_window_context =
reinterpret_cast<GetWindowDpiAwarenessContextFn>(
::GetProcAddress(user32, "GetWindowDpiAwarenessContext"));
get_awareness =
reinterpret_cast<GetAwarenessFromDpiAwarenessContextFn>(
::GetProcAddress(user32, "GetAwarenessFromDpiAwarenessContext"));
get_system_dpi = reinterpret_cast<GetDpiForSystemFn>(
::GetProcAddress(user32, "GetDpiForSystem"));
get_window_dpi = reinterpret_cast<GetDpiForWindowFn>(
::GetProcAddress(user32, "GetDpiForWindow"));
}
};
const TrayPopupDpiApi& tray_popup_dpi_api() {
static const TrayPopupDpiApi api;
return api;
}
TrayPopupDpiAwareness tray_popup_dpi_awareness_from_raw(int awareness) {
switch (awareness) {
case 0:
return TrayPopupDpiAwareness::Unaware;
case 1:
return TrayPopupDpiAwareness::SystemAware;
case 2:
return TrayPopupDpiAwareness::PerMonitorAware;
default:
return TrayPopupDpiAwareness::Unknown;
}
}
const char* tray_popup_dpi_awareness_name(TrayPopupDpiAwareness awareness) {
switch (awareness) {
case TrayPopupDpiAwareness::Unaware:
return "unaware";
case TrayPopupDpiAwareness::SystemAware:
return "system";
case TrayPopupDpiAwareness::PerMonitorAware:
return "per-monitor";
case TrayPopupDpiAwareness::Unknown:
return "unknown";
}
return "unknown";
}
TrayPopupDpiAwareness current_thread_dpi_awareness() {
const auto& api = tray_popup_dpi_api();
if (api.get_thread_context && api.get_awareness) {
return tray_popup_dpi_awareness_from_raw(
api.get_awareness(api.get_thread_context()));
}
if (HMODULE shcore = ::LoadLibraryW(L"Shcore.dll")) {
using GetProcessDpiAwarenessFn = HRESULT(WINAPI*)(HANDLE, int*);
auto get_process_awareness =
reinterpret_cast<GetProcessDpiAwarenessFn>(
::GetProcAddress(shcore, "GetProcessDpiAwareness"));
int awareness = -1;
if (get_process_awareness &&
SUCCEEDED(get_process_awareness(::GetCurrentProcess(), &awareness))) {
::FreeLibrary(shcore);
return tray_popup_dpi_awareness_from_raw(awareness);
}
::FreeLibrary(shcore);
}
return TrayPopupDpiAwareness::Unknown;
}
TrayPopupDpiAwareness window_dpi_awareness(HWND hwnd) {
const auto& api = tray_popup_dpi_api();
if (hwnd && api.get_window_context && api.get_awareness) {
return tray_popup_dpi_awareness_from_raw(
api.get_awareness(api.get_window_context(hwnd)));
}
return TrayPopupDpiAwareness::Unknown;
}
int current_system_dpi() {
const auto& api = tray_popup_dpi_api();
if (api.get_system_dpi) {
const UINT dpi = api.get_system_dpi();
if (dpi > 0) return static_cast<int>(dpi);
}
HDC hdc = ::GetDC(nullptr);
const int dpi = hdc ? ::GetDeviceCaps(hdc, LOGPIXELSX) : 96;
if (hdc) ::ReleaseDC(nullptr, hdc);
return dpi > 0 ? dpi : 96;
}
int window_dpi(HWND hwnd) {
const auto& api = tray_popup_dpi_api();
if (hwnd && api.get_window_dpi) {
const UINT dpi = api.get_window_dpi(hwnd);
if (dpi > 0) return static_cast<int>(dpi);
}
return 0;
}
class ScopedTrayPopupDpiContext {
public:
ScopedTrayPopupDpiContext() {
set_context_ = tray_popup_dpi_api().set_thread_context;
if (!set_context_) return;
constexpr INT_PTR kPerMonitorAwareV2 = -4;
previous_context_ =
set_context_(reinterpret_cast<HANDLE>(kPerMonitorAwareV2));
if (previous_context_) {
requested_context_ = "per-monitor-v2";
return;
}
constexpr INT_PTR kPerMonitorAware = -3;
previous_context_ =
set_context_(reinterpret_cast<HANDLE>(kPerMonitorAware));
if (previous_context_) requested_context_ = "per-monitor";
}
ScopedTrayPopupDpiContext(const ScopedTrayPopupDpiContext&) = delete;
ScopedTrayPopupDpiContext& operator=(const ScopedTrayPopupDpiContext&) =
delete;
~ScopedTrayPopupDpiContext() {
if (set_context_ && previous_context_) {
set_context_(previous_context_);
}
}
const char* requested_context_name() const {
return requested_context_;
}
private:
TrayPopupDpiApi::SetThreadDpiAwarenessContextFn set_context_ = nullptr;
HANDLE previous_context_ = nullptr;
const char* requested_context_ = "unchanged";
};
struct Win32TrayPopupMetrics {
int layout_dpi = 96;
int text_scale_percent = 100;
int font_height = kTrayPopupFontHeightDip;
int width = kTrayPopupWidthDip;
int outer_padding = 8;
int horizontal_padding = 20;
int text_gap = 16;
int header_height = (kTrayPopupRowHeightHalfDip + 1) / 2;
int item_height = (kTrayPopupRowHeightHalfDip + 1) / 2;
int action_height = (kTrayPopupRowHeightHalfDip + 1) / 2;
int separator_height = 17;
int corner_radius = 12;
int right_column_width = 0;
int chrome_inset = kTrayPopupChromeInsetDip;
int shadow_blur = kTrayPopupShadowBlurDip;
int shadow_offset_y = kTrayPopupShadowOffsetYDip;
int shadow_max_alpha = kTrayPopupShadowMaxAlpha;
};
struct Win32TrayPopupRow {
TrayPopupRow model;
int top = 0;
int height = 0;
};
struct Win32TrayPopupController;
struct Win32TrayPopupWindow {
Win32TrayPopupController* controller = nullptr;
HWND hwnd = nullptr;
bool is_submenu = false;
Win32TrayPopupMetrics metrics;
std::vector<Win32TrayPopupRow> rows;
int content_height = 0;
int viewport_height = 0;
int scroll_offset = 0;
int hovered_index = -1;
HFONT font = nullptr;
bool repaint_failure_logged = false;
~Win32TrayPopupWindow() {
if (font) ::DeleteObject(font);
}
};
struct Win32TrayPopupController {
TrayMenuLayout layout;
std::unique_ptr<Win32TrayPopupWindow> main_window;
std::unique_ptr<Win32TrayPopupWindow> submenu_window;
int main_more_index = -1;
bool keyboard_in_submenu = false;
bool closing = false;
// While true, ignore WA_INACTIVE dismiss. UpdateLayeredWindow makes the
// layered HWND visible; a subsequent SetForegroundWindow(owner) would
// otherwise deactivate it and post-dismiss the menu before it is usable.
bool suppress_deactivate_dismiss = false;
};
std::unique_ptr<Win32TrayPopupController> g_tray_popup;
LRESULT CALLBACK tray_popup_wnd_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);
int scale_px(int value, int dpi) {
return scale_tray_popup_size_px(value, dpi);
}
int scale_half_dip(int half_dip_value, int dpi) {
return ::MulDiv(half_dip_value, dpi > 0 ? dpi : 96, 96 * 2);
}
int windows_text_scale_percent() {
// "Make text bigger" is independent from monitor DPI. The registry value
// is absent at the default 100%, so failure deliberately means 100%.
DWORD value = 100;
DWORD value_size = sizeof(value);
const LONG result = ::RegGetValueW(
HKEY_CURRENT_USER,
L"Software\\Microsoft\\Accessibility",
L"TextScaleFactor",
RRF_RT_REG_DWORD,
nullptr,
&value,
&value_size);
if (result != ERROR_SUCCESS || value_size != sizeof(value)) {
return 100;
}
return normalize_tray_popup_text_scale_percent(static_cast<int>(value));
}
int query_monitor_effective_dpi(HMONITOR monitor) {
if (HMODULE shcore = ::LoadLibraryW(L"Shcore.dll")) {
using GetDpiForMonitorFn =
HRESULT(WINAPI*)(HMONITOR, int, UINT*, UINT*);
auto get_dpi = reinterpret_cast<GetDpiForMonitorFn>(
::GetProcAddress(shcore, "GetDpiForMonitor"));
UINT dpi_x = 0;
UINT dpi_y = 0;
constexpr int kMdtEffectiveDpi = 0;
if (get_dpi &&
SUCCEEDED(get_dpi(monitor, kMdtEffectiveDpi, &dpi_x, &dpi_y)) &&
dpi_x > 0) {
::FreeLibrary(shcore);
return static_cast<int>(dpi_x);
}
::FreeLibrary(shcore);
}
return 0;
}
int query_monitor_scale_factor_dpi_unaware(HMONITOR monitor) {
// GetScaleFactorForMonitor is only trustworthy while the calling thread is
// DPI-unaware. Query under a temporary unaware context, then restore.
const auto& api = tray_popup_dpi_api();
HANDLE previous = nullptr;
if (api.set_thread_context) {
constexpr INT_PTR kUnaware = -1; // DPI_AWARENESS_CONTEXT_UNAWARE
previous = api.set_thread_context(reinterpret_cast<HANDLE>(kUnaware));
}
int dpi = 0;
if (HMODULE shcore = ::LoadLibraryW(L"Shcore.dll")) {
using GetScaleFactorForMonitorFn = HRESULT(WINAPI*)(HMONITOR, int*);
auto get_scale_factor = reinterpret_cast<GetScaleFactorForMonitorFn>(
::GetProcAddress(shcore, "GetScaleFactorForMonitor"));
int scale_percent = 100;
if (get_scale_factor &&
SUCCEEDED(get_scale_factor(monitor, &scale_percent))) {
dpi = compute_tray_popup_geometry_dpi_from_monitor_scale_percent(
scale_percent);
}
::FreeLibrary(shcore);
}
if (api.set_thread_context) {
if (previous) {
api.set_thread_context(previous);
} else {
// Best-effort restore to per-monitor-v2 when the previous context
// handle was not reported.
constexpr INT_PTR kPerMonitorAwareV2 = -4;
api.set_thread_context(
reinterpret_cast<HANDLE>(kPerMonitorAwareV2));
}
}
return dpi;
}
int point_target_monitor_dpi(POINT pt, int& monitor_scale_percent) {
// Resolve the target monitor's DPI from two sources and merge them. A bare
// GetDpiForMonitor call while per-monitor-aware is preferred when it
// reports a real scale, but some sessions report 96 for every monitor even
// though the shell is clearly scaled — in that case the unaware
// GetScaleFactorForMonitor sample recovers the configured scale.
monitor_scale_percent = 100;
HMONITOR monitor = ::MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
const int from_get_dpi = query_monitor_effective_dpi(monitor);
const int from_scale_unaware =
query_monitor_scale_factor_dpi_unaware(monitor);
const int resolved = resolve_tray_popup_target_monitor_dpi(
from_get_dpi,
from_scale_unaware);
monitor_scale_percent =
compute_tray_popup_monitor_scale_percent_from_dpi(resolved);
LOG_INFO(
"[desktop] tray popup monitor DPI samples: get_dpi=" +
std::to_string(from_get_dpi) +
", scale_unaware=" + std::to_string(from_scale_unaware) +
", resolved=" + std::to_string(resolved));
return resolved;
}
HFONT create_popup_font(int font_height_px) {
return ::CreateFontW(
-std::max(1, font_height_px),
0,
0,
0,
FW_NORMAL,
FALSE,
FALSE,
FALSE,
DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_DONTCARE,
L"Segoe UI");
}
int measure_text_width(HDC hdc, const std::wstring& text) {
if (!hdc || text.empty()) return 0;
SIZE size{};
if (::GetTextExtentPoint32W(hdc, text.c_str(), static_cast<int>(text.size()), &size)) {
return size.cx;
}
RECT rc{0, 0, 0, 0};
::DrawTextW(hdc,
text.c_str(),
static_cast<int>(text.size()),
&rc,
DT_SINGLELINE | DT_CALCRECT | DT_NOPREFIX);
return rc.right - rc.left;
}
Win32TrayPopupMetrics compute_popup_metrics(
const TrayMenuLayout& layout,
int layout_dpi,
int text_scale_percent) {
Win32TrayPopupMetrics metrics;
metrics.layout_dpi = layout_dpi;
metrics.text_scale_percent =
normalize_tray_popup_text_scale_percent(text_scale_percent);
metrics.font_height = compute_tray_popup_font_height_px(
kTrayPopupFontHeightDip,
layout_dpi,
metrics.text_scale_percent);
HDC hdc = ::GetDC(nullptr);
HFONT font = create_popup_font(metrics.font_height);
HGDIOBJ old_font = nullptr;
if (hdc && font) old_font = ::SelectObject(hdc, font);
int max_subtitle_width = 0;
for (const auto& e : layout.entries) {
if (!tray_popup_entry_is_session(e.kind)) continue;
max_subtitle_width = std::max(max_subtitle_width, measure_text_width(hdc, utf8_to_wide(e.subtitle)));
}
if (old_font) ::SelectObject(hdc, old_font);
if (font) ::DeleteObject(font);
if (hdc) ::ReleaseDC(nullptr, hdc);
metrics.outer_padding = scale_px(8, layout_dpi);
metrics.horizontal_padding = scale_px(20, layout_dpi);
metrics.text_gap = scale_px(16, layout_dpi);
const int geometry_row_height =
scale_half_dip(kTrayPopupRowHeightHalfDip, layout_dpi);
const int text_row_height = compute_tray_popup_text_row_height(
geometry_row_height,
metrics.font_height,
scale_px(12, layout_dpi));
metrics.header_height = text_row_height;
metrics.item_height = text_row_height;
metrics.action_height = text_row_height;
metrics.separator_height = std::max(1, scale_px(1, layout_dpi));
metrics.corner_radius = scale_px(12, layout_dpi);
metrics.chrome_inset = scale_px(kTrayPopupChromeInsetDip, layout_dpi);
metrics.shadow_blur = scale_px(kTrayPopupShadowBlurDip, layout_dpi);
metrics.shadow_offset_y = scale_px(kTrayPopupShadowOffsetYDip, layout_dpi);
metrics.shadow_max_alpha = kTrayPopupShadowMaxAlpha;
if (max_subtitle_width > 0) {
metrics.right_column_width = std::clamp(
max_subtitle_width,
scale_px(64, layout_dpi),
scale_px(104, layout_dpi));
}
metrics.width = scale_px(kTrayPopupWidthDip, layout_dpi);
return metrics;
}
int popup_row_height(TrayMenuEntryKind kind, const Win32TrayPopupMetrics& metrics) {
if (tray_popup_entry_is_header(kind)) return metrics.header_height;
if (kind == TrayMenuEntryKind::Separator) return metrics.separator_height;
if (tray_popup_entry_is_fixed_action(kind)) return metrics.action_height;
return metrics.item_height;
}
std::unique_ptr<Win32TrayPopupWindow> make_popup_window_state(
Win32TrayPopupController* controller,
bool is_submenu,
std::vector<TrayPopupRow> rows,
const Win32TrayPopupMetrics& metrics) {
auto state = std::make_unique<Win32TrayPopupWindow>();
state->controller = controller;
state->is_submenu = is_submenu;
state->metrics = metrics;
state->font = create_popup_font(metrics.font_height);
int top = 0;
for (auto& row : rows) {
Win32TrayPopupRow view;
view.model = std::move(row);
view.top = top;
view.height = popup_row_height(view.model.entry.kind, metrics);
top += view.height;
state->rows.push_back(std::move(view));
}
state->content_height = top;
return state;
}
RECT monitor_work_area(POINT pt) {
MONITORINFO info{};
info.cbSize = sizeof(info);
HMONITOR monitor = ::MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
if (::GetMonitorInfoW(monitor, &info)) return info.rcWork;
return RECT{0, 0, ::GetSystemMetrics(SM_CXSCREEN), ::GetSystemMetrics(SM_CYSCREEN)};
}
RECT monitor_bounds(POINT pt) {
MONITORINFO info{};
info.cbSize = sizeof(info);
HMONITOR monitor = ::MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
if (::GetMonitorInfoW(monitor, &info)) return info.rcMonitor;
return RECT{0, 0, ::GetSystemMetrics(SM_CXSCREEN), ::GetSystemMetrics(SM_CYSCREEN)};
}
TrayPopupChromeGeometry popup_chrome_geometry(
const Win32TrayPopupWindow& state,
int surface_x,
int surface_y) {
return compute_tray_popup_chrome_geometry(
surface_x,
surface_y,
state.metrics.width,
state.viewport_height,
state.metrics.chrome_inset);
}
RECT popup_surface_screen_rect(const Win32TrayPopupWindow& state) {
RECT window{};
if (!state.hwnd || !::GetWindowRect(state.hwnd, &window)) return {};
const auto chrome = popup_chrome_geometry(state, 0, 0);
return {
window.left + chrome.surface_left,
window.top + chrome.surface_top,
window.left + chrome.surface_left + chrome.surface_width,
window.top + chrome.surface_top + chrome.surface_height,
};
}
bool popup_point_in_surface(
const Win32TrayPopupWindow& state,
int window_x,
int window_y) {
return tray_popup_point_in_rounded_surface(
popup_chrome_geometry(state, 0, 0),
window_x,
window_y,
state.metrics.corner_radius);
}
int max_popup_scroll(const Win32TrayPopupWindow& state) {
const int visible_content = std::max(
0,
state.viewport_height - state.metrics.outer_padding * 2);
return std::max(0, state.content_height - visible_content);
}
void set_popup_scroll(Win32TrayPopupWindow& state, int next) {
const int clamped = std::clamp(next, 0, max_popup_scroll(state));
if (clamped == state.scroll_offset) return;
state.scroll_offset = clamped;
if (state.hwnd) ::InvalidateRect(state.hwnd, nullptr, FALSE);
}
void ensure_popup_row_visible(Win32TrayPopupWindow& state, int index) {
if (index < 0 || index >= static_cast<int>(state.rows.size())) return;
const auto& row = state.rows[static_cast<std::size_t>(index)];
const int visible_height = std::max(
0,
state.viewport_height - state.metrics.outer_padding * 2);
if (row.top < state.scroll_offset) {
set_popup_scroll(state, row.top);
} else if (row.top + row.height > state.scroll_offset + visible_height) {
set_popup_scroll(state, row.top + row.height - visible_height);
}
}
int popup_row_at(const Win32TrayPopupWindow& state, int x, int y) {
const auto chrome = popup_chrome_geometry(state, 0, 0);
if (!tray_popup_point_in_rounded_surface(
chrome, x, y, state.metrics.corner_radius)) {
return -1;
}
const int surface_y = y - chrome.surface_top;
const int content_y =
surface_y - state.metrics.outer_padding + state.scroll_offset;
for (std::size_t i = 0; i < state.rows.size(); ++i) {
const auto& row = state.rows[i];
if (content_y >= row.top && content_y < row.top + row.height) {
return static_cast<int>(i);
}
}
return -1;
}
void fill_rounded_rect(HDC hdc, const RECT& rect, int radius, COLORREF color) {
const int diameter = std::max(1, radius * 2);
HRGN region = ::CreateRoundRectRgn(
rect.left,
rect.top,
rect.right + 1,
rect.bottom + 1,
diameter,
diameter);
HBRUSH brush = ::CreateSolidBrush(color);
if (region && brush) ::FillRgn(hdc, region, brush);
if (brush) ::DeleteObject(brush);
if (region) ::DeleteObject(region);
}
void draw_popup_chevron(HDC hdc, const RECT& row_rect, const Win32TrayPopupMetrics& metrics) {
const int center_x = row_rect.right - metrics.horizontal_padding;
const int center_y = (row_rect.top + row_rect.bottom) / 2;
const int half = scale_px(3, metrics.layout_dpi);
HPEN pen = ::CreatePen(
PS_SOLID,
std::max(1, scale_px(1, metrics.layout_dpi)),
RGB(76, 76, 76));
HGDIOBJ old_pen = pen ? ::SelectObject(hdc, pen) : nullptr;
::MoveToEx(hdc, center_x - half, center_y - half, nullptr);
::LineTo(hdc, center_x, center_y);
::LineTo(hdc, center_x - half, center_y + half);
if (old_pen) ::SelectObject(hdc, old_pen);
if (pen) ::DeleteObject(pen);
}
struct Win32LayeredDib {
HDC screen = nullptr;
HDC memory = nullptr;
HBITMAP bitmap = nullptr;
HGDIOBJ old_bitmap = nullptr;
std::uint32_t* pixels = nullptr;
~Win32LayeredDib() {
if (old_bitmap && memory) ::SelectObject(memory, old_bitmap);
if (bitmap) ::DeleteObject(bitmap);
if (memory) ::DeleteDC(memory);
if (screen) ::ReleaseDC(nullptr, screen);
}
bool create(int width, int height) {
if (width <= 0 || height <= 0) return false;
screen = ::GetDC(nullptr);
if (!screen) return false;
memory = ::CreateCompatibleDC(screen);
if (!memory) return false;
BITMAPINFO info{};
info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth = width;
info.bmiHeader.biHeight = -height;
info.bmiHeader.biPlanes = 1;
info.bmiHeader.biBitCount = 32;
info.bmiHeader.biCompression = BI_RGB;
void* bits = nullptr;
bitmap = ::CreateDIBSection(
screen, &info, DIB_RGB_COLORS, &bits, nullptr, 0);
if (!bitmap || !bits) return false;
old_bitmap = ::SelectObject(memory, bitmap);
if (!old_bitmap || old_bitmap == HGDI_ERROR) {
old_bitmap = nullptr;
return false;
}
pixels = static_cast<std::uint32_t*>(bits);
return true;
}
};
std::uint8_t popup_surface_coverage(double signed_distance) {
const double coverage = std::clamp(0.5 - signed_distance, 0.0, 1.0);
return static_cast<std::uint8_t>(std::lround(coverage * 255.0));
}
std::uint8_t popup_shadow_alpha(
double signed_distance,
const Win32TrayPopupMetrics& metrics) {
if (metrics.shadow_blur <= 0 ||
signed_distance >= static_cast<double>(metrics.shadow_blur)) {
return 0;
}
const double normalized = 1.0 -
std::max(0.0, signed_distance) /
static_cast<double>(metrics.shadow_blur);
return static_cast<std::uint8_t>(std::lround(
static_cast<double>(metrics.shadow_max_alpha) *
normalized * normalized));
}
void draw_tray_popup_contents(
Win32TrayPopupWindow& state,
HDC draw,
const RECT& surface) {
HFONT font = state.font
? state.font
: static_cast<HFONT>(::GetStockObject(DEFAULT_GUI_FONT));
HGDIOBJ old_font = font ? ::SelectObject(draw, font) : nullptr;
const int old_bk_mode = ::SetBkMode(draw, TRANSPARENT);
for (std::size_t i = 0; i < state.rows.size(); ++i) {
const auto& row = state.rows[i];
RECT row_rect{
surface.left,
surface.top + state.metrics.outer_padding +
row.top - state.scroll_offset,
surface.right,
surface.top + state.metrics.outer_padding +
row.top + row.height - state.scroll_offset,
};
if (row_rect.bottom <= surface.top ||
row_rect.top >= surface.bottom) {
continue;
}
const auto kind = row.model.entry.kind;
if (kind == TrayMenuEntryKind::Separator) {
const int y = (row_rect.top + row_rect.bottom) / 2;
HPEN pen = ::CreatePen(PS_SOLID, 1, RGB(225, 230, 238));
HGDIOBJ old_pen = pen ? ::SelectObject(draw, pen) : nullptr;
::MoveToEx(draw, surface.left, y, nullptr);
::LineTo(draw, surface.right, y);
if (old_pen) ::SelectObject(draw, old_pen);
if (pen) ::DeleteObject(pen);
continue;
}
const bool selectable = tray_popup_entry_is_selectable(kind);
if (selectable && state.hovered_index == static_cast<int>(i)) {
HBRUSH hover = ::CreateSolidBrush(RGB(243, 243, 243));
::FillRect(draw, &row_rect, hover);
::DeleteObject(hover);
}
RECT text_rect = row_rect;
text_rect.left += state.metrics.horizontal_padding;
text_rect.right -= state.metrics.horizontal_padding;
const std::wstring label = utf8_to_wide(row.model.entry.label);
if (tray_popup_entry_is_header(kind)) {
::SetTextColor(draw, RGB(108, 101, 97));
::DrawTextW(draw,
label.c_str(),
static_cast<int>(label.size()),
&text_rect,
DT_SINGLELINE | DT_VCENTER | DT_LEFT | DT_END_ELLIPSIS | DT_NOPREFIX);
continue;
}
if (tray_popup_entry_is_session(kind)) {
const std::wstring title = utf8_to_wide(
row.model.entry.title.empty() ? row.model.entry.label : row.model.entry.title);
const std::wstring subtitle = utf8_to_wide(row.model.entry.subtitle);
RECT title_rect = text_rect;
if (!subtitle.empty() && state.metrics.right_column_width > 0) {
RECT subtitle_rect = text_rect;
subtitle_rect.left = std::max(
subtitle_rect.left,
subtitle_rect.right - state.metrics.right_column_width);
::SetTextColor(draw, RGB(82, 73, 68));
::DrawTextW(draw,
subtitle.c_str(),
static_cast<int>(subtitle.size()),
&subtitle_rect,
DT_SINGLELINE | DT_VCENTER | DT_RIGHT | DT_END_ELLIPSIS | DT_NOPREFIX);
title_rect.right = std::max(
title_rect.left,
subtitle_rect.left - state.metrics.text_gap);
}
::SetTextColor(draw, RGB(28, 28, 28));
::DrawTextW(draw,
title.c_str(),
static_cast<int>(title.size()),
&title_rect,
DT_SINGLELINE | DT_VCENTER | DT_LEFT | DT_END_ELLIPSIS | DT_NOPREFIX);
continue;
}
::SetTextColor(draw, RGB(28, 28, 28));
if (kind == TrayMenuEntryKind::MoreSubmenuRoot) {
text_rect.right -= scale_px(16, state.metrics.layout_dpi);
}
::DrawTextW(draw,
label.c_str(),
static_cast<int>(label.size()),
&text_rect,
DT_SINGLELINE | DT_VCENTER | DT_LEFT | DT_END_ELLIPSIS | DT_NOPREFIX);
if (kind == TrayMenuEntryKind::MoreSubmenuRoot) {
draw_popup_chevron(draw, row_rect, state.metrics);
}
}
const int max_scroll = max_popup_scroll(state);
if (max_scroll > 0) {
const int track_inset = scale_px(8, state.metrics.layout_dpi);
const int track_top = surface.top + track_inset;
const int track_height = std::max(
1, state.viewport_height - track_inset * 2);
const int full_height = state.content_height + state.metrics.outer_padding * 2;
const int thumb_height = std::clamp(
state.viewport_height * track_height / std::max(1, full_height),
scale_px(18, state.metrics.layout_dpi),
track_height);
const int thumb_top = track_top +
state.scroll_offset * (track_height - thumb_height) / max_scroll;
RECT thumb{
surface.right - scale_px(4, state.metrics.layout_dpi),
thumb_top,
surface.right - scale_px(2, state.metrics.layout_dpi),
thumb_top + thumb_height,
};
fill_rounded_rect(
draw,
thumb,
scale_px(2, state.metrics.layout_dpi),
RGB(190, 190, 190));
}
::SetBkMode(draw, old_bk_mode);
if (old_font) ::SelectObject(draw, old_font);
}
bool paint_tray_popup(Win32TrayPopupWindow& state) {
if (!state.hwnd) return false;
const auto chrome = popup_chrome_geometry(state, 0, 0);
const int width = chrome.window_width;
const int height = chrome.window_height;
const std::size_t pixel_count =
static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
Win32LayeredDib dib;
if (!dib.create(width, height)) return false;
std::vector<std::uint8_t> surface_alpha(pixel_count);
std::vector<std::uint8_t> shadow_alpha(pixel_count);
const RECT surface{
chrome.surface_left,
chrome.surface_top,
chrome.surface_left + chrome.surface_width,
chrome.surface_top + chrome.surface_height,
};
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
const std::size_t index =
static_cast<std::size_t>(y) * static_cast<std::size_t>(width) +
static_cast<std::size_t>(x);
const double surface_x =
static_cast<double>(x - surface.left) + 0.5;
const double surface_y =
static_cast<double>(y - surface.top) + 0.5;
const double surface_distance = tray_popup_rounded_rect_distance(
surface_x,
surface_y,
chrome.surface_width,
chrome.surface_height,
state.metrics.corner_radius);
surface_alpha[index] =
popup_surface_coverage(surface_distance);
const double shadow_y = surface_y -
static_cast<double>(state.metrics.shadow_offset_y);
const double shadow_distance = tray_popup_rounded_rect_distance(
surface_x,
shadow_y,
chrome.surface_width,
chrome.surface_height,
state.metrics.corner_radius);
shadow_alpha[index] =
popup_shadow_alpha(shadow_distance, state.metrics);
dib.pixels[index] =
surface_alpha[index] > 0 ? 0x00FFFFFFu : 0u;
}
}