-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackplate.cpp
More file actions
3025 lines (2685 loc) · 99.9 KB
/
Copy pathBackplate.cpp
File metadata and controls
3025 lines (2685 loc) · 99.9 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
#include "Backplate.h"
#include "Core.h"
#include "Util.h"
#include "FD2DLog.h"
#include <cmath>
#include <cstring>
#include <dxgi1_3.h>
#include <string>
#include <algorithm>
#include <shellapi.h>
#include <windowsx.h> // For GET_X_LPARAM, GET_Y_LPARAM, MAKELPARAM
#include <ole2.h>
#include <oleidl.h>
#include <vector>
namespace FD2D
{
static bool IsDeviceRemovedHr(HRESULT hr)
{
return hr == DXGI_ERROR_DEVICE_REMOVED
|| hr == DXGI_ERROR_DEVICE_RESET
|| hr == DXGI_ERROR_DRIVER_INTERNAL_ERROR;
}
static InputEventType ToInputEventType(UINT message)
{
static std::unordered_map <UINT, InputEventType> mapMsg2EventType = {
{ WM_MOUSEMOVE, InputEventType::MouseMove },
{ WM_LBUTTONDOWN, InputEventType::MouseDown },
{ WM_RBUTTONDOWN, InputEventType::MouseDown },
{ WM_MBUTTONDOWN, InputEventType::MouseDown },
{ WM_XBUTTONDOWN, InputEventType::MouseDown },
{ WM_LBUTTONUP, InputEventType::MouseUp },
{ WM_RBUTTONUP, InputEventType::MouseUp },
{ WM_MBUTTONUP, InputEventType::MouseUp },
{ WM_XBUTTONUP, InputEventType::MouseUp },
{ WM_LBUTTONDBLCLK, InputEventType::MouseDoubleClick },
{ WM_RBUTTONDBLCLK, InputEventType::MouseDoubleClick },
{ WM_MBUTTONDBLCLK, InputEventType::MouseDoubleClick },
{ WM_XBUTTONDBLCLK, InputEventType::MouseDoubleClick },
{ WM_MOUSEWHEEL, InputEventType::MouseWheel },
{ WM_MOUSEHWHEEL, InputEventType::MouseHWheel },
{ WM_MOUSELEAVE, InputEventType::MouseLeave },
{ WM_CAPTURECHANGED, InputEventType::CaptureChanged },
{ WM_SETCURSOR, InputEventType::SetCursor },
{ WM_KEYDOWN, InputEventType::KeyDown },
{ WM_SYSKEYDOWN, InputEventType::KeyDown },
{ WM_KEYUP, InputEventType::KeyUp },
{ WM_SYSKEYUP, InputEventType::KeyUp },
{ WM_CHAR, InputEventType::Char },
{ WM_SYSCHAR, InputEventType::SystemChar },
{ WM_DEADCHAR, InputEventType::DeadChar },
{ WM_SYSDEADCHAR, InputEventType::SystemDeadChar },
{ WM_UNICHAR, InputEventType::UniChar }
};
auto it = mapMsg2EventType.find(message);
if (it != mapMsg2EventType.end())
return it->second;
else
return InputEventType::None;
}
static MouseButton ToMouseButton(UINT message, WPARAM wParam)
{
static std::unordered_map<UINT, MouseButton> mapMsg2MouseButton = {
{ WM_LBUTTONDOWN, MouseButton::Left },
{ WM_RBUTTONDOWN, MouseButton::Right },
{ WM_MBUTTONDOWN, MouseButton::Middle },
{ WM_LBUTTONUP, MouseButton::Left },
{ WM_RBUTTONUP, MouseButton::Right },
{ WM_MBUTTONUP, MouseButton::Middle },
{ WM_LBUTTONDBLCLK, MouseButton::Left },
{ WM_RBUTTONDBLCLK, MouseButton::Right },
{ WM_MBUTTONDBLCLK, MouseButton::Middle },
};
auto it = mapMsg2MouseButton.find(message);
if (it != mapMsg2MouseButton.end())
return it->second;
else
return MouseButton::None;
}
static bool IsRoutedMouseMessage(UINT message)
{
switch (message)
{
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_RBUTTONDBLCLK:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_MBUTTONDBLCLK:
case WM_MOUSEWHEEL:
case WM_MOUSEHWHEEL:
case WM_CAPTURECHANGED:
return true;
default:
return false;
}
}
static D2D1_BITMAP_PROPERTIES1 MakeSwapChainBitmapProps()
{
const float dpi = 96.0f;
D2D1_BITMAP_PROPERTIES1 bp {};
bp.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM;
// Swapchain alpha is DXGI_ALPHA_MODE_IGNORE, so the D2D target must match.
bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE;
bp.dpiX = dpi;
bp.dpiY = dpi;
// Recommended for swapchain-backed targets (can be set as target, but not used as a source).
bp.bitmapOptions = static_cast<D2D1_BITMAP_OPTIONS>(
D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW);
return bp;
}
Backplate::Backplate()
{
m_asyncRedrawEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
m_asyncRedrawControl = std::make_shared<AsyncRedrawToken::ControlBlock>();
m_asyncRedrawControl->backplate = this;
}
Backplate::Backplate(const std::wstring& name)
: m_name(name)
{
m_asyncRedrawEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
m_asyncRedrawControl = std::make_shared<AsyncRedrawToken::ControlBlock>();
m_asyncRedrawControl->backplate = this;
}
Backplate::~Backplate()
{
// Drop the HWND first so any Invalidate/Render triggered by the
// Shutdown invalidation cascade cannot touch a destroyed window.
m_window = nullptr;
DetachAsyncRedrawControl();
NotifyGraphicsInvalidated(GraphicsInvalidationReason::Shutdown);
UnregisterDropTarget();
if (m_asyncRedrawEvent)
{
CloseHandle(m_asyncRedrawEvent);
m_asyncRedrawEvent = nullptr;
}
}
AsyncRedrawToken::AsyncRedrawToken(std::weak_ptr<ControlBlock> control)
: m_control(std::move(control))
{
}
void AsyncRedrawToken::RequestAsyncRedraw() const
{
auto control = m_control.lock();
if (!control)
{
return;
}
std::lock_guard<std::mutex> lock(control->mutex);
if (control->backplate)
{
control->backplate->RequestAsyncRedraw();
}
}
void Backplate::DetachAsyncRedrawControl()
{
if (!m_asyncRedrawControl)
{
return;
}
std::lock_guard<std::mutex> lock(m_asyncRedrawControl->mutex);
m_asyncRedrawControl->backplate = nullptr;
}
std::shared_ptr<AsyncRedrawToken> Backplate::GetAsyncRedrawToken() const
{
if (!m_asyncRedrawControl)
{
return nullptr;
}
return std::shared_ptr<AsyncRedrawToken>(new AsyncRedrawToken(m_asyncRedrawControl));
}
void Backplate::InvalidateGraphics(
GraphicsInvalidationReason reason,
bool bumpDevice,
bool bumpTarget,
bool bumpRenderer)
{
if (bumpDevice)
{
++m_graphicsGeneration.device;
}
if (bumpTarget)
{
++m_graphicsGeneration.target;
}
if (bumpRenderer)
{
++m_graphicsGeneration.renderer;
}
NotifyGraphicsInvalidated(reason);
}
void Backplate::NotifyGraphicsInvalidated(GraphicsInvalidationReason reason)
{
const GraphicsGeneration generation = m_graphicsGeneration;
for (const auto& child : m_childrenOrdered)
{
if (child)
{
child->OnGraphicsInvalidated(reason, generation);
}
}
}
void Backplate::ScheduleNextFrame()
{
if (m_window != nullptr && IsWindow(m_window))
{
InvalidateRect(m_window, nullptr, FALSE);
}
}
void Backplate::LogDeviceRemovedReason(HRESULT triggerHr, const char* where) const
{
if (m_d3dDevice)
{
const HRESULT reasonHr = m_d3dDevice->GetDeviceRemovedReason();
FD2D_LOG_INFO(
"[Graphics] device lost at {}: hr=0x{:08X} GetDeviceRemovedReason=0x{:08X}",
where ? where : "?",
static_cast<unsigned>(triggerHr),
static_cast<unsigned>(reasonHr));
}
else
{
FD2D_LOG_INFO(
"[Graphics] device lost at {}: hr=0x{:08X} (no D3D device)",
where ? where : "?",
static_cast<unsigned>(triggerHr));
}
}
bool Backplate::HandleDeviceLostHr(HRESULT hr, const char* where)
{
if (!IsDeviceRemovedHr(hr))
{
return false;
}
LogDeviceRemovedReason(hr, where);
DiscardDeviceResources();
InvalidateGraphics(GraphicsInvalidationReason::DeviceLost, true, true, false);
ScheduleNextFrame();
return true;
}
void Backplate::SetOnBeforeDestroy(std::function<void(HWND)> handler)
{
m_onBeforeDestroy = std::move(handler);
}
void Backplate::SetOnWindowPlacementChanged(std::function<void(HWND)> handler)
{
m_onWindowPlacementChanged = std::move(handler);
}
void Backplate::InvokeBeforeDestroyOnce()
{
if (m_beforeDestroyInvoked)
{
return;
}
m_beforeDestroyInvoked = true;
if (m_onBeforeDestroy && m_window != nullptr)
{
m_onBeforeDestroy(m_window);
}
}
void Backplate::SchedulePlacementAutosave()
{
if (m_window == nullptr || !m_onWindowPlacementChanged)
{
return;
}
if (m_placeAutosaveTimerId == 0)
{
m_placeAutosaveTimerId = 0xFD22;
}
// Debounce (reset timer each time).
(void)SetTimer(m_window, m_placeAutosaveTimerId, 200, nullptr);
}
void Backplate::FlushPlacementAutosave()
{
if (m_window == nullptr || !m_onWindowPlacementChanged)
{
return;
}
if (m_placeAutosaveTimerId != 0)
{
KillTimer(m_window, m_placeAutosaveTimerId);
}
m_onWindowPlacementChanged(m_window);
}
namespace
{
static bool DataObjectHasHDrop(IDataObject* dataObject)
{
if (dataObject == nullptr)
{
return false;
}
FORMATETC fmt {};
fmt.cfFormat = CF_HDROP;
fmt.ptd = nullptr;
fmt.dwAspect = DVASPECT_CONTENT;
fmt.lindex = -1;
fmt.tymed = TYMED_HGLOBAL;
return dataObject->QueryGetData(&fmt) == S_OK;
}
// Extracts file paths from a CF_HDROP data object.
// When firstOnly is true, only the first path is queried.
static std::vector<std::wstring> ExtractHDropPaths(IDataObject* dataObject, bool firstOnly)
{
std::vector<std::wstring> out;
if (dataObject == nullptr)
{
return out;
}
FORMATETC fmt {};
fmt.cfFormat = CF_HDROP;
fmt.ptd = nullptr;
fmt.dwAspect = DVASPECT_CONTENT;
fmt.lindex = -1;
fmt.tymed = TYMED_HGLOBAL;
STGMEDIUM stg {};
if (FAILED(dataObject->GetData(&fmt, &stg)))
{
return out;
}
const HDROP hDrop = reinterpret_cast<HDROP>(stg.hGlobal);
if (hDrop != nullptr)
{
wchar_t buf[MAX_PATH] {};
const UINT fileCount = firstOnly
? 1U
: DragQueryFileW(hDrop, 0xFFFFFFFF, nullptr, 0);
out.reserve(fileCount);
for (UINT i = 0; i < fileCount; ++i)
{
const UINT cch = DragQueryFileW(hDrop, i, buf, static_cast<UINT>(std::size(buf)));
if (cch == 0)
{
continue;
}
out.emplace_back(buf);
}
}
ReleaseStgMedium(&stg);
return out;
}
static std::wstring GetFirstPathFromDataObject(IDataObject* dataObject)
{
const auto paths = ExtractHDropPaths(dataObject, true /*firstOnly*/);
return paths.empty() ? std::wstring {} : paths.front();
}
static std::vector<std::wstring> GetAllPathsFromDataObject(IDataObject* dataObject)
{
return ExtractHDropPaths(dataObject, false /*firstOnly*/);
}
}
class Backplate::DropTarget final : public IDropTarget
{
public:
explicit DropTarget(Backplate* owner)
: m_owner(owner)
{
}
HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObject) override
{
if (ppvObject == nullptr)
{
return E_POINTER;
}
if (riid == IID_IUnknown || riid == IID_IDropTarget)
{
*ppvObject = static_cast<IDropTarget*>(this);
AddRef();
return S_OK;
}
*ppvObject = nullptr;
return E_NOINTERFACE;
}
ULONG __stdcall AddRef() override
{
return static_cast<ULONG>(InterlockedIncrement(&m_refCount));
}
ULONG __stdcall Release() override
{
const ULONG r = static_cast<ULONG>(InterlockedDecrement(&m_refCount));
if (r == 0)
{
delete this;
}
return r;
}
HRESULT __stdcall DragEnter(IDataObject* pDataObj, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) override
{
UNREFERENCED_PARAMETER(grfKeyState);
if (pdwEffect == nullptr)
{
return E_POINTER;
}
if (!DataObjectHasHDrop(pDataObj) || m_owner == nullptr)
{
*pdwEffect = DROPEFFECT_NONE;
return S_OK;
}
m_owner->m_dragPath = GetFirstPathFromDataObject(pDataObj);
return DragOver(grfKeyState, pt, pdwEffect);
}
HRESULT __stdcall DragOver(DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) override
{
UNREFERENCED_PARAMETER(grfKeyState);
if (pdwEffect == nullptr)
{
return E_POINTER;
}
if (m_owner == nullptr || m_owner->m_window == nullptr || m_owner->m_dragPath.empty())
{
*pdwEffect = DROPEFFECT_NONE;
return S_OK;
}
POINT ptScreen { pt.x, pt.y };
POINT ptClient = ptScreen;
ScreenToClient(m_owner->m_window, &ptClient);
const bool handled = m_owner->HandleFileDragOver(m_owner->m_dragPath, ptClient);
*pdwEffect = handled ? DROPEFFECT_COPY : DROPEFFECT_NONE;
return S_OK;
}
HRESULT __stdcall DragLeave() override
{
if (m_owner != nullptr)
{
m_owner->m_dragPath.clear();
m_owner->HandleFileDragLeave();
}
return S_OK;
}
HRESULT __stdcall Drop(IDataObject* pDataObj, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) override
{
UNREFERENCED_PARAMETER(grfKeyState);
if (pdwEffect == nullptr)
{
return E_POINTER;
}
if (!DataObjectHasHDrop(pDataObj) || m_owner == nullptr || m_owner->m_window == nullptr)
{
*pdwEffect = DROPEFFECT_NONE;
return S_OK;
}
const auto paths = GetAllPathsFromDataObject(pDataObj);
POINT ptScreen { pt.x, pt.y };
POINT ptClient = ptScreen;
ScreenToClient(m_owner->m_window, &ptClient);
// Clear overlays first, then route the drop as a normal file drop.
m_owner->HandleFileDragLeave();
m_owner->m_dragPath.clear();
const bool handled = m_owner->HandleFileDropPaths(paths, ptClient);
*pdwEffect = handled ? DROPEFFECT_COPY : DROPEFFECT_NONE;
return S_OK;
}
private:
Backplate* m_owner { nullptr };
volatile LONG m_refCount { 1 };
};
bool Backplate::EnsureDropTargetRegistered()
{
if (m_dropTargetRegistered)
{
return true;
}
if (m_window == nullptr)
{
return false;
}
// Register OLE drop target for live drag-over updates (overlays + per-pane routing).
m_dropTarget.Attach(new DropTarget(this));
const HRESULT hr = RegisterDragDrop(m_window, m_dropTarget.Get());
if (FAILED(hr))
{
m_dropTarget.Reset();
m_dropTargetRegistered = false;
return false;
}
m_dropTargetRegistered = true;
return true;
}
void Backplate::UnregisterDropTarget()
{
if (m_dropTargetRegistered && m_window != nullptr)
{
(void)RevokeDragDrop(m_window);
}
m_dropTargetRegistered = false;
m_dropTarget.Reset();
m_dragPath.clear();
}
bool Backplate::HandleFileDragOver(const std::wstring& path, const POINT& ptClient)
{
// OLE calls DragOver on every mouse-move during a drag (many times/sec).
// Clearing stale visuals and setting the new one each call Invalidate(),
// which normally renders+presents immediately -- so without batching, a
// single DragOver could present one frame with the overlay cleared and
// another with it set, visible as a flicker on every drag move. Defer all
// Invalidate() calls triggered below into a single Render() at the end.
BeginDeferredRender();
// Clear any prior visuals from children that are no longer the drag target
// (the loop below only reaches the first child that claims the point).
for (const auto& child : m_childrenOrdered)
{
if (child)
{
child->OnFileDragLeave();
}
}
FileDragVisual visual = FileDragVisual::None;
bool handled = false;
for (auto it = m_childrenOrdered.rbegin(); it != m_childrenOrdered.rend(); ++it)
{
if (*it && (*it)->OnFileDrag(path, ptClient, visual))
{
handled = true;
break;
}
}
EndDeferredRender();
if (m_window != nullptr)
{
Render();
}
return handled;
}
void Backplate::HandleFileDragLeave()
{
BeginDeferredRender();
for (const auto& child : m_childrenOrdered)
{
if (child)
{
child->OnFileDragLeave();
}
}
EndDeferredRender();
if (m_window != nullptr)
{
Render();
}
}
bool Backplate::HandleFileDropPaths(const std::vector<std::wstring>& paths, const POINT& ptClient)
{
if (paths.empty())
{
return false;
}
for (auto it = m_childrenOrdered.rbegin(); it != m_childrenOrdered.rend(); ++it)
{
if (*it && (*it)->OnFileDropPaths(paths, ptClient))
{
return true;
}
}
return false;
}
void Backplate::RequestAsyncRedraw()
{
if (!m_asyncRedrawEvent || !m_window || !IsWindow(m_window))
{
return;
}
// Coalesce multiple worker completions into a single wakeup.
const bool wasPending = m_asyncRedrawPending.exchange(true);
if (!wasPending)
{
SetEvent(m_asyncRedrawEvent);
}
}
void Backplate::ProcessAsyncRedraw()
{
if (!m_window || !IsWindow(m_window) || !m_asyncRedrawEvent)
{
return;
}
// Drain the pending flag and reset the event for future signals.
m_asyncRedrawPending.store(false);
ResetEvent(m_asyncRedrawEvent);
// During interactive resizing, avoid synchronous repaint pressure.
if (m_inSizeMove)
{
InvalidateRect(m_window, nullptr, FALSE);
}
else
{
// Trigger a prompt repaint (once per coalesced burst).
FD2D_TIMER_START(t_redraw);
RedrawWindow(m_window, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_NOERASE);
const auto redrawMs = FD2D_ELAPSED_MS(t_redraw);
if (redrawMs > 50)
{
FD2D_LOG_INFO("[UI stall] ProcessAsyncRedraw: RedrawWindow(UPDATENOW) took {}ms", redrawMs);
}
}
}
void Backplate::RequestAnimationFrame()
{
m_lastAnimationRequestMs.store(Util::NowMs());
}
bool Backplate::HasActiveAnimation(unsigned long long nowMs) const
{
const unsigned long long last = m_lastAnimationRequestMs.load();
// Consider animation active if someone requested frames recently.
// Use a small window to detect stale animation requests (100ms is ~6 frames at 60fps).
// This prevents stuck animation loops when no component actually needs animation.
return (last != 0) && (nowMs - last <= 100ULL);
}
void Backplate::ProcessAnimationTick(unsigned long long nowMs)
{
if (!m_window || !IsWindow(m_window))
{
return;
}
// Advance tooltip dwell / toast expiry first: it re-arms the animation
// while a tooltip is pending or a toast is showing, so these keep
// ticking even when nothing else animates.
AdvanceHoverToast(nowMs);
if (!HasActiveAnimation(nowMs))
{
return;
}
// Adaptive animation cadence:
// - Default: ~60fps for smooth interactions.
// - While async redraw bursts are pending or during live resize:
// back off to ~30fps to reduce UI-thread render pressure.
const bool asyncPending = m_asyncRedrawPending.load();
const unsigned long long minTickIntervalMs =
(m_inSizeMove || asyncPending) ? 33ULL : 16ULL;
// Diagnostic: log only when the cadence actually changes (not every tick), so we
// get crisp "throttle engaged/lifted" markers to correlate with the [FPS] summary.
if (minTickIntervalMs != m_lastLoggedTickIntervalMs)
{
FD2D_LOG_INFO(
"[FPS] animation tick cadence -> {}ms ({}fps target) inSizeMove={} asyncRedrawPending={}",
minTickIntervalMs, minTickIntervalMs > 0 ? (1000ULL / minTickIntervalMs) : 0ULL,
m_inSizeMove, asyncPending);
m_lastLoggedTickIntervalMs = minTickIntervalMs;
}
const unsigned long long lastTick = m_lastAnimationTickMs.load();
if (lastTick != 0 && (nowMs - lastTick) < minTickIntervalMs)
{
return;
}
m_lastAnimationTickMs.store(nowMs);
// Direct rendering: bypass message loop for smoother 60fps animation.
// Log frames that take > 100ms (rate-limited to one log per 100ms to avoid flooding).
FD2D_TIMER_START(t_frame);
NoteRenderTrigger(RenderTrigger::Tick);
Render();
const auto frameMs = FD2D_ELAPSED_MS(t_frame);
if (frameMs > 100)
{
static std::chrono::steady_clock::time_point s_lastSlowFrameLog {};
const auto nowTp = std::chrono::steady_clock::now();
if (nowTp - s_lastSlowFrameLog >= std::chrono::milliseconds(100))
{
FD2D_LOG_INFO("[UI stall] ProcessAnimationTick: Render took {}ms", frameMs);
s_lastSlowFrameLog = nowTp;
}
}
}
Wnd* Backplate::FindTargetWnd(const POINT& ptClient)
{
UNREFERENCED_PARAMETER(ptClient);
return nullptr;
}
namespace
{
constexpr unsigned long long kTooltipDwellMs = 500ULL;
constexpr unsigned long long kToastDurationMs = 1800ULL;
}
Wnd* Backplate::HitTestTopLevel(const POINT& pt)
{
for (auto it = m_childrenOrdered.rbegin(); it != m_childrenOrdered.rend(); ++it)
{
if (*it)
{
if (Wnd* hit = (*it)->HitTestDeepest(pt))
{
return hit;
}
}
}
return nullptr;
}
void Backplate::UpdateHoverTarget(const POINT& ptClient)
{
m_hoverPt = ptClient;
Wnd* hit = HitTestTopLevel(ptClient);
std::wstring tip = hit ? hit->TooltipText() : std::wstring();
// Same control + same tip: keep the running dwell (and any shown
// tooltip) so small jitters don't restart it.
if (hit == m_hoverWnd && tip == m_hoverTip)
{
return;
}
const bool wasShown = m_tipShown;
m_hoverWnd = hit;
m_hoverTip = std::move(tip);
m_hoverSinceMs = Util::NowMs();
m_tipShown = false;
if (!m_hoverTip.empty())
{
RequestAnimationFrame(); // drive the dwell timer via ProcessAnimationTick
}
else if (wasShown && m_window != nullptr)
{
InvalidateRect(m_window, nullptr, FALSE); // erase the tooltip that was showing
}
}
void Backplate::ClearHoverTooltip()
{
m_hoverWnd = nullptr;
m_hoverTip.clear();
m_hoverSinceMs = 0;
if (m_tipShown)
{
m_tipShown = false;
if (m_window != nullptr)
{
InvalidateRect(m_window, nullptr, FALSE);
}
}
}
void Backplate::ShowToast(const std::wstring& text)
{
m_toastText = text;
m_toastExpireMs = Util::NowMs() + kToastDurationMs;
RequestAnimationFrame();
if (m_window != nullptr)
{
InvalidateRect(m_window, nullptr, FALSE);
}
}
bool Backplate::CopyTextToClipboard(const std::wstring& text)
{
if (m_window == nullptr || !OpenClipboard(m_window))
{
return false;
}
bool ok = false;
if (EmptyClipboard())
{
const std::size_t bytes = (text.size() + 1) * sizeof(wchar_t);
if (HGLOBAL h = GlobalAlloc(GMEM_MOVEABLE, bytes))
{
if (void* dst = GlobalLock(h))
{
std::memcpy(dst, text.c_str(), bytes);
GlobalUnlock(h);
ok = (SetClipboardData(CF_UNICODETEXT, h) != nullptr);
}
if (!ok)
{
GlobalFree(h); // ownership only transfers to the clipboard on success
}
}
}
CloseClipboard();
return ok;
}
void Backplate::AdvanceHoverToast(unsigned long long nowMs)
{
bool needAnim = false;
// Tooltip dwell: once elapsed, flip m_tipShown so the next render (this
// tick's Render, since animation is active) paints it. Keep re-arming
// the animation until then.
if (m_hoverWnd != nullptr && !m_hoverTip.empty() && !m_tipShown)
{
if (nowMs - m_hoverSinceMs >= kTooltipDwellMs)
{
m_tipShown = true;
m_tipAnchor = m_hoverPt;
}
else
{
needAnim = true;
}
}
// Toast expiry: clear it (one more render this tick erases it).
if (!m_toastText.empty())
{
if (nowMs >= m_toastExpireMs)
{
m_toastText.clear();
}
else
{
needAnim = true;
}
}
if (needAnim)
{
RequestAnimationFrame();
}
}
bool Backplate::HasActiveOverlay(OverlayLayer layer) const
{
for (const auto& child : m_childrenOrdered)
{
if (child && child->HasActiveOverlayInTree(layer))
{
return true;
}
}
return false;
}
bool Backplate::RouteOverlayInput(const InputEvent& event, OverlayLayer layer)
{
for (auto it = m_childrenOrdered.rbegin(); it != m_childrenOrdered.rend(); ++it)
{
if (*it && (*it)->RouteOverlayInput(event, layer))
{
return true;
}
}
return false;
}
void Backplate::RenderOverlayLayer(ID2D1RenderTarget* target, OverlayLayer layer)
{
for (const auto& child : m_childrenOrdered)
{
if (child)
{
child->RenderOverlayTree(target, layer);
}
}
}
void Backplate::DrawHoverAndToast(
ID2D1RenderTarget* target,
bool drawHover,
bool drawToast)
{
if (target == nullptr)
{
return;
}
const bool hasHover =
drawHover &&
m_tipShown &&
!m_hoverTip.empty();
const bool hasToast =
drawToast &&
!m_toastText.empty();
if (!hasHover && !hasToast)
{
return;
}
IDWriteFactory* dwrite = Core::DWriteFactory();
if (dwrite == nullptr)
{
return;
}
if (!m_tipFormat)
{
(void)dwrite->CreateTextFormat(L"Segoe UI", nullptr, DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 13.0f, L"", &m_tipFormat);
if (!m_tipFormat)
{
return;
}
(void)m_tipFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
}
const float clientW = static_cast<float>(m_size.width);
const float clientH = static_cast<float>(m_size.height);
constexpr float padX = 9.0f;
constexpr float padY = 5.0f;
auto drawBox = [&](const std::wstring& text, float boxLeft, float boxTop,
bool clampBelowRightOfCursor, const D2D1_COLOR_F& bg,
const D2D1_COLOR_F& border, const D2D1_COLOR_F& fg)
{
Microsoft::WRL::ComPtr<IDWriteTextLayout> layout;
if (FAILED(dwrite->CreateTextLayout(text.c_str(), static_cast<UINT32>(text.size()),
m_tipFormat.Get(), 100000.0f, 100000.0f, &layout)) || !layout)
{
return;
}
DWRITE_TEXT_METRICS m {};
if (FAILED(layout->GetMetrics(&m)))