-
Notifications
You must be signed in to change notification settings - Fork 126
/
Hw.cpp
1457 lines (1399 loc) · 58.4 KB
/
Hw.cpp
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
// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt
#include "Hw.h"
#if defined(_MSC_VER) && (NTDDI_VERSION >= NTDDI_WINBLUE)
#include <ShellScalingApi.h> // SetProcessDpiAwareness(), if (NTDDI_VERSION >= NTDDI_WINBLUE)
#endif
#include <commdlg.h> // GetOpenFileNameW()
#include <shellapi.h> // DragAcceptFiles()
HH_REFERENCE_LIB("comdlg32.lib"); // GetOpenFilenameW(), GetSaveFileNameW()
HH_REFERENCE_LIB("opengl32.lib");
HH_REFERENCE_LIB("shcore.lib"); // SetProcessDpiAwareness()
HH_REFERENCE_LIB("shell32.lib"); // CommandLineToArgvW()
HH_REFERENCE_LIB("winmm.lib"); // timeEndPeriod, etc.
#include <mutex> // once_flag, call_once()
#include "libHh/Args.h"
#include "libHh/Array.h"
#include "libHh/Image.h"
#include "libHh/MathOp.h"
#include "libHh/StringOp.h"
// Notes:
// https://learn.microsoft.com/en-us/windows/win32/winmsg/using-window-classes
// https://learn.microsoft.com/en-us/windows/win32/winmsg/windows
namespace hh {
// Determine if an application (in this case always a CONSOLE app) was started from a console window
// (as opposed to launched from some UI).
// https://stackoverflow.com/a/14550262
namespace details {
static int fwbp_pid;
static int fwbp_count;
static BOOL CALLBACK find_win_by_procid(HWND hwnd, LPARAM lp) {
dummy_use(lp);
int pid;
GetWindowThreadProcessId(hwnd, LPDWORD(&pid));
if (pid == fwbp_pid) fwbp_count++;
return TRUE;
}
static bool win_started_from_console_aux() {
static bool result;
static std::once_flag flag;
std::call_once(flag, [] {
// the result seems to be only correct the first time it is run
result = false;
fwbp_pid = GetCurrentProcessId();
if (fwbp_pid) {
fwbp_count = 0;
EnumWindows(WNDENUMPROC(find_win_by_procid), 0L);
result = fwbp_count == 0;
}
});
return result;
}
} // namespace details
static bool win_started_from_console() { return details::win_started_from_console_aux(); }
const HWND k_bogus_hwnd = HWND(intptr_t{-7}); // clang: reinterpret_cast<HWND>() is not allowed in a constexpr
extern HANDLE g_buf_event_data_available; // from Buffer.cpp
// Solutions in https://stackoverflow.com/questions/117792/best-method-for-storing-this-pointer-for-use-in-wndproc
// seems too complicated. We can assume a single-window model.
static Hw* g_hw;
bool Hw::init_aux(Array<string>& aargs) {
assertx(_state == EState::uninit);
_state = EState::init;
bool minimize = false;
ParseArgs args(aargs, "Hw");
args.p("-geom[etry", _user_geometry, "geom : set window geometry (e.g. 640x480)");
args.f("-icon[ic", _iconic, ": set initial window state");
args.p("-back[ground", _backcolor, "color : set backcolor (e.g. white or #5987B3)");
args.p("-fore[ground", _forecolor, "color : set forecolor (e.g. black)");
args.p("-hwdebug", _hwdebug, "val : set debug level");
args.p("-hwkey", _hwkey, "string : simulate keys");
args.p("-hwdelay", _hwdelay, "secs : delay between keys");
args.f("-bigfont", _bigfont, ": use larger font");
args.f("-minimize", minimize, ": same as -iconic");
args.f("-maximize", _maximize, ": set initial window state");
args.f("-fullscreen", _fullscreen, ": set initial window state");
args.p("-offscreen", _offscreen, "imagefilename : save image");
args.f("-nosetforeground", _nosetforeground, ": do not ask that window receive focus");
args.other_args_ok();
args.other_options_ok();
args.disallow_prefixes();
if (!args.parse_and_extract(aargs)) {
_state = EState::uninit;
return false;
}
assertx(aargs.num());
_argv0 = aargs[0];
if (minimize) _iconic = true;
g_hw = this;
//
_hInstance = GetModuleHandle(nullptr);
if (0) {
// Hopefully avoid foreground process priority boost during G3dcmp by making all windows have
// higher process priority.
// Problem 1: SetPriorityClass has parameter ABOVE_NORMAL_PRIORITY_CLASS which is not found in winbase.h
// For now, try HIGH_PRIORITY_CLASS.
// Test:
// G3dcmp -win1 "-key iij____J" hover.m{,} -key i
// That does not solve problem. We notice the following:
// If the left window is selected using either Alt-TAB or by clicking into it, it updates much faster than
// the right window.
// However, if we just left-click on the title bar, or select the left window by clicking its title bar,
// that bad behavior does not occur. Bizarre.
// The behavior is the same at both NORMAL and HIGH priority classes.
SHOWL;
assertx(SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS));
}
if (0) {
// This has not effect, for either NORMAL or HIGH priority classes.
SHOWL;
const bool disable = true;
assertx(SetProcessPriorityBoost(GetCurrentProcess(), disable));
}
//
if (1) {
#if defined(_MSC_VER) && (NTDDI_VERSION >= NTDDI_WINBLUE)
// This program is taking care of DPI issues; Windows dwm should never rescale the window contents.
// (default is PROCESS_DPI_UNAWARE; intermediate is PROCESS_SYSTEM_DPI_AWARE.)
// assertx(SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE) == S_OK);
// E_ACCESSDENIED if already set by prior call or in *.exe manifest.
void(SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE));
#elif defined(_WIN32) && (NTDDI_VERSION >= NTDDI_WINBLUE)
// For mingw, the API is not exposed in the include files, so we retrieve its address from the DLL.
enum PROCESS_DPI_AWARENESS { PROCESS_DPI_UNAWARE, PROCESS_SYSTEM_DPI_AWARE, PROCESS_PER_MONITOR_DPI_AWARE };
using voidp = void*;
using Func = HRESULT(WINAPI*)(PROCESS_DPI_AWARENESS);
HMODULE hModule = assertx(LoadLibraryA("shcore.dll"));
Func func = Func(voidp(GetProcAddress(hModule, "SetProcessDpiAwareness")));
assertx(!func(PROCESS_PER_MONITOR_DPI_AWARE));
assertx(FreeLibrary(hModule));
#else
// assertx(SetProcessDPIAware()); // this older API is available; should be in user32.lib but not found
#endif
}
set_window_title(_argv0);
set_double_buffering(true);
if (!win_started_from_console()) _extra_console_visible = true;
#if 1 // || !defined(HH_DEBUG)
// Note: if we launch from a shortcut as "minimized", the program terminates unless
// "ShowWindow(GetConsoleWindow(), SW_HIDE);" is called as done below. Unclear why.
//
// See discussion at
// https://stackoverflow.com/questions/493536/can-one-executable-be-both-a-console-and-gui-application
if (_hwdebug) SHOW(win_started_from_console(), IsDebuggerPresent());
if (!getenv_bool("SHOW_CONSOLE_WINDOW") && _extra_console_visible && !IsDebuggerPresent()) {
// https://www.cplusplus.com/forum/beginner/12001/
// Benefits:
// - no change to compilation (i.e., omit: -SUBSYSTEM:windows -ENTRY:mainCRTStartup).
// - subprocesses (RFile / WFile / my_system) still have access to console so behave properly.
// Drawbacks:
// - Flashes console window briefly before it disappears;
// To counter this, one can create a shortcut that starts minimized.
_extra_console_visible = false;
if (_hwdebug) SHOW(GetConsoleWindow());
ShowWindow(GetConsoleWindow(), SW_HIDE);
}
#endif
return true;
}
void Hw::open() {
assertx(_state == EState::init);
_state = EState::open;
// Create a window
{
if (_backcolor == "") _backcolor = _default_background;
if (_forecolor == "") _forecolor = _default_foreground;
_color_background = parse_color(_backcolor);
_color_foreground = parse_color(_forecolor);
}
Vec2<int> yxpos;
{
string s = _user_geometry;
if (s == "") s = _default_geometry;
if (sscanf(s.c_str(), "%dx%d+%d+%d", &_win_dims[1], &_win_dims[0], &yxpos[1], &yxpos[0]) == 4) {
} else if (sscanf(s.c_str(), "%dx%d", &_win_dims[1], &_win_dims[0]) == 2) {
yxpos = twice(-1);
} else {
Warning("Could not parse window geometry string");
yxpos = twice(-1);
_win_dims = twice(500);
}
}
ogl_create_window(yxpos);
if (_offscreen == "") {
for (;;)
if (loop()) break;
} else {
_exposed = true;
// Due to interaction with window events or double-buffering, first draw_it() produces only background color.
draw_it();
draw_it();
draw_it(); // necessary 2021-03-21
// glFlush();
glFinish();
// my_sleep(0.2);
Image image(_win_dims);
if (!_pbuffer) {
assertx(!_is_glx_dbuf);
uint8_t* p = static_cast<uint8_t*>(_bitmap_data);
for_int(y, image.ysize()) {
for_int(x, image.xsize()) {
for_int(z, 3) image[y][x][2 - z] = *p++; // BGR to RGB
}
while ((reinterpret_cast<uintptr_t>(p) & 3) != 0) p++;
}
} else {
Vec2<int> tdims = image.dims();
for_int(c, 2) {
while (!is_pow2(tdims[c])) tdims[c]++;
}
Image timage(tdims);
GLenum internal_format = GL_RGBA8;
glTexImage2D(GL_TEXTURE_2D, 0, internal_format, tdims[1], tdims[0], 0, GL_RGBA, GL_UNSIGNED_BYTE, timage.data());
int get_w;
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &get_w);
assertx(get_w == tdims[1]);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, _win_dims[1], _win_dims[0]);
glFinish();
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, timage.data());
image = crop(timage, twice(0), tdims - _win_dims);
}
image.reverse_y(); // because OpenGL has image origin at lower-left
image.write_file(_offscreen);
}
_state = EState::uninit;
// Cleanup/un-initialization
if (_hwdebug) SHOW("Hw::open Cleanup");
assertw(!gl_report_errors());
assertx(wglMakeCurrent(_hRenderDC, nullptr));
assertx(wglDeleteContext(_hRC));
if (_offscreen != "" && _pbuffer) {
// Possibly:
// wglReleasePbufferDCARB(hbuf, _hRenderDC);
// wglDestroyPbufferARB(hbuf);
}
if (_hRenderDC != _hDC) assertx(DeleteDC(_hRenderDC));
if (_hDC) assertx(ReleaseDC(_hwnd, _hDC));
assertx(DestroyWindow(_hwnd));
}
bool Hw::loop() {
for (;;) {
// handle all possible types of events
if (_update == EUpdate::quit) return true;
handle_events(); // WM_ MESSAGES
if (_update == EUpdate::quit) return true;
handle_keyintr(); // non-interactive key input
if (_update == EUpdate::quit) return true;
if (!got_event() && !_is_keyintr) {
// no more events, so possibly blocked
if (_update != EUpdate::nothing) break;
// We've really got nothing to do, so let's pause to avoid CPU usage when nothing is happening.
if (_hwkey != "") {
// it would be best if callbackSimuKey() would post a message so we could wait in the MsgWait.
const double delay_no_activity = 0.001; // how long to sleep (in seconds) when there's no activity
my_sleep(delay_no_activity);
continue;
}
if (_watch_fd0) {
DWORD ret =
MsgWaitForMultipleObjectsEx(1, &g_buf_event_data_available, INFINITE, QS_ALLEVENTS, MWMO_INPUTAVAILABLE);
assertx(ret != WAIT_FAILED);
if (ret == WAIT_OBJECT_0) input_received();
} else {
assertx(WaitMessage());
}
}
}
// No more events but redraw has been requested
// *Might* need to check if '_exposed' is true, and only do draw_it() if is true (and else, do a my_sleep() here).
draw_it();
// This improves load-balancing a bit in G3dcmp (see also discussion on SetPriorityClass)
// and doesn't seem to hurt performance too much for single window.
if (1) SleepEx(0, TRUE); // 0 milliseconds; relinquish time slice
return false;
}
void Hw::handle_events() {
while (got_event() && _update != EUpdate::quit) {
handle_event();
}
}
void Hw::handle_event() {
_gotevent = false;
TranslateMessage(&_msg);
DispatchMessage(&_msg);
// Won't return from here until the window proc finishes processing message -- so ok.
}
// This wrapper to avoid the problem where can't access 'Hw' class members from a non-class function -- yuck!
LRESULT CALLBACK wndProc_wrapper(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) {
if (0) SHOW(hwnd, iMsg, wParam, lParam);
if (g_hw->_hwnd == k_bogus_hwnd) g_hw->_hwnd = hwnd;
assertx(hwnd == g_hw->_hwnd);
return g_hw->wndProc(iMsg, wParam, lParam);
}
// Windows 7 Touch Input:
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd371581%28v=vs.85%29.aspx RegisterTouchWindow
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd317341%28v=vs.85%29.aspx WM_TOUCH message
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd744775%28v=vs.85%29.aspx Detecting and Tracking
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd317334%28v=vs.85%29.aspx TOUCHINPUT structure
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd562199%28v=vs.85%29.aspx samples
// https://msdn.microsoft.com/en-us/magazine/ee336016.aspx overview
LRESULT Hw::wndProc(UINT iMsg, WPARAM wParam, LPARAM lParam) {
if (_hwdebug) SHOW("wndProc", iMsg);
static PAINTSTRUCT ps; // always zero
switch (iMsg) {
case WM_ERASEBKGND:
// https://www.opengl.org/pipeline/article/vol003_7/
// Handle the application window's WM_ERASEBKGND by returning non-zero in the message handler
// (this will avoid GDI clearing the OpenGL windows background).
return 1; // introduced 2014-12-03
case WM_CREATE:
// On window creation, send a WM_SHOWWINDOW msg,
// since that msg doesn't get sent when ShowWindow() is called, in certain situations.
if (_hwdebug) SHOW("WM_CREATE");
assertx(PostMessage(_hwnd, WM_SHOWWINDOW, TRUE, 0));
DragAcceptFiles(_hwnd, TRUE);
return 0;
case WM_SHOWWINDOW: {
BOOL fShow = BOOL(wParam);
if (_hwdebug) SHOW("WM_SHOWWINDOW", fShow);
if (fShow) {
// Window is about to be SHOWN (like X-windows MapNotify)
if (!_exposed) {
_exposed = true;
if (_hwdebug) SHOW("window now exposed");
if (_hwkey != "") start_hwkey();
}
} else {
// Window is about to be HIDDEN (like X-windows UnmapNotify)
// Possibly we could somehow force the redraws to stop.
}
return 0;
}
case WM_PAINT: {
// (Part of) window requires repaint (like X-windows Expose)
if (_hwdebug) SHOW("WM_PAINT");
if (!_exposed) assertnever("");
// Remove from message queue all other repaint messages.
// Implicitly "validates" whole window to remove WM_PAINT msgs.
// Win32 note: only 1 WM_PAINT message will be in queue at a time.
// To support several OpenGL contexts, see https://stackoverflow.com/questions/2842319/swapbuffers-causes-redraw
assertx(BeginPaint(_hwnd, &ps));
assertx(EndPaint(_hwnd, &ps));
// Redraw the screen
redraw_now();
return 0;
}
case WM_SIZE: {
// Window size has changed (like X-windows ConfigureNotify).
// Might want to do some tricks (for efficiency only) to see if we _really_ need to resize the window, like:
// if (wParam == SIZE_MAXHIDE || wParam == SIZE_MAXHIDE)...
// Update value of '_exposed' flag
if (wParam == SIZE_MAXIMIZED || wParam == SIZE_RESTORED) {
_exposed = true;
} else if (wParam == SIZE_MINIMIZED) {
_exposed = false;
}
// This is size of _client_ area. Do we need to subtract window border, scrollbars, etc? No.
_win_dims = convert<int>(V(HIWORD(lParam), LOWORD(lParam))); // new (height, width) of client area
if (_hwdebug) SHOW("WM_SIZE", _win_dims);
if (!_exposed) return 0;
soft_discard();
glViewport(0, 0, _win_dims[1], _win_dims[0]);
if (1) {
// Remove from message queue all other repaint messages.
// Implicitly "validates" whole window to remove WM_PAINT msgs.
// Win32 note: only 1 WM_PAINT message will be in queue at a time.
assertx(BeginPaint(_hwnd, &ps));
assertx(EndPaint(_hwnd, &ps));
}
// The problem in windows is that there is no way to avoid seeing a flash of background color right
// after window resizing (most noticeable in Remote Desktop). Good discussion at
// https://stackoverflow.com/questions/9786218/drawing-in-window-while-resizing-leaves-unpainted-border
if (0) {
// This clears the new window completely, which makes the problem somewhat worse.
{
Vector4 v(_color_background);
glClearColor(v[0], v[1], v[2], 1.f);
}
glDrawBuffer(GL_FRONT_AND_BACK);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (_is_glx_dbuf) glDrawBuffer(GL_BACK);
set_color_to_foreground();
}
if (0 && gl_extensions_string() != "") { // only if OpenGL is already initialized.
// This draws directly to the front buffer. However, the window is already painted white.
glDrawBuffer(GL_FRONT);
bool bu_is_glx_dbuf = _is_glx_dbuf;
_is_glx_dbuf = false;
draw_it();
_is_glx_dbuf = bu_is_glx_dbuf;
} else {
redraw_now(); // redraw it later; works just as well
}
return 0;
}
case WM_MOVE: {
_win_pos = convert<int>(V(HIWORD(lParam), LOWORD(lParam))); // y, x
if (_hwdebug) SHOW("WM_MOVE", _win_pos);
return 0;
}
case WM_KEYDOWN:
case WM_CHAR:
if (_hwdebug) SHOW("WM_KEYDOWN/WM_CHAR", wParam);
handle_key(iMsg, wParam);
return 0;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_XBUTTONDOWN:
case WM_XBUTTONUP: {
// cursor relative to upper-left of client area
const Vec2<int> yx = convert<int>(V(HIWORD(lParam), LOWORD(lParam)));
const bool shift = (wParam & MK_SHIFT) != 0;
dummy_use(shift);
int butnum;
switch (iMsg) {
case WM_LBUTTONDOWN:
case WM_LBUTTONUP: butnum = 1; break;
case WM_MBUTTONDOWN:
case WM_MBUTTONUP: butnum = 2; break;
case WM_RBUTTONDOWN:
case WM_RBUTTONUP: butnum = 3; break;
case WM_XBUTTONDOWN:
case WM_XBUTTONUP: butnum = 3 + HIWORD(wParam); break; // thus 4 or 5
default: assertnever("");
}
bool pressed;
switch (iMsg) {
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_XBUTTONDOWN: pressed = true; break;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
case WM_XBUTTONUP: pressed = false; break;
default: assertnever("");
}
if (_hwdebug) SHOW("WM_BUTTON", butnum, pressed, yx);
if (pressed)
SetCapture(_hwnd);
else
assertw(ReleaseCapture());
button_press(butnum, pressed, yx);
return 0;
}
case WM_MOUSEWHEEL: {
bool shift = (wParam & MK_SHIFT) != 0;
dummy_use(shift);
int wheel_motion = HIWORD(wParam);
if (wheel_motion >= (1 << 15)) wheel_motion = wheel_motion - (1 << 16);
if (_hwdebug) SHOW("WM_MOUSEWHEEL", wheel_motion);
wheel_turn(wheel_motion / 120.f); // wheel_motion == 120 for one click turn
return 0;
}
case WM_DROPFILES: {
// See https://www.codeproject.com/Articles/840/How-to-Implement-Drag-and-Drop-Between-Your-Progra
Array<string> filenames;
{
HDROP hdrop = HDROP(wParam);
// POINT pt; DragQueryPoint(hdrop, &pt); SHOW(pt.x, pt.y);
int cFiles = int(DragQueryFileW(hdrop, unsigned(-1), nullptr, 0));
filenames.init(cFiles);
for_int(i, cFiles) {
Vec<wchar_t, 2000> filename;
assertx(DragQueryFileW(hdrop, i, filename.data(), filename.num() - 1));
filenames[i] = get_canonical_path(utf8_from_utf16(filename.data()));
// TextOutW(hdc, pt.x, pt.y, filename.data(), lstrlenW(filename)); pt.y += 20;
}
DragFinish(hdrop);
}
if (_hwdebug) SHOW("WM_DROPFILES", filenames);
drag_and_drop(filenames);
grab_focus();
return 0;
}
case WM_CLOSE:
if (_hwdebug) SHOW("WM_CLOSE");
quit();
return 0;
case WM_DESTROY:
if (_hwdebug) SHOW("WM_DESTROY");
DragAcceptFiles(_hwnd, FALSE);
break;
case WM_GETMINMAXINFO: {
// Try to override the smallest width to < 104 interior pixels.
// (GetSystemMetrics(SM_CXMIN)=112 - 2 * 4 == 104).
// The fix below seems to allow small geometry from command-line,
// but not when resizing window (min width 100 on Windows 7). This seems OK.
MINMAXINFO* p = reinterpret_cast<MINMAXINFO*>(lParam);
p->ptMinTrackSize.x = 20; // was previously 50
p->ptMinTrackSize.y = 20; // no effect
if (_hwdebug) SHOW("WM_GETMINMAXINFO");
return 0;
}
// case WM_DPICHANGED:
// do nothing currently
// break;
default:
void();
// unrecognized message, pass through
} // end switch
// If got here, didn't handle the message, so pass on to default handler.
return DefWindowProcW(_hwnd, iMsg, wParam, lParam);
}
bool Hw::got_event() {
// If there's a pending event, retrieve it and set flag
// (_unless_ we already have an event; in that case, don't fetch another one).
if (!_gotevent && PeekMessage(&_msg, nullptr, 0, 0, PM_REMOVE)) _gotevent = true;
return _gotevent;
}
bool Hw::suggests_stop() {
assertx(_state == EState::open);
if (got_event() && _update != EUpdate::quit) handle_events();
if (_is_keyintr) handle_keyintr();
return _update == EUpdate::quit || _update == EUpdate::redrawnow;
}
// Warning: Can't call any system-defined functions inside a multimedia-timer callback,
// except for PostMessage, OutputDebugString, certain 'timeXXXX' functions, and certain 'midiOutXXXX' functions.
// (See 'TimeProc' documentation for full details.)
// Only called by start_hwkey()
void CALLBACK callbackSimuKey(UINT id, UINT msg, DWORD_PTR userData, DWORD_PTR dw1, DWORD_PTR dw2) {
dummy_use(id, msg, dw1, dw2);
// Set flag, meaning that a "new" keypress (simulated) has occurred.
// (Basically just "opens the gates", so msg loop will process next simulated key now.
// Gives periodic/delayed keypresses this way, instead of all being processed at once -- more like real input).
reinterpret_cast<Hw*>(userData)->set_keyintr();
}
void Hw::start_hwkey() {
// *** TURN-ON timer (periodic) ***
UINT timer_delay; // How long b/w timer events (mSec)
TIMECAPS time_caps; // timer capabilities
// Check what resolution, etc the timer supports
assertx(timeGetDevCaps(&time_caps, sizeof(time_caps)) == TIMERR_NOERROR);
// Clamp desired timer resolution to allowed range
_sk_timerResolution = clamp(_sk_timerResolution, time_caps.wPeriodMin, time_caps.wPeriodMax);
// Set our req'd timer resolution
assertx(timeBeginPeriod(_sk_timerResolution) == TIMERR_NOERROR);
// Start/create the timer
_hwdelay = max(_hwdelay, .01f);
timer_delay = int(_hwdelay * 1000.f + .5f);
_sk_timerID = timeSetEvent(timer_delay, _sk_timerResolution, callbackSimuKey, reinterpret_cast<DWORD_PTR>(this),
TIME_PERIODIC);
assertx(_sk_timerID);
}
void Hw::end_hwkey() {
// *** TURN-OFF timer (periodic) ***
if (_sk_timerID) {
assertx(timeKillEvent(_sk_timerID) == TIMERR_NOERROR);
_sk_timerID = 0;
}
if (_sk_timerResolution) {
assertx(timeEndPeriod(_sk_timerResolution) == TIMERR_NOERROR);
_sk_timerResolution = 0;
}
}
void Hw::handle_key(int why_called, WPARAM key_data) {
string s;
// SHOW(why_called, why_called == WM_KEYDOWN, int(key_data));
if (why_called == WM_KEYDOWN) {
int virt_key = int(key_data);
if (virt_key >= VK_F1 && virt_key <= VK_F12) {
s = sform("<f%d>", virt_key - VK_F1 + 1);
} else {
switch (virt_key) {
case VK_LEFT: s = "<left>"; break;
case VK_RIGHT: s = "<right>"; break;
case VK_UP: s = "<up>"; break;
case VK_DOWN: s = "<down>"; break;
case VK_HOME: s = "<home>"; break;
case VK_END: s = "<end>"; break;
case VK_PRIOR: s = "<prior>"; break;
case VK_NEXT: s = "<next>"; break;
case VK_INSERT: s = "<insert>"; break;
case VK_DELETE: s = "<delete>"; break;
default:
if (get_key_modifier(EModifier::control) && virt_key >= '0' && virt_key <= '9') {
// control-numbers (C-0 .. C-9) do not produce any subsequent WM_CHAR message, so handle now.
char ch = assert_narrow_cast<char>(virt_key);
s = ch;
} else {
return; // we don't care about this key, or it will be handled later (by WM_CHAR)
}
}
}
} else {
// we assume we're handling a WM_CHAR message
char ch = assert_narrow_cast<char>(key_data);
if (ch == 127) ch = '\b'; // C-<backspace> should just be <backspace> for now
s = ch;
}
assertx(s != "");
if (1) {
if (_query) {
query_keypress(s);
} else if (key_press(s)) {
// client has handled key press
} else if (s == "\033") { // <esc> key ( == uchar{27})
quit();
} else if (s == "~") { // toggle console window
if (!win_started_from_console()) {
_extra_console_visible = !_extra_console_visible;
const int show_flag = 0 ? SW_SHOWNORMAL : SW_SHOWNOACTIVATE;
ShowWindow(GetConsoleWindow(), _extra_console_visible ? show_flag : SW_HIDE);
}
} else {
beep();
}
}
}
void Hw::draw_it() {
_update = EUpdate::nothing;
if (!_exposed) return;
if (_hwdebug) SHOW("draw_it", _win_dims);
_async = true;
if (_query) {
clear_window();
draw_text(_query_yx, _query_prompt + _query_buffer + "_");
} else {
// 2014-12-13
glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // for non-premultiplied alpha
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // 2017-02-23; source is assumed to have premultiplied alpha
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // glLoadMatrixf(to_Matrix(Frame::identity()).data());
if (0) {
glOrtho(-.5, _win_dims[1] - .5, _win_dims[0] - .5, -.5, -1., 1.); // multiplies GL_PROJECTION; reverse y
} else {
// 2015-01-08 pixels are now centered at half-integers
glOrtho(0., _win_dims[1] - 0., _win_dims[0] - 0., 0., -1., 1.); // multiplies GL_PROJECTION; reverse y
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
draw_window(_win_dims);
}
_async = false;
if (_update == EUpdate::quit) return;
if (_update == EUpdate::nothing || _update == EUpdate::redrawlater) {
soft_flush();
if (_is_glx_dbuf) {
// glFlush();
// assertx(SwapBuffers(_hDC));
assertx(SwapBuffers(_hRenderDC));
} else {
glFlush();
}
} else {
soft_discard();
}
}
void Hw::clear_window() {
soft_discard();
clear_window_ogl();
}
void Hw::beep() {
assertx(_state != EState::uninit);
Beep(600, 100);
}
void Hw::set_double_buffering(bool newstate) {
if (_offscreen != "") newstate = true; // else multisampling is not supported (bizarre)
if (!assertw(_state == EState::init)) return;
_is_glx_dbuf = newstate;
// if !_is_glx_dbuf, do not call glXSwapBuffers(), glDrawBuffer(GL_BACK)
if (_hwdebug) SHOW(_is_glx_dbuf);
}
bool Hw::get_pointer(Vec2<int>& yx) {
assertx(_state == EState::open);
POINT pt_screen, pt_client;
// Get position of mouse cursor (relative to screen, not window).
if (!GetCursorPos(&pt_screen)) return false;
// Convert coords so that they're relative to window's client area.
pt_client = pt_screen;
assertx(ScreenToClient(_hwnd, &pt_client));
// Assign values to the [OUT] arguments.
yx = convert<int>(V(pt_client.y, pt_client.x));
// Return True if mouse pointer is inside window, or False if isn't
// (to be consistent with X-windows -- recall that X-windows only activates window if pointer is on it).
RECT window_rect;
assertx(GetWindowRect(_hwnd, &window_rect));
// return PtInRect(&window_rect, pt_screen);
return true;
}
bool Hw::get_key_modifier(EModifier modifier) {
int virt_key;
switch (modifier) {
case EModifier::shift: virt_key = VK_SHIFT; break;
case EModifier::control: virt_key = VK_CONTROL; break;
case EModifier::alt: virt_key = VK_MENU; break;
default: assertnever("");
}
short v = GetKeyState(virt_key);
return !!(v & (1 << 15)); // high-order bit indicates key down, low-order bit is odd "toggle" state for caps_lock
}
void Hw::set_color_to_foreground() {
assertx(_state == EState::open);
glColor3ubv(_color_foreground.data());
}
void Hw::set_color(const Pixel& pix) {
assertx(_state == EState::open);
glColor4ubv(pix.data());
}
void Hw::draw_text_internal(const Vec2<int>& yx, const string& s) {
assertx(_state == EState::open);
draw_text_ogl(yx, s);
}
void Hw::fill_polygon(CArrayView<Vec2<float>> points) {
assertx(_state == EState::open);
fill_polygon_ogl(points);
}
void Hw::set_window_title(string ps) {
assertx(_state == EState::init || _state == EState::open);
_window_title = std::move(ps);
if (_state == EState::open) {
ASSERTX(IsWindowUnicode(_hwnd));
assertx(SetWindowTextW(_hwnd, utf16_from_utf8(_window_title).c_str()));
// Note that this gets converted to a WM_SETTEXT message;
// see https://stackoverflow.com/questions/9410681/setwindowtextw-in-an-ansi-project
}
}
Vec2<int> Hw::get_max_window_dims() {
RECT wa_rect;
assertx(SystemParametersInfo(SPI_GETWORKAREA, 0, &wa_rect, 0));
// The above does subtract the taskbar area.
// SHOW(wa_rect.top, wa_rect.bottom, wa_rect.left, wa_rect.right);
//
// Use Win->Up_arrow to maximize window height, then use '@' key to compare:
// get_max_window_dims() = [1573, 2464]
// g_win_dims=[1568, 2360]
Vec2<int> top = V(16, 0); // Windows 7
top = V(19, 0); // Windows 10
top = V(24, 0); // Windows 10 update1511
auto window_borders =
top + V(2 * (3 + 1 + 0), 2 * (3 + 1 + 0)); // iBorderWidth default 1, +iPaddedBorderWidth (def 4, set 0)
return V(int(wa_rect.bottom - wa_rect.top), int(wa_rect.right - wa_rect.left)) - window_borders;
}
void Hw::resize_window(const Vec2<int>& yx) {
assertx(_state == EState::open);
// https://stackoverflow.com/questions/5609486/in-c-windows-api-resize-window-during-runtime
// https://stackoverflow.com/questions/692742
RECT wa_rect;
assertx(SystemParametersInfo(SPI_GETWORKAREA, 0, &wa_rect, 0));
RECT rect = {0, 0, yx[1], yx[0]}; // left, top, right, bottom
assertx(AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0));
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
// or consider MoveWindow()
// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowpos
int new_top = 0, new_left = 0; // unused unless force_move
bool force_move = false;
if (_win_pos[0] + height > wa_rect.bottom || _win_pos[1] + width > wa_rect.right) {
new_top = wa_rect.top;
new_left = wa_rect.left;
force_move = true;
}
// SHOW(new_top, new_left);
if (_hwdebug) SHOW("resize", yx, width, height);
// SWP_NOCOPYBITS? SWP_DEFERERASE? SWP_SHOWWINDOW? SWP_NOREDRAW? remove SWP_NOACTIVATE?
assertx(SetWindowPos(_hwnd, nullptr, new_left, new_top, width, height,
(force_move ? 0 : SWP_NOMOVE) | SWP_NOZORDER | SWP_NOACTIVATE));
// Note: Although the initially created window can have arbitrary tiny size,
// using SetWindwPos() to resize the window forces a minimum width on the window
// (approximately 102 pixels) (for the buttons above it).
}
bool Hw::is_fullscreen() {
DWORD style = GetWindowLong(_hwnd, GWL_STYLE);
return !(style & WS_OVERLAPPEDWINDOW);
}
void Hw::make_fullscreen(bool b) {
if (b == is_fullscreen()) return;
static WINDOWPLACEMENT g_wp_prev;
g_wp_prev.length = sizeof(g_wp_prev);
DWORD style = GetWindowLong(_hwnd, GWL_STYLE);
if (b) { // go full screen
MONITORINFO mi;
mi.cbSize = sizeof(mi);
if (GetWindowPlacement(_hwnd, &g_wp_prev) &&
GetMonitorInfo(MonitorFromWindow(_hwnd, MONITOR_DEFAULTTOPRIMARY), &mi)) {
SetWindowLong(_hwnd, GWL_STYLE, style & ~WS_OVERLAPPEDWINDOW);
SetWindowPos(_hwnd, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top, SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
}
} else { // come back from full screen
SetWindowLong(_hwnd, GWL_STYLE, style | WS_OVERLAPPEDWINDOW);
SetWindowPlacement(_hwnd, &g_wp_prev);
SetWindowPos(_hwnd, nullptr, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
}
}
void Hw::grab_focus() {
// assertx(SetFocus(_hwnd));
// assertw(SetActiveWindow(_hwnd));
assertw(SetForegroundWindow(_hwnd));
}
void Hw::flush_seg() { flush_seg_ogl(); }
void Hw::flush_point() { flush_point_ogl(); }
void Hw::hard_flush() {
assertx(_state == EState::open);
soft_flush();
glFinish();
}
#define VIDEO_EXTS \
L"*.mpg;*.mpeg;*.mpe;*.mpv;*.mp2;*.mpeg2;*.mp4;*.mpeg4;*.mov;*.avi;" \
L"*.wmv;*.flv;*.m2v;*.m4v;*.webm;*.ogv;*.3gp;*.mts;*.gif"
#define IMAGE_EXTS \
L"*.jpg;*.jpeg;*.png;*.bmp;*.rgb;*.ppm;*.pgm;*.pbm;*.tif;*.tiff;" \
L"*.jxr;*.hdp;*.wdp;*.wmp;*.webp;*.bpg;*.jp2"
Array<string> Hw::query_open_filenames(const string& hint_filename) {
// http://www.winprog.org/tutorial/app_two.html
std::wstring whint_filename = utf16_from_utf8(hint_filename);
std::wstring whint_directory = utf16_from_utf8(replace_all(get_path_head(hint_filename), "/", "\\"));
std::wstring whint_tail = utf16_from_utf8(get_path_tail(hint_filename));
Array<wchar_t> buffer(64000);
assertx(whint_tail.size() < buffer.size());
wcsncpy(buffer.data(), whint_tail.c_str(), buffer.size());
OPENFILENAMEW ofn = {};
{
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = _hwnd;
ofn.lpstrFilter = (L"Video and Images\0" VIDEO_EXTS L";" IMAGE_EXTS L"\0"
L"Video Files\0" VIDEO_EXTS L"\0"
L"Image Files\0" IMAGE_EXTS L"\0"
L"All Files (*.*)\0*.*\0");
ofn.lpstrFile = buffer.data();
ofn.nMaxFile = buffer.num();
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT;
// ofn.lpstrDefExt = L"txt";
ofn.lpstrTitle = L"Open File";
ofn.lpstrInitialDir = whint_directory.c_str();
if (0) SHOW(utf8_from_utf16(ofn.lpstrInitialDir), utf8_from_utf16(ofn.lpstrFile));
}
if (!GetOpenFileNameW(&ofn)) return {};
// If the OFN_ALLOWMULTISELECT flag is set and the user selects multiple files, the buffer contains
// the current directory followed by the file names of the selected files, separated by null characters.
// If the user selects only one file, the lpstrFile string does not have a separator between the path and
// file name.
Array<string> filenames;
if (ofn.nFileOffset == 0 || buffer[ofn.nFileOffset - 1]) { // single file
filenames.reserve(1);
filenames.push(get_canonical_path(utf8_from_utf16(buffer.data())));
} else { // multiple files
string directory = get_canonical_path(utf8_from_utf16(buffer.data()));
for (wchar_t* p = &buffer[int(directory.size() + 1)]; *p;) {
if (0) SHOW(directory, utf8_from_utf16(p));
filenames.push(directory + "/" + utf8_from_utf16(p));
p += wcslen(p) + 1;
}
}
if (0) SHOW(filenames);
return filenames;
}
string Hw::query_save_filename(const string& hint_filename, bool force) {
// https://learn.microsoft.com/en-us/windows/win32/api/commdlg/nf-commdlg-getsavefilenamea
std::wstring whint_filename = utf16_from_utf8(hint_filename);
std::wstring whint_directory = utf16_from_utf8(replace_all(get_path_head(hint_filename), "/", "\\"));
std::wstring whint_tail = utf16_from_utf8(get_path_tail(hint_filename));
std::wstring whint_extension = utf16_from_utf8(get_path_extension(hint_filename));
Array<wchar_t> buffer(64000);
assertx(whint_tail.size() < buffer.size());
wcsncpy(buffer.data(), whint_tail.c_str(), buffer.size());
OPENFILENAMEW ofn = {};
{
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = _hwnd;
ofn.lpstrFilter = (L"All Files (*.*)\0*.*\0");
ofn.lpstrFile = buffer.data();
ofn.nMaxFile = buffer.num();
ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | (force ? 0 : OFN_OVERWRITEPROMPT);
ofn.lpstrDefExt = whint_extension.c_str();
ofn.lpstrTitle = L"Save File";
ofn.lpstrInitialDir = whint_directory.c_str();
}
if (!GetSaveFileNameW(&ofn)) return "";
assertx(ofn.nFileOffset == 0 || buffer[ofn.nFileOffset - 1]); // single file
return get_canonical_path(utf8_from_utf16(buffer.data()));
}
void Hw::begin_draw_visible() {
assertx(_state == EState::open);
soft_flush();
glDrawBuffer(GL_FRONT);
}
void Hw::end_draw_visible() {
assertx(_state == EState::open);
soft_flush();
if (_is_glx_dbuf) glDrawBuffer(GL_BACK);
}
void Hw::wake_up() {
WPARAM wParam = 0;
LPARAM lParam = 0;
if (_exposed) assertw(PostMessage(_hwnd, WM_USER + 0, wParam, lParam));
}
void Hw::set_pixel_format(bool fake_first) {
// https://www.opengl.org/pipeline/article/vol003_7/
// Windows Vista introduces the new pixelformat flag PFD_SUPPORT_COMPOSITION (defined in the Driver
// Development Kit's wingdi.h as 0x00008000).
// Creating an OpenGL context for a pixelformat without this flag will disable composition for the duration
// of the process which created the context. The flag is mutually exclusive with PFD_SUPPORT_GDI.
#if !defined(PFD_SUPPORT_COMPOSITION) // e.g. clang
const unsigned PFD_SUPPORT_COMPOSITION = 0x00008000;
#endif
PIXELFORMATDESCRIPTOR pfd;
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_SUPPORT_OPENGL;
if (fake_first || _offscreen == "") {
pfd.dwFlags |= PFD_DRAW_TO_WINDOW;
if (_is_glx_dbuf) pfd.dwFlags |= PFD_DOUBLEBUFFER;
pfd.dwFlags |= PFD_SUPPORT_COMPOSITION;
} else if (!_pbuffer) {
pfd.dwFlags |= PFD_DRAW_TO_BITMAP;
} else {
// WGL_DRAW_TO_PBUFFER not recognized by ChoosePixelFormat.
// We will use wglChoosePixelFormatARB() instead later.
}
pfd.iPixelType = PFD_TYPE_RGBA; // COLORINDEX or RGBA
pfd.cColorBits = BYTE(_scr_bpp); // Bits per pixel used for color
pfd.cAlphaBits = 0; // >= 0
pfd.cAccumBits = 0; // >= 0
pfd.cDepthBits = BYTE(_scr_zbufbits); // >= 0
pfd.cStencilBits = BYTE(_scr_stencilbits); // >= 0
pfd.cAuxBuffers = 0; // >= 0
pfd.iLayerType = PFD_MAIN_PLANE; // MAIN or OVERLAY or UNDERLAY
if (_hwdebug) {
SHOW("Requested:");
const PIXELFORMATDESCRIPTOR& p = pfd;
SHOW(p.dwFlags, unsigned(p.cColorBits), unsigned(p.cAlphaBits), unsigned(p.cAccumBits));
SHOW(unsigned(p.cDepthBits), unsigned(p.cStencilBits), unsigned(p.cAuxBuffers), unsigned(p.iLayerType));
}
int iPixelFormat = assertx(ChoosePixelFormat(_hRenderDC, &pfd));
// note: pfd is not modified by ChoosePixelFormat.
if (1) {
PIXELFORMATDESCRIPTOR pfd2;
assertx(DescribePixelFormat(_hRenderDC, iPixelFormat, sizeof(pfd2), &pfd2));
if (_hwdebug) {
SHOW("Obtained:");
const PIXELFORMATDESCRIPTOR& p = pfd2;
SHOW(p.dwFlags, unsigned(p.cColorBits), unsigned(p.cAlphaBits), unsigned(p.cAccumBits));
SHOW(unsigned(p.cDepthBits), unsigned(p.cStencilBits), unsigned(p.cAuxBuffers), unsigned(p.iLayerType));
}
assertx(PFD_SWAP_COPY == 1024); // dwFlags == 1061 == 1024 + 32 + 4 + 1
if (!fake_first) {
unsigned desired = pfd.dwFlags & ~PFD_SUPPORT_COMPOSITION;
assertw((pfd2.dwFlags & desired) == desired);
assertw(pfd2.iPixelType == pfd.iPixelType);
assertw(pfd2.cColorBits >= pfd.cColorBits);
assertw(pfd2.cAlphaBits >= pfd.cAlphaBits);
assertw(pfd2.cAccumBits >= pfd.cAccumBits);
assertw(pfd2.cDepthBits >= pfd.cDepthBits);
assertw(pfd2.cStencilBits >= pfd.cStencilBits);
assertw(pfd2.cAuxBuffers >= pfd.cAuxBuffers);
assertw(pfd2.iLayerType == pfd.iLayerType);