File size: 51,186 Bytes
2edf277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
// FCS Glass - src/app/main.cpp
//
// MILESTONE M0: a real window, a real device, and the first presented frame.
// The smallest program that can honestly be called "running": one top-level
// window, one DComp swap chain, one Present. Everything visual (glass, blur,
// text, widgets) is M2+ and arrives behind the same frame loop.
//
// RESEARCH FINDINGS - each read from the SDK or measured before it was written.
//
//  1. Visual tree order is fixed and not interchangeable (learn.microsoft.com,
//     "How to build a simple visual tree"):
//        DCompositionCreateDevice(IDXGIDevice*)      <- from the DXGI device, not QI
//        IDCompositionDevice::CreateTargetForHwnd
//        IDXGIFactory2::CreateSwapChainForComposition
//        IDCompositionDevice::CreateVisual
//        IDCompositionVisual::SetContent(swap chain)
//        IDCompositionTarget::SetRoot(visual)
//        IDCompositionDevice::Commit
//     SetContent takes an IUnknown*, so the swap chain IS the content - there is
//     no intermediate surface to allocate. Getting this order wrong yields a
//     window that stays black while every HRESULT reports S_OK, which is why
//     each step is checked separately (D-22, D-23, D-25).
//
//  2. The DPI manifest is a two-element ladder, not one element. On a host older
//     than Windows 10 1607, <dpiAwareness> is IGNORED, so <dpiAware>true/pm</dpiAware>
//     is the fallback and the process does not silently become DPI-unaware on the
//     2012 R2 floor. See src/app/app.manifest.
//
//  3. A composition swap chain MUST use DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL. Measured:
//     DISCARD returns DXGI_ERROR_INVALID_CALL (0x887A0001), as does BufferCount 0.
//     (D-25)
//
//  4. The first frame is presented BEFORE the loop. Presenting inside the loop
//     leaves a visible empty window for one refresh, and makes a later DwmFlush()
//     measure the interval since the PREVIOUS present rather than this frame -
//     which is what made the M0a probe report the 16.66 ms vsync period as if it
//     were a frame cost (X29; J6 splits pacing from GPU cost for this reason).
//
//  5. Three API details the first draft got wrong, all caught by the compiler
//     rather than by reading:
//       a. ComPtr (platform.h) has explicit operator bool and operator! but NO
//          operator==, so `ptr == nullptr` is error C2678. Use `!ptr`.
//       b. ComPtr's out-parameter accessor is GetAddressOf(), not GetAddrOf().
//       c. IDCompositionDevice::CreateTargetForHwnd takes THREE arguments
//          (dcomp.h L266): (HWND, BOOL topmost, IDCompositionTarget**). The
//          `topmost` flag is not optional - IID_PPV_ARGS supplies only the third.
//       d. OsProfile is Classic/Fluent (W4), not a Windows-version name, and
//          build is a DWORD, so %lu needs an explicit unsigned long cast.
//
// Not in this milestone, deliberately: no shader is compiled and none is drawn.
// M0 presents the swap chain and nothing more. J11's embedded bytecode path needs
// shaders/glass.hlsl compiled by fxc, which is M2; adding a placeholder draw here
// would make M2 look further along than it is.

#include <windowsx.h>   // GET_X_LPARAM / GET_Y_LPARAM for WM_DPICHANGED (E1)

#include "platform/platform.h"
#include "platform/os_info.h"
#include "platform/dpi.h"
#include "platform/window.h"
#include "platform/backdrop.h"
#include "platform/input_map.h"
#include "device/dx.h"
#include "core/input.h"

#include <cstdio>

namespace fcs {
namespace {

// BUG-26. The system's modal size/move loop OWNS THIS THREAD between
// WM_ENTERSIZEMOVE and WM_EXITSIZEMOVE, so RunApp's frame loop cannot iterate
// while the user drags an edge. The client grows immediately (WM_NCCALCSIZE is
// now correct), but the swap chain still holds the PREVIOUS, smaller buffer -
// so the strip the window has just gained has no composition content at all and
// composites black. It fills in only once the drag ends and the loop finally
// runs, which is exactly the "black while I drag, then the teal catches up"
// behaviour that was reported.
//
// The demo in this workspace hit the same wall and solved it the same way:
// repaint synchronously from the message that reports the resize, so the
// presented frame and the window rectangle stay in lockstep. Outside a drag the
// frame loop still owns rendering; nothing here changes the idle model.
//
// This is file-scope because HostWndProc and RunApp are two different functions
// and the WndProc has only an HWND to work from. It is the same shape as the
// demo's g_swapchain/g_in_size_move, deliberately.
struct FrameCtx {
  DxDevice* dx = nullptr;
  Window* win = nullptr;
  QualityTier tier = QualityTier::Full;
  // C3/C4/E11. The one InputFrame for the process, fed by HostWndProc and frozen
  // once per frame by RunApp. It lives here for the same reason `win` and `dx`
  // do: the window procedure has only an HWND to work from.
  core::InputFrame input;
  // The size the chain was last SUCCESSFULLY sized to, shared by both paths so
  // a synchronous resize does not leave the loop believing it still has work.
  UINT last_w = 0;
  UINT last_h = 0;
  bool in_size_move = false;
  // Reentrancy guard. A D3D/DXGI call can dispatch messages, and a present
  // started from inside a present is how this kind of code deadlocks.
  bool in_flight = false;
  // BUG-26 diagnostics: emit at most ONE "sync" line per drag. TraceDrag opens
  // trace.txt on every call, so a line per WM_SIZE would slow the very drag it
  // is measuring.
  bool sync_traced = false;
  // BUG-26: the same bounding trick for the WM_WINDOWPOSCHANGING pre-stage, so
  // a drag that produced NO `pre` line proves the pre-stage never ran, rather
  // than leaving us guessing whether the hook fired.
  bool prestage_traced = false;
  // BUG-26: true between WM_ENTERSIZEMOVE and WM_EXITSIZEMOVE while the chain
  // is deliberately OVERSIZED, so no ResizeBuffers happens per mouse-move.
  bool oversize_active = false;
};
FrameCtx g_frame;

// PresentFrame and its result enum are defined further down this file, but
// HostWndProc's WM_WINDOWPOSCHANGING pre-stage calls it, so both are declared
// here. The default argument lives on the declaration, not the definition.
enum class PresentResult { Presented, Retry, Failed };
PresentResult PresentFrame(DxDevice& dx, bool allow_wait = false);

// Defined below (they need PresentFrame); declared here because the window
// procedure above them needs to call them.
bool EnsureChainForSize(UINT w, UINT h);
bool EnsureChainCoversClient();
void SyncResizeAndPresent();
void TraceDrag(const char* tag);

// R6/C4: input is a dirty source, but NOT every input event may be one. A
// mouse-move fires continuously, so dirtying on each would hold a permanent
// 60 fps redraw on an idle window - the exact busy-wait this loop was built to
// eliminate. Discrete events (buttons, wheel, keys, characters) always dirty. A
// move dirties only while a drag is in flight; until there are widgets, a hover
// change has nothing to redraw, and the snapshot carries it for free anyway.
inline void MarkDirtyForInput(Window* win, bool dirty) {
  if (win != nullptr && dirty) win->MarkDirty();
}

// D-15/D-16: the host window procedure. Routing lives here; state decisions stay in
// Window, and the DComp lifecycle stays in RunApp, where the ordering is visible.
LRESULT CALLBACK HostWndProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l) {
  // WM_NCCALCSIZE is delivered DURING CreateWindowEx, before GWLP_USERDATA is
  // set, so the null check below used to swallow it and hand it to
  // DefWindowProc. That applied the default system frame, and the client area
  // was born 22x56 px smaller than the window and never corrected: measured
  // 1280x800 window -> 1258x744 client. The uncovered margin composited black
  // because the swap chain is premultiplied. It must be handled first, from the
  // HWND alone.
  if (msg == WM_NCCALCSIZE) {
    // lParam is an NCCALCSIZE_PARAMS*, NOT a CREATESTRUCTW* - see the J7 note in
    // probe.cpp, where guessing that faulted the callback (0xC000041D).
    return Window::NccCalcSizeFor(hwnd, w, l);
  }

  Window* win = reinterpret_cast<Window*>(::GetWindowLongPtrW(hwnd, GWLP_USERDATA));
  if (win == nullptr) return ::DefWindowProcW(hwnd, msg, w, l);

  switch (msg) {
    case WM_NCCALCSIZE: {
      // lParam is an NCCALCSIZE_PARAMS*, NOT a CREATESTRUCTW* - see the J7 note in
      // probe.cpp, where guessing that faulted the callback (0xC000041D).
      return win->OnNCCalcSize(w, l);
    }

    case WM_NCHITTEST: {
      // W2. THIS CASE IS THE REASON THE WINDOW WAS IMMOBILE.
      //
      // HostWndProc had no WM_NCHITTEST at all, so every one of these went to
      // DefWindowProc, which for a plain WS_OVERLAPPEDWINDOW answers HTCLIENT
      // for the whole window. The user-visible result was a window that could
      // not be dragged, not resized, and whose caption buttons did nothing:
      // Window::NCHitTest, HitTestClient, HitToHt and the whole caption-button
      // cluster in window.cpp were implemented, unit-reachable, and NEVER CALLED.
      //
      // Because WM_NCCALCSIZE returns 0 the client area covers the frame, so the
      // caption strip and resize borders are inside the CLIENT rect and only a
      // hit test can classify them. lParam is SCREEN coordinates here; the
      // ScreenToClient conversion lives in NCHitTest and happens exactly once.
      POINT pt = {GET_X_LPARAM(l), GET_Y_LPARAM(l)};
      return win->NCHitTest(pt);
    }

    case WM_NCMOUSEMOVE:
      // W2/W3. Hover state for the caption cluster. This is a non-client message
      // precisely because HTCAPTION routes input away from the client window.
      win->OnNcMouseMove(POINT{GET_X_LPARAM(l), GET_Y_LPARAM(l)});
      return 0;

    case WM_NCMOUSELEAVE:
      win->OnNcMouseLeave();
      return 0;

    case WM_NCLBUTTONDOWN:
    case WM_NCLBUTTONUP:
    case WM_NCRBUTTONUP:
      // W2/W9. Delegated to DefWindowProc on purpose. The hit test now returns
      // HTCAPTION for the strip and HTMINBUTTON/HTMAXBUTTON/HTCLOSE for the
      // buttons, and the OS drives all of them from a real frame: HTCAPTION
      // starts the drag, and the three button codes run the standard commands.
      //
      // Calling Window::OnNcLButtonUp here instead would DOUBLE-ACT - the
      // maximize toggle would flip twice and restore itself. Window keeps those
      // handlers for the NOACTIVATE dock window (M1+), which has no OS frame to
      // drive it; this main window is not that window.
      return ::DefWindowProcW(hwnd, msg, w, l);

    case WM_GETMINMAXINFO: {
      // W6. A minimum size, so a resize cannot produce an unusable window.
      // W6/BUG-05. The Window converts its dp minimum to px at the CURRENT
      // dpi, at query time. The old code read a pre-converted pair that
      // was initialised once (640x420 physical px) and never recomputed.
      win->OnGetMinMaxInfo(reinterpret_cast<MINMAXINFO*>(l));
      return 0;
    }

    case WM_SYSCOMMAND: {
      // W1/J7. Track the zoomed state, because WM_NCCALCSIZE needs to know it
      // to apply the maximized inset.
      if ((w & 0xFFF0) == SC_MAXIMIZE) {
        win->set_maximized(true);
      } else if ((w & 0xFFF0) == SC_RESTORE || (w & 0xFFF0) == SC_MINIMIZE) {
        win->set_maximized(false);
      }
      break;   // fall through to DefWindowProc
    }

    case WM_ERASEBKGND:
      // E2: returning 1 is what removes the black flash on maximize and snap.
      // Returning 0 lets Windows paint a black canvas we then overwrite, which is
      // precisely the flicker E2 forbids.
      return 1;

    case WM_DWMCOMPOSITIONCHANGED:
      // W1: the margins call must be repeated here, or a composition restart
      // silently drops the sheet of glass.
      win->OnCompositionChanged();
      win->MarkDirty();   // BUG-01: the recomposited surface must be re-presented
      return 0;

    case WM_DPICHANGED:
      // E1/BUG-06/RV-07. The handler lives in Window, which LEDGER P1 already
      // names as the owner - and which the probe can therefore drive directly,
      // so RV-07's "the guard cannot get stuck" fix has a test.
      return win->OnDpiChanged(w, l);

    case WM_WINDOWPOSCHANGING: {
      // BUG-26, third part - the measured one. Every handler above runs AFTER
      // the window rect has already changed, so each presents into a window that
      // is already larger than its buffer. trace.txt measured that shortfall -
      // logged BEFORE the fix-up - at 4-11 px at the first synchronous present
      // of each drag, and that thin strip is the residual dark edge. Re-arming
      // on WM_SIZE or WM_PAINT cannot close it: both are dispatched after the
      // fact, one mouse-move step too late.
      //
      // WM_WINDOWPOSCHANGING is delivered BEFORE the move/resize is applied, so
      // staging the buffer here puts the frame on screen BEFORE the rect grows.
      // Scoped to in_size_move so ordinary moves, maximize and snap keep using
      // the established paths - which also keeps the staged size correct,
      // because outside a zoom transition our client equals the window, so cx/cy
      // IS the client size and the following WM_SIZE then finds the chain already
      // at the right size and does not resize a second time.
      if (g_frame.in_size_move && !g_frame.oversize_active && !g_frame.in_flight &&
          g_frame.dx != nullptr && g_frame.win != nullptr) {
        const WINDOWPOS* wp = reinterpret_cast<const WINDOWPOS*>(l);
        if (wp != nullptr && (wp->flags & SWP_NOSIZE) == 0 && wp->cx > 0 &&
            wp->cy > 0 && (wp->flags & SWP_HIDEWINDOW) == 0 &&
            !::IsIconic(g_frame.win->handle())) {
          const UINT stage_w = static_cast<UINT>(wp->cx);
          const UINT stage_h = static_cast<UINT>(wp->cy);
          if (stage_w != g_frame.last_w || stage_h != g_frame.last_h) {
            g_frame.in_flight = true;
            if (EnsureChainForSize(stage_w, stage_h)) {
              PresentFrame(*g_frame.dx, /*allow_wait=*/true);
            }
            g_frame.in_flight = false;
            // Logged AFTER the resize, so a `pre` line whose buffer already
            // equals the window is direct proof the hook fired in time.
            if (!g_frame.prestage_traced) {
              g_frame.prestage_traced = true;
              TraceDrag("pre");
            }
          }
        }
      }
      break;   // the system must still apply the move/resize
    }

    case WM_ENTERSIZEMOVE:
      // BUG-26: from here until WM_EXITSIZEMOVE the system owns the mouse AND
      // this thread, so the frame loop below cannot iterate. Every resize that
      // happens in that window of time must be presented from here instead.
      g_frame.in_size_move = true;
      g_frame.sync_traced = false;
      g_frame.prestage_traced = false;

      // BUG-26, architecture change. Resizing the chain on every mouse-move
      // calls ResizeBuffers dozens of times a second, and each call tears the
      // back buffer down and allocates a new one. The trace had already proved
      // the buffer was big enough - `sync` reported 0 px behind the window - yet
      // a dark band still showed, so the residual was never a coverage hole: it
      // was the churn itself. So the chain is sized ONCE here, generously, and
      // then left alone for the whole drag. The surplus is clipped by the window
      // rect and costs nothing. Two ResizeBuffers per drag instead of fifty.
      if (g_frame.dx != nullptr && g_frame.win != nullptr) {
        RECT wr0 = {};
        ::GetWindowRect(hwnd, &wr0);
        const UINT cur_w = static_cast<UINT>(wr0.right - wr0.left);
        const UINT cur_h = static_cast<UINT>(wr0.bottom - wr0.top);
        const int margin = DpToPx(200.0f, g_frame.win->dpi_scale());
        const UINT wide_w = cur_w + static_cast<UINT>(margin * 2);
        const UINT wide_h = cur_h + static_cast<UINT>(margin * 2);
        g_frame.oversize_active = true;
        if (EnsureChainForSize(wide_w, wide_h)) {
          PresentFrame(*g_frame.dx, /*allow_wait=*/false);
        }
        TraceDrag("wide");
      }
      return 0;

    case WM_EXITSIZEMOVE:
      // Drop the oversized buffer and land on the exact final client size: the
      // last WM_SIZE of a drag can arrive before the window settles, and the
      // loop may not have reached its resize block yet.
      g_frame.in_size_move = false;
      g_frame.oversize_active = false;
      SyncResizeAndPresent();
      TraceDrag("exit");
      return 0;

    case WM_SIZE: {
      // RV-07: the guard has to be READ HERE, before the line that clears it.
      // Read after EndDpiChange it is unconditionally false, so the guard guards
      // nothing - which is the state this flag has been in since it was added:
      // written by WM_DPICHANGED, cleared by this very message, read by nobody.
      // E1's "does not reflow twice" guarantee was therefore vacuous, and the
      // M1 dock layout that is meant to consume it had nothing to consume.
      const bool provoked_by_dpi = win->dpi_change_in_flight();
      win->EndDpiChange();
      // BUG-01: this message is usually dispatched by the system's modal
      // move/size pump, which never runs the app's idle GetMessageW branch,
      // so the dirty flag is raised HERE, on the Window, where every pump
      // can reach it. Clearing is the frame loop's job.
      win->MarkDirty();
      // BUG-26: during a drag the frame is presented from HERE, synchronously, so
      // the composited frame always covers the rectangle it is being shown in.
      // E1: a WM_SIZE provoked by WM_DPICHANGED must NOT present - that handler
      // is still mid-flight and the suggested rect is not applied yet, so
      // presenting here is precisely the double reflow E1 exists to prevent. The
      // dirty flag is already set, so the frame loop presents the settled size
      // on the very next iteration.
      if (g_frame.in_size_move && !provoked_by_dpi) SyncResizeAndPresent();
      return 0;
    }

    case WM_PAINT:
      // BUG-01: WM_PAINT may be dispatched by ANY pump (ours, the modal
      // move/size pump, a nested loop). DefWindowProc then validates the
      // update region, which is the ONLY notification a resize exposes -
      // so the dirty flag must be raised before falling through.
      win->MarkDirty();
      // BUG-26, second half. A resize INVALIDATES the window, and mid-drag that
      // WM_PAINT is dispatched by the system's modal loop, where the frame loop
      // cannot run. Raising the dirty flag alone therefore changes nothing until
      // the mouse is released, and the newly exposed region stays dark for that
      // whole time - which is exactly the residual "dark window for a split
      // second" reported after the WM_SIZE fix. Answer it HERE; DefWindowProc
      // still runs below and validates the update region.
      if (g_frame.in_size_move) SyncResizeAndPresent();
      return ::DefWindowProcW(hwnd, msg, w, l);

    // ---- input (C3, C4, E11) ------------------------------------------------
    // Everything here TRANSLATES a Win32 message into a core-layer call. No
    // decisions are made here and none of it is testable in the portable
    // harness; that is the boundary the split is for.

    case WM_MOUSEMOVE:
      // Client coordinates - lParam is already in client space for this message.
      g_frame.input.OnMouseMove(GET_X_LPARAM(l), GET_Y_LPARAM(l));
      MarkDirtyForInput(win, g_frame.input.buttons_down() != 0);   // drag only
      return 0;

    case WM_MOUSEWHEEL: {
      // Three things are wrong with reading this like a mouse-move, and all
      // three are silent:
      //   1. The delta is in the HIGH word of wParam, in 120ths of a notch.
      //    GET_X_LPARAM(l) reads the LOW word, which is not the delta.
      //   2. The position in lParam is SCREEN space, not client space.
      //   3. The delta is POSITIVE when the wheel goes up, and Windows'
      //    convention is that a positive wheel means "away from the user".
      g_frame.input.OnWheel(GET_WHEEL_DELTA_WPARAM(w));
      POINT pt = {GET_X_LPARAM(l), GET_Y_LPARAM(l)};
      ::ScreenToClient(hwnd, &pt);
      g_frame.input.OnMouseMove(pt.x, pt.y);
      MarkDirtyForInput(win, true);
      return 0;
    }

    case WM_LBUTTONDOWN:
    case WM_RBUTTONDOWN:
    case WM_MBUTTONDOWN: {
      const int b = platform::ButtonFromMessage(msg);   // P3-01: never from wParam
      if (b >= 0) {
        g_frame.input.OnMouseMove(GET_X_LPARAM(l), GET_Y_LPARAM(l));
        // E11: SetCapture is what lets a drag continue outside the client.
        // Without it WM_MOUSEMOVE stops at the window edge, the drag freezes
        // mid-gesture, and the button is still down when the pointer returns.
        ::SetCapture(hwnd);
        // Armed only when a drag starts. A TrackMouseEvent on every
        // WM_MOUSEMOVE is a syscall per mouse move, and with no button held
        // there is nothing for a leave notification to invalidate.
        TRACKMOUSEEVENT tme = {sizeof(tme), TME_LEAVE, hwnd, 0};
        ::TrackMouseEvent(&tme);
        g_frame.input.OnMouseButton(b, true);
      }
      MarkDirtyForInput(win, true);
      return 0;
    }

    case WM_XBUTTONDOWN:
    case WM_XBUTTONUP: {
      // X buttons put the button number in the HIGH word, so they cannot go
      // through ButtonFromVk at all.
      const int b = 3 + (GET_XBUTTON_WPARAM(w) == XBUTTON2 ? 1 : 0);
      g_frame.input.OnMouseMove(GET_X_LPARAM(l), GET_Y_LPARAM(l));
      if (msg == WM_XBUTTONDOWN) {
        ::SetCapture(hwnd);
        TRACKMOUSEEVENT tme = {sizeof(tme), TME_LEAVE, hwnd, 0};
        ::TrackMouseEvent(&tme);
      }
      g_frame.input.OnMouseButton(b, msg == WM_XBUTTONDOWN);
      // P3-07: mirror the left/right/middle path. Capture was taken on down and must be
      // dropped once NOTHING is held, or the pointer stays captured after the click.
      if (msg == WM_XBUTTONUP &&
          (g_frame.input.buttons_down() & ~core::InputFrame::ButtonBit(b)) == 0) {
        ::ReleaseCapture();
      }
      MarkDirtyForInput(win, true);
      return TRUE;   // documented return value for a handled XBUTTON message
    }

    case WM_LBUTTONUP:
    case WM_RBUTTONUP:
    case WM_MBUTTONUP: {
      const int b = platform::ButtonFromMessage(msg);   // P3-01: never from wParam
      if (b >= 0) {
        g_frame.input.OnMouseMove(GET_X_LPARAM(l), GET_Y_LPARAM(l));
        g_frame.input.OnMouseButton(b, false);
        // Release the capture only once NOTHING is still held. Dropping it
        // while a second button is down silently ends that button's drag.
        if ((g_frame.input.buttons_down() & ~core::InputFrame::ButtonBit(b)) == 0) {
          ::ReleaseCapture();
        }
      }
      MarkDirtyForInput(win, true);
      return 0;
    }

    case WM_MOUSELEAVE:
      // No button-up is delivered when the pointer leaves mid-press, so the
      // button would otherwise stay down until the user clicks again.
      g_frame.input.ReleaseAllButtons();
      return 0;

    case WM_CAPTURECHANGED:
      // E11: the capture can be taken by another window, a UAC prompt, or a
      // session switch, and Windows delivers NO button-up when it goes. A drag
      // left running here keeps reporting a pointer position nobody can move,
      // and the next click would then look like a second concurrent drag.
      g_frame.input.OnCaptureChanged();
      return 0;

    case WM_KEYDOWN:
    case WM_SYSKEYDOWN: {
      const core::Key k = platform::KeyFromVk(static_cast<int>(w));
      if (k != core::Key::None) {
        g_frame.input.OnKey(k, true);
        MarkDirtyForInput(win, true);
      }
      break;   // DefWindowProc still owns Alt/System-menu handling
    }

    case WM_KEYUP:
    case WM_SYSKEYUP: {
      const core::Key k = platform::KeyFromVk(static_cast<int>(w));
      if (k != core::Key::None) {
        g_frame.input.OnKey(k, false);
        MarkDirtyForInput(win, true);
      }
      break;
    }

    case WM_CHAR:
      // E11: wParam is ONE UTF-16 CODE UNIT, not a character. Every non-BMP
      // character arrives as two of these, and a text field that emits them
      // separately fills with U+FFFD. WM_SYSCHAR is deliberately NOT handled -
      // Alt+key is a menu accelerator, not text.
      g_frame.input.OnCharUnit(static_cast<unsigned>(w));
      MarkDirtyForInput(win, true);
      return 0;

    case WM_KILLFOCUS:
      // E11: Windows does NOT deliver the matching WM_KEYUP when focus is lost,
      // so every key held during an Alt+Tab would stay down for the rest of the
      // session. Same for a button held while a menu took the click.
      g_frame.input.ReleaseAllKeys();
      g_frame.input.ReleaseAllButtons();
      return 0;

    case WM_CLOSE:
      ::DestroyWindow(hwnd);
      return 0;

    case WM_DESTROY:
      ::PostQuitMessage(0);
      return 0;
  }
  return ::DefWindowProcW(hwnd, msg, w, l);
}

// M0. Build the composition content for this window.
//
// OWNERSHIP: DxDevice::CreateSwapChain OWNS the composition tree (target, root
// visual, SetContent, Commit). This function used to build a second one over the
// same swap chain, which gave one HWND two DComp targets and made the winner
// depend on an inconsistent `topmost` flag (TRUE in dx.cpp, FALSE here). It now
// only asks the device to (re-)attach, and delegates the tree to its owner.
bool BuildCompositionTree(DxDevice& dx, Window& win, QualityTier tier) {
  if (!dx.composition()) return false;

  RECT cr = {};
  if (!::GetClientRect(win.handle(), &cr)) return false;
  const UINT w = static_cast<UINT>(cr.right - cr.left);
  const UINT h = static_cast<UINT>(cr.bottom - cr.top);
  if (w == 0 || h == 0) return false;   // E2: never present a zero-sized chain

  // A chain that already exists at this size only needs its content re-linked
  // (the resize case). BUG-14: if that re-link fails the chain is unusable
  // (device removed, failed resize) - fall through and rebuild the whole
  // chain + tree instead of reporting a failure the caller cannot recover.
  if (dx.swap_chain() != nullptr && dx.AttachContent()) return true;
  return dx.CreateSwapChain(win.handle(), w, h, tier);
}

// M0. One frame: present the current back buffer.
//
// BUG-02. The result distinguishes "frame is on the screen" from "frame was
// dropped, try again". The old signature returned bool and mapped
// DXGI_ERROR_WAS_STILL_DRAWING to true, so the caller cleared the dirty
// flag for a present that never happened - the first frame could be lost
// and the window would sit on its DComp-default black until a later event.
// The enum is declared with the forward declarations at the top of this file,
// because HostWndProc's WM_WINDOWPOSCHANGING pre-stage calls PresentFrame.
//
// J5/G1: the chain is B8G8R8A8 with premultiplied alpha (X28), so anything drawn
// into it must be given PREMULTIPLIED. J6 note: this Present is what a later
// DwmFlush() would be measured against, so it must happen before the wait - that
// ordering is exactly what X29 got wrong in the M0a probe.
PresentResult PresentFrame(DxDevice& dx, bool allow_wait) {
  if (dx.swap_chain() == nullptr) return PresentResult::Failed;

  // M0 presents a CLEARED frame. The first version of this function called
  // Present() and nothing else, so the back buffer was whatever the driver left
  // in it - which on this host is black. A swap chain that is presented without
  // ever being written is not "a presented frame", it is an undefined one, and
  // there is no way to tell a working renderer from a dead one by looking.
  //
  // The clear is deliberately a distinctive mid slate-teal rather than black,
  // for two reasons: a black clear is indistinguishable from the failure above,
  // and a non-black fill is positive evidence that THESE pixels came from THIS
  // Present. That is what makes a screenshot able to prove the frame arrived.
  HRESULT hr = S_OK;
  ID3D11RenderTargetView* rtv = dx.AcquireRtv(&hr);
  if (rtv == nullptr || FAILED(hr)) {
    FCS_CHECK_HR(hr);
    return PresentResult::Failed;
  }
  ID3D11DeviceContext* ctx = dx.context();
  ctx->OMSetRenderTargets(1, &rtv, nullptr);

  // G1/X28: the chain is PREMULTIPLIED, so the clear value must be premultiplied
  // too. A straight-alpha colour here is a real bug: with alpha 1.0 the two are
  // numerically identical, so the clear deliberately keeps alpha at 1.0 to stay
  // correct by construction while later M2 work introduces partial alpha.
  const FLOAT clear[4] = {0.16f, 0.22f, 0.28f, 1.0f};
  ctx->ClearRenderTargetView(rtv, clear);

  // The clear must be ordered before the Present. D3D11 context state is not
  // implicitly flushed by Present on every adapter, and an unflushed clear is
  // exactly the kind of thing that presents as a stale or black buffer.
  ctx->Flush();

  // BUG-26: DXGI_PRESENT_DO_NOT_WAIT is right for the frame loop, where a
  // dropped frame is simply retried on the next iteration, but wrong mid-drag,
  // where a dropped frame IS the visible black strip. With allow_wait the call
  // may block until a buffer frees instead of returning WAS_STILL_DRAWING.
  // SyncInterval stays 0 either way: waiting for a vblank inside the modal loop
  // is felt as the window lagging the pointer (X29's split of pacing vs cost).
  const UINT present_flags =
      allow_wait ? 0u : static_cast<UINT>(DXGI_PRESENT_DO_NOT_WAIT);
  hr = dx.Present(present_flags);
  // BUG-02: WAS_STILL_DRAWING means the frame DID NOT reach the screen.
  // It is not a device failure, but it is not success either - the caller
  // must keep the dirty flag set and retry on a later iteration.
  if (hr == DXGI_ERROR_WAS_STILL_DRAWING) return PresentResult::Retry;
  if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
    // E3: recoverable, but rebuilding device + chain + visual is M0+ work. Report
    // it rather than spinning on a dead device.
    FCS_CHECK_HR(hr);
    return PresentResult::Failed;
  }
  return (FCS_CHECK(hr) == S_OK) ? PresentResult::Presented
                                 : PresentResult::Failed;
}

// BUG-26. Make the swap chain cover the LIVE client rect.
//
// Extracted from RunApp's loop so the synchronous size/move path and the frame
// loop share ONE implementation. Two copies of a resize guard is how the strip
// gets fixed in one path and left broken in the other - this file has already
// been bitten once by two owners of the same composition state (see the
// ownership note on BuildCompositionTree).
// BUG-26: takes the size explicitly rather than reading the client rect, because
// WM_WINDOWPOSCHANGING needs to stage the PROPOSED size before the window rect
// has actually moved to it. Every other caller wants the live client rect and
// goes through EnsureChainCoversClient below.
bool EnsureChainForSize(UINT w, UINT h) {
  if (g_frame.dx == nullptr || g_frame.win == nullptr) return false;
  DxDevice& dx = *g_frame.dx;
  HWND hwnd = g_frame.win->handle();

  if (w == 0 || h == 0) return false;   // E2: never touch a zero-size surface
  if (w == g_frame.last_w && h == g_frame.last_h) return true;

  // E2: on SUCCESS the DComp content link must be re-established.
  // ResizeBuffers allocates a new back buffer but does not re-point root_ at it,
  // so the old (now destroyed) buffer stays composited and the window goes
  // black. Note the polarity: AttachContent is the success path.
  bool resized = dx.ResizeSwapChain(w, h);
  if (resized) {
    dx.AttachContent();
  } else {
    // Recovery. The old code called BuildCompositionTree here, which for an
    // ALREADY-EXISTING chain only re-links content and never changes its size -
    // so it could not possibly fix a size mismatch. A failed resize is only
    // recoverable by rebuilding at the new size.
    dx.DestroySwapChain();
    resized = dx.CreateSwapChain(hwnd, w, h, g_frame.tier);
  }
  // last_w/last_h advance ONLY after the chain really is the new size. Advancing
  // them BEFORE the attempt was a real defect: a single failed ResizeBuffers made
  // the guard permanently false, so the chain stayed at its old size for the
  // rest of the session and the uncovered part of the window stayed black.
  // Caching the ATTEMPT instead of the RESULT is what made the failure permanent.
  if (resized) {
    g_frame.last_w = w;
    g_frame.last_h = h;
  }
  return resized;
}

bool EnsureChainCoversClient() {
  if (g_frame.win == nullptr) return false;
  RECT cr = {};
  if (!::GetClientRect(g_frame.win->handle(), &cr)) return false;
  const UINT cw = static_cast<UINT>(cr.right - cr.left);
  const UINT ch = static_cast<UINT>(cr.bottom - cr.top);
  // BUG-26: mid-drag the chain is deliberately LARGER than the window (see
  // WM_ENTERSIZEMOVE) so the drag costs zero ResizeBuffers. Never shrink it
  // here - that would undo the whole point - and only grow, and only if the
  // user outran the margin.
  if (g_frame.oversize_active && cw <= g_frame.last_w && ch <= g_frame.last_h) {
    return true;
  }
  return EnsureChainForSize(cw, ch);
}

// BUG-26. One synchronous resize-and-present, safe to call from inside the
// system's modal size/move loop when the frame loop cannot run.
//
// The reentrancy guard is load-bearing: Present can dispatch messages, and
// starting a second present from inside the first is how this kind of code
// deadlocks. `in_flight` is cleared on every path.
void SyncResizeAndPresent() {
  if (g_frame.dx == nullptr || g_frame.win == nullptr) return;
  if (g_frame.in_flight) return;
  if (::IsIconic(g_frame.win->handle())) return;   // E2: nothing to draw

  g_frame.in_flight = true;
  // BEFORE the resize, so the line records how far the buffer had fallen behind
  // the window at the moment the compositor would be showing the shortfall.
  if (g_frame.in_size_move && !g_frame.sync_traced) {
    g_frame.sync_traced = true;
    TraceDrag("sync");
  }
  EnsureChainCoversClient();
  const PresentResult pr = PresentFrame(*g_frame.dx, /*allow_wait=*/true);
  g_frame.in_flight = false;

  // Same contract as the loop: only a frame that actually reached the screen
  // consumes the dirty flag, so a Retry is still redrawn by the loop.
  if (pr == PresentResult::Presented) g_frame.win->ClearDirty();
}

// E2/W1 diagnostic sink.
//
// fcs_glass is a WIN32-subsystem binary, so std::printf reaches no console and
// the size-mismatch warning was invisible - which is precisely why a 354 px
// uncovered strip survived two sign-off passes. This appends to trace.txt
// (already in .gitignore) so the numbers are readable after the fact.
void TraceSize(const char* fmt, UINT a, UINT b, UINT c, UINT d) {
  char line[256];
  std::snprintf(line, sizeof(line), fmt, a, b, c, d);
  std::printf("FCS Glass: %s\n", line);
  if (FILE* f = std::fopen("trace.txt", "a")) {
    std::fprintf(f, "%s\n", line);
    std::fclose(f);
  }
}

// BUG-26 diagnostic. ONE line at drag start, at the first synchronous present,
// and at drag end - bounded on purpose for the reason in g_frame.sync_traced.
// The three numbers are the ones that decide the bug: if the buffer lags the
// WINDOW while the window is growing, the shortfall is exactly the region the
// compositor shows dark.
void TraceDrag(const char* tag) {
  if (g_frame.win == nullptr || g_frame.dx == nullptr) return;
  RECT wr = {};
  RECT cr = {};
  ::GetWindowRect(g_frame.win->handle(), &wr);
  ::GetClientRect(g_frame.win->handle(), &cr);
  UINT bw = 0;
  UINT bh = 0;
  (void)g_frame.dx->SwapChainBufferSize(&bw, &bh);
  char line[176];
  std::snprintf(line, sizeof(line), "%-5s window=%ux%u client=%ux%u buffer=%ux%u",
                tag, static_cast<UINT>(wr.right - wr.left),
                static_cast<UINT>(wr.bottom - wr.top),
                static_cast<UINT>(cr.right - cr.left),
                static_cast<UINT>(cr.bottom - cr.top), bw, bh);
  std::printf("FCS Glass: %s\n", line);
  if (FILE* f = std::fopen("trace.txt", "a")) {
    std::fprintf(f, "%s\n", line);
    std::fclose(f);
  }
}

int RunApp(HINSTANCE instance) {
  // J4 first: restrict the DLL search order before anything else can load a DLL.
  if (!InitDllSearch()) {
    std::printf("FCS Glass: DLL search could not be restricted to System32 (J4).\n");
  }

  // P1. The manifest already set the process default; this is the runtime path and
  // is what the probe measures. It must run before any HWND exists.
  const DpiState dpi = InitDpiAwareness();

  const OsInfo os = QueryOsInfo();
  std::printf("FCS Glass M0 - profile %s, build %lu, per-monitor-v2 %s\n",
              os.profile == OsProfile::Fluent ? "Fluent" : "Classic",
              static_cast<unsigned long>(os.build),
              dpi.per_monitor_v2 ? "on" : "off");

  // D5: one device, shared by every window this process owns.
  DxDevice dx;
  if (!dx.Create()) {
    std::printf("FCS Glass: device creation failed (0x%08lX).\n",
                static_cast<unsigned long>(dx.info().last_failure));
    return 1;
  }
  std::printf("FCS Glass: %s device, feature level %x, presented format %d.\n",
              dx.info().driver == DriverKind::Hardware ? "hardware" : "WARP",
              static_cast<unsigned>(dx.info().feature_level),
              static_cast<int>(dx.RenderTargetFormat(QualityTier::Full)));

  static const wchar_t kClass[] = L"FCSGlassHostWindow";
  if (!RegisterHostClass(instance, nullptr, &HostWndProc, kClass)) {
    std::printf("FCS Glass: window class registration failed.\n");
    return 1;
  }

  Window win;
  if (!win.Create(kClass, L"FolderCloneSync", WS_OVERLAPPEDWINDOW, 0,
                  CW_USEDEFAULT, CW_USEDEFAULT, 1280, 800, nullptr, instance)) {
    std::printf("FCS Glass: window creation failed.\n");
    return 1;
  }
  win.SetMinSizeDp(640, 420);   // W6

  // W4: profile attributes, then W1's sheet of glass. Both report HRESULTs.
  win.ApplyProfile(/*fluent=*/os.profile == OsProfile::Fluent, /*dark=*/true);   // P3-09
  if (!win.EnableSheetOfGlass()) {
    std::printf("FCS Glass: sheet of glass not enabled; continuing (reported, not fatal).\n");
  }

  // R6: WARP or a remote session forces Basic. Console + hardware on this host.
  const QualityTier tier =
      (os.session == SessionKind::Remote || dx.info().driver == DriverKind::Warp)
          ? QualityTier::Basic
          : QualityTier::Full;

  if (!BuildCompositionTree(dx, win, tier)) {
    std::printf("FCS Glass: could not build the composition tree.\n");
    return 1;
  }

  // BUG-26: publish the two objects HostWndProc needs to drive a synchronous
  // frame while the system's modal size/move loop owns the thread. Set only once
  // the composition tree exists, so the window procedure can never present
  // against a half-built chain.
  g_frame.dx = &dx;
  g_frame.win = &win;
  g_frame.tier = tier;

  ::ShowWindow(win.handle(), SW_SHOW);
  ::UpdateWindow(win.handle());

  // Research finding 4: present BEFORE the loop, or the window shows empty for one
  // refresh and a later DwmFlush measures the previous frame's interval (X29).
  const PresentResult first = PresentFrame(dx);
  // BUG-02: a dropped first present is retried by the loop below, because
  // the Window starts dirty and stays dirty until a frame actually lands.
  std::printf("FCS Glass: first frame %s; running. Close the window to exit.\n",
              first == PresentResult::Presented ? "presented" : "deferred (will retry)");

  MSG msg = {};
  bool running = true;
  // R6: "render on demand and sleep when idle". The first version of this loop
  // presented unconditionally, which measured 9.2% CPU while doing nothing -
  // against T10's idle budget of under 1%. An unconditional present is a busy
  // wait dressed up as a frame loop, and it also starves WM_SIZE/WM_DPICHANGED
  // processing enough that SetWindowPos was being ignored in testing.
  //
  // The fix is the two-part contract R6 actually states:
  //   1. `needs_redraw` is set by the events that change the image, and cleared
  //      once the frame is presented. Nothing repaints an unchanged window.
  //   2. When there is nothing to draw, block in GetMessageW instead of spinning.
  // BUG-01: dirty state lives on `win` (Window::MarkDirty/ClearDirty) so
  // every message pump - ours AND the system's modal move/size pump - can
  // reach it. The Window starts dirty, so the first frame still happens.
  const int frame_budget_ms = dx.TargetFrameMs(tier);   // R6: 60 fps Full, 30 Basic
  // BUG-26: the size the chain was last successfully sized to now lives on
  // g_frame, because the synchronous size/move path in HostWndProc must share it
  // with this loop. Seeded to 0 so the first frame always performs its initial
  // resize/attach.
  g_frame.last_w = 0;
  g_frame.last_h = 0;
  // E2/W1. Edge-triggered so one bad frame does not spam the log every redraw.
  bool reported_size_mismatch = false;
  // One-shot: the first presented frame's sizes are logged exactly once.
  bool logged_first_size = false;
  // P3-02: consecutive failed presents; bounds the device-rebuild attempts below.
  int present_failures = 0;

  while (running) {
    if (win.dirty()) {
      // Drain input and window messages first, so a resize or DPI change is
      // applied before the frame that depends on it is drawn.
      while (::PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
        if (msg.message == WM_QUIT) { running = false; break; }
        ::TranslateMessage(&msg);
        ::DispatchMessageW(&msg);
      }
      if (!running) break;
      // C3: the freeze. Once per frame, AFTER the message drain and BEFORE
      // anything reads input - that ordering is the whole requirement, since two
      // widgets reading input at different points must not be able to disagree
      // because a WM_MOUSEMOVE landed between them. Nothing reads it yet (the
      // widgets arrive with M1's UI layer), but the call belongs here rather than
      // at the first widget: the discipline is only worth anything in place before
      // something depends on it.
      g_frame.input.Snapshot();
      if (!win.ShouldRender()) { win.ClearDirty(); continue; }  // E2 minimized

      RECT cr = {};
      if (::GetClientRect(win.handle(), &cr)) {
        const UINT w = static_cast<UINT>(cr.right - cr.left);
        const UINT h = static_cast<UINT>(cr.bottom - cr.top);
        // E2/BUG-26: the resize itself lives in EnsureChainCoversClient, which
        // the synchronous size/move path also calls - ONE implementation, so the
        // two paths cannot drift apart. It still only touches the chain when the
        // size ACTUALLY changed: calling ResizeSwapChain unconditionally every
        // frame reallocated both buffers on each redraw for no reason, a resize
        // storm that also drops the DComp content link (see AttachContent).
        EnsureChainCoversClient();
        // One-shot: record the first presented frame's geometry, because the
        // first question about any fill bug is "what did we ask for vs what did
        // the client actually give us".
        if (!logged_first_size) {
          logged_first_size = true;
          RECT w0 = {};
          ::GetWindowRect(win.handle(), &w0);
          TraceSize("WINDOW %ux%u", static_cast<UINT>(w0.right - w0.left),
                    static_cast<UINT>(w0.bottom - w0.top), 0, 0);
          UINT bw0 = 0, bh0 = 0;
          if (dx.SwapChainBufferSize(&bw0, &bh0)) {
            TraceSize("FIRST buffer=%ux%u client=%ux%u", bw0, bh0, w, h);
          }
        }
        // E2/W1. The back buffer must COVER the client rect. The cached
        // width_/height_ only record what we ASKED for, so they cannot detect a
        // resize that was skipped or silently failed - which is exactly how the
        // M0 capture ended up with an uncovered margin compositing black.
        // Read the granted size back from DXGI and compare it to the live client
        // rect. On a PREMULTIPLIED chain the uncovered region is alpha 0, so it
        // shows whatever is behind the window instead of our clear colour.
        {
          UINT bw = 0;
          UINT bh = 0;
          if (dx.SwapChainBufferSize(&bw, &bh)) {
            // BUG-26: mid-drag the chain is intentionally LARGER than the client,
            // so comparing the two is meaningless until the drag lands.
            if (!g_frame.in_size_move && (bw != w || bh != h)) {
              if (!reported_size_mismatch) {
                reported_size_mismatch = true;
                TraceSize("MISMATCH buffer=%ux%u client=%ux%u", bw, bh, w, h);
                // Force another resize attempt next frame. last_w/last_h are
                // deliberately not advanced while the sizes disagree.
                g_frame.last_w = 0;
                g_frame.last_h = 0;
              }
            } else {
              reported_size_mismatch = false;
            }
          }
        }
        const PresentResult pr = PresentFrame(dx);
        if (pr == PresentResult::Retry) {
          // BUG-02: the present did not happen; keep the dirty flag set
          // and retry next iteration. The 1 ms yield stops this becoming a
          // busy spin inside the single vblank it usually takes.
          ::Sleep(1);
          continue;
        }
        if (pr == PresentResult::Failed) {
          // E3: the chain or device may be gone. Rebuild; if that also
          // fails, drop the dirty flag so a dead device cannot spin the
          // loop - the next event re-arms a frame.
          // P3-02: bound the recovery. A persistent NON-device failure (bad descriptor, an
          // AcquireRtv error) must not rebuild the whole device on every iteration for
          // ever. Give up for this dirty cycle; the next event re-arms a fresh burst.
          if (++present_failures > 3) {
            TraceSize("PRESENT_GIVEUP failures=%u 0 0 0", static_cast<UINT>(present_failures), 0, 0, 0);
            present_failures = 0;
            win.ClearDirty();
            continue;
          }
          dx.Recreate();
          g_frame.last_w = 0;   // P3-02: the rebuilt chain is a new size authority
          g_frame.last_h = 0;
          if (BuildCompositionTree(dx, win, tier)) {
            // BUG-20: the failed present never reached the screen, and a
            // freshly built chain has never been presented - it holds
            // whatever the allocator left, which composites as black. Keep
            // the dirty flag SET so the next iteration presents the
            // recovered chain, instead of idling on a black window until
            // some unrelated event re-arms a frame. Sleep one frame budget
            // so a persistently failing present cannot spin hot.
            ::Sleep(static_cast<DWORD>(frame_budget_ms));
            continue;
          }
          FCS_CHECK_HR(dx.info().last_failure);
        }
        if (pr == PresentResult::Presented) present_failures = 0;   // P3-02
        win.ClearDirty();
      }
      // R6 frame cap. Measured against the monotonic clock rather than assumed;
      // DwmFlush is deliberately NOT used here because it measures the refresh
      // period, not this frame's cost (X29).
      ::Sleep(static_cast<DWORD>(frame_budget_ms));
      continue;
    }

    // Idle: block until a message arrives instead of spinning. This is the
    // difference between ~0% and ~9% CPU.
    //
    // RV-06: GetMessageW has THREE outcomes, not two. `> 0` is a message, 0 is
    // WM_QUIT, and -1 is an ERROR. Testing `> 0` sends -1 straight back into the
    // pump, which returns -1 again immediately - an idle spin at 100% CPU, in the
    // one place whose entire job is to not spin. Unreachable today (null filter,
    // one thread) and live the moment the pump grows an hwnd filter or a second
    // window, which is M1's dock.
    //
    // Note WM_QUIT is also now taken from the RETURN VALUE rather than by
    // inspecting msg.message. When GetMessage returns 0 the struct is not
    // guaranteed to be meaningful, so reading it was a second, quieter version of
    // the same mistake.
    switch (::GetMessageW(&msg, nullptr, 0, 0)) {
      case -1: {
        // LastError is captured before anything else can clobber it.
        const DWORD err = ::GetLastError();
        // TraceSize is a fixed 5-argument printf, so the unused slots must be
        // passed explicitly - reading them is undefined, not zero.
        TraceSize("PUMP_ERROR GetMessageW failed GetLastError=%lu 0 0 0",
                  static_cast<UINT>(err), 0, 0, 0);
        // Leave the loop rather than spin. A pump that cannot read its queue has
        // no way to learn that WM_QUIT is coming, so idling on it forever would
        // strand the process with no way out.
        running = false;
        break;
      }
      case 0:
        running = false;
        break;
      default:
        ::TranslateMessage(&msg);
        ::DispatchMessageW(&msg);
        // BUG-01: the stale-image flags are set inside HostWndProc
        // (Window::MarkDirty) for every message that changes the image, so
        // no per-message bookkeeping is needed here - and messages
        // dispatched by OTHER pumps (modal resize, menus) are covered too.
        break;
    }
  }

  // BUG-26: unpublish before the objects die. Teardown itself sends messages
  // (WM_SIZE/WM_DESTROY), and a synchronous present against a destroyed chain is
  // exactly the crash this ordering prevents.
  g_frame.dx = nullptr;
  g_frame.win = nullptr;

  dx.DestroySwapChain();
  win.Destroy();
  return 0;
}

}  // namespace
}  // namespace fcs

// WIN32 subsystem (CMakeLists sets WIN32), so the entry point is wWinMain. The
// printf calls above reach no console in a normal run; they exist for a debugger
// and for the M0 harness, which attaches a console. The exit code is what a
// script can read.
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, LPWSTR, int show) {
  (void)show;
  return fcs::RunApp(instance);
}