-
Notifications
You must be signed in to change notification settings - Fork 123
/
winapp.d
1883 lines (1692 loc) · 68.4 KB
/
winapp.d
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
// Written in the D programming language.
/**
This module contains implementation of Win32 platform support
Provides Win32Window and Win32Platform classes.
Usually you don't need to use this module directly.
Synopsis:
----
import dlangui.platforms.windows.winapp;
----
Copyright: Vadim Lopatin, 2014
License: Boost License 1.0
Authors: Vadim Lopatin, coolreader.org@gmail.com
*/
module dlangui.platforms.windows.winapp;
public import dlangui.core.config;
static if (BACKEND_WIN32):
import core.runtime;
import core.sys.windows.windows;
import std.string;
import std.utf;
import std.stdio;
import std.algorithm;
import std.file;
import dlangui.platforms.common.platform;
import dlangui.platforms.windows.win32fonts;
import dlangui.platforms.windows.win32drawbuf;
import dlangui.widgets.styles;
import dlangui.widgets.widget;
import dlangui.graphics.drawbuf;
import dlangui.graphics.images;
import dlangui.graphics.fonts;
import dlangui.core.logger;
import dlangui.core.files;
static if (ENABLE_OPENGL) {
import dlangui.graphics.glsupport;
}
// specify debug=DebugMouseEvents for logging mouse handling
// specify debug=DebugRedraw for logging drawing and layouts handling
// specify debug=DebugKeys for logging of key events
pragma(lib, "gdi32.lib");
pragma(lib, "user32.lib");
/// this function should be defined in user application!
extern (C) int UIAppMain(string[] args);
immutable WIN_CLASS_NAME = "DLANGUI_APP";
/* This is a pretty dirty hack to get multisampling to work */
private __gshared bool isInitialized = false;
__gshared HINSTANCE _hInstance;
__gshared int _cmdShow;
// TODO: Encapsulate this better
private string GetErrorMessage(DWORD error) @trusted
{
char[] err = new char[256];
err[0 .. $] = 0;
int chars = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error,
MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), err.ptr, 255, NULL);
return cast(string) err[0 .. chars];
}
static if (ENABLE_OPENGL) {
// WGL stuff
// WGL_ARB_pixel_format
enum WGL_DRAW_TO_WINDOW_ARB = 0x2001;
enum WGL_DRAW_TO_BITMAP_ARB = 0x2002;
enum WGL_ACCELERATION_ARB = 0x2003;
enum WGL_SUPPORT_GDI_ARB = 0x200F;
enum WGL_SUPPORT_OPENGL_ARB = 0x2010;
enum WGL_DOUBLE_BUFFER_ARB = 0x2011;
enum WGL_STEREO_ARB = 0x2012;
enum WGL_PIXEL_TYPE_ARB = 0x2013;
enum WGL_COLOR_BITS_ARB = 0x2014;
enum WGL_DEPTH_BITS_ARB = 0x2022;
enum WGL_STENCIL_BITS_ARB = 0x2023;
enum WGL_NO_ACCELERATION_ARB = 0x2025;
enum WGL_GENERIC_ACCELERATION_ARB = 0x2026;
enum WGL_FULL_ACCELERATION_ARB = 0x2027;
enum WGL_TYPE_RGBA_ARB = 0x202B;
enum WGL_TYPE_COLORINDEX_ARB = 0x202C;
// WGL_ARB_create_context_profile
enum WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
enum WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092;
enum WGL_CONTEXT_FLAGS_ARB = 0x2094;
enum WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126;
// WGL_CONTEXT_FLAGS bits
enum WGL_CONTEXT_DEBUG_BIT_ARB = 0x0001;
enum WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x0002;
// WGL_CONTEXT_PROFILE_MASK_ARB bits
enum WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001;
enum WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002;
enum GL_NUM_EXTENSIONS = 0x821D;
enum WGL_ALPHA_BITS_ARB = 0x201B;
enum WGL_SAMPLE_BUFFERS_ARB = 0x2041;
enum WGL_SAMPLES_ARB = 0x2042;
bool setupPixelFormat(HDC hDC, int multisamples = 0)
{
PIXELFORMATDESCRIPTOR pfd = {
PIXELFORMATDESCRIPTOR.sizeof, /* size */
1, /* version */
PFD_SUPPORT_OPENGL |
PFD_DRAW_TO_WINDOW |
PFD_DOUBLEBUFFER, /* support double-buffering */
PFD_TYPE_RGBA, /* color type */
24, /* prefered color depth */
0, 0, 0, 0, 0, 0, /* color bits (ignored) */
0, /* no alpha buffer */
0, /* alpha bits (ignored) */
0, /* no accumulation buffer */
0, 0, 0, 0, /* accum bits (ignored) */
16, /* depth buffer */
0, /* no stencil buffer */
0, /* no auxiliary buffers */
0, /* main layer PFD_MAIN_PLANE */
0, /* reserved */
0, 0, 0, /* no layer, visible, damage masks */
};
int pixelFormat;
pixelFormat = multisamples > 0 ? sharedGLContext.multisampleFormat(hDC, multisamples) : ChoosePixelFormat(hDC, &pfd);
if (pixelFormat == 0) {
Log.e("ChoosePixelFormat failed.");
return false;
}
if (SetPixelFormat(hDC, pixelFormat, &pfd) != TRUE) {
Log.e("SetPixelFormat failed.");
return false;
}
return true;
}
HPALETTE setupPalette(HDC hDC)
{
import core.stdc.stdlib;
HPALETTE hPalette = NULL;
int pixelFormat = GetPixelFormat(hDC);
PIXELFORMATDESCRIPTOR pfd;
LOGPALETTE* pPal;
int paletteSize;
DescribePixelFormat(hDC, pixelFormat, PIXELFORMATDESCRIPTOR.sizeof, &pfd);
if (pfd.dwFlags & PFD_NEED_PALETTE) {
paletteSize = 1 << pfd.cColorBits;
} else {
return null;
}
pPal = cast(LOGPALETTE*)
malloc(LOGPALETTE.sizeof + paletteSize * PALETTEENTRY.sizeof);
pPal.palVersion = 0x300;
pPal.palNumEntries = cast(ushort)paletteSize;
/* build a simple RGB color palette */
{
int redMask = (1 << pfd.cRedBits) - 1;
int greenMask = (1 << pfd.cGreenBits) - 1;
int blueMask = (1 << pfd.cBlueBits) - 1;
int i;
for (i=0; i<paletteSize; ++i) {
pPal.palPalEntry[i].peRed = cast(ubyte)(
(((i >> pfd.cRedShift) & redMask) * 255) / redMask);
pPal.palPalEntry[i].peGreen = cast(ubyte)(
(((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask);
pPal.palPalEntry[i].peBlue = cast(ubyte)(
(((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask);
pPal.palPalEntry[i].peFlags = 0;
}
}
hPalette = CreatePalette(pPal);
free(pPal);
if (hPalette) {
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
}
return hPalette;
}
private __gshared bool BINDBC_GL3_RELOADED = false; // is this even used?
}
const uint CUSTOM_MESSAGE_ID = WM_USER + 1;
// HACK: To allow Drag & Drop when running as admin
extern(Windows) BOOL ChangeWindowMessageFilter(UINT message, DWORD dwFlag);
enum MSGFLT_ADD = 1;
static if (ENABLE_OPENGL) {
alias PFNWGLCHOOSEPIXELFORMATARBPROC = extern(C) BOOL function(HDC hdc, const(int)* attributes, const(FLOAT)* fAttributes, UINT maxFormats, int* pixelFormat, UINT *numFormats);
PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
alias PFNWGLCREATECONTEXTATTRIBSARBPROC = extern(C) HGLRC function(HDC hdc, HGLRC hShareContext, const int *attribList);
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB;
/// Shared opengl context helper
struct SharedGLContext {
import bindbc.opengl;
HGLRC _hGLRC; // opengl context
HPALETTE _hPalette;
bool _error;
/// Init OpenGL context, if not yet initialized
bool init(HDC hDC) {
if (_hGLRC) {
// just setup pixel format
if (setupPixelFormat(hDC)) {
Log.i("OpenGL context already exists. Setting pixel format.");
} else {
Log.e("Cannot setup pixel format");
}
return true;
}
if (_error)
return false;
if (setupPixelFormat(hDC)) {
_hPalette = setupPalette(hDC);
_hGLRC = wglCreateContext(hDC);
if (_hGLRC) {
bind(hDC);
wglChoosePixelFormatARB = cast(PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
unbind(hDC);
return true;
} else {
_error = true;
return false;
}
} else {
Log.e("Cannot setup pixel format");
_error = true;
return false;
}
}
bool initGLBindings(HDC hDC)
{
bind(hDC);
scope(exit) unbind(hDC);
bool initialized = initGLSupport(Platform.instance.GLVersionMajor < 3);
if (!initialized) {
uninit();
Log.e("Failed to init OpenGL shaders");
_error = true;
return false;
}
return true;
}
/// A helper function to reinit a context to use multisampling
bool reinit(HDC hDC, int samples)
{
if(setupPixelFormat(hDC, samples))
{
_hPalette = setupPalette(hDC);
_hGLRC = wglCreateContext(hDC);
if (_hGLRC) {
return true;
}
else
{
_error = true;
return false;
}
}
else
{
Log.e("Cannot reinit pixel format");
_error = true;
return false;
}
}
void uninit() {
if (_hGLRC) {
wglDeleteContext(_hGLRC);
_hGLRC = null;
}
}
/// make this context current for DC
void bind(HDC hDC) {
if (!wglMakeCurrent(hDC, _hGLRC)) {
import std.string : format;
Log.e("wglMakeCurrent is failed. ", GetErrorMessage(GetLastError()));
}
}
/// make null context current for DC
void unbind(HDC hDC) {
//wglMakeCurrent(hDC, null);
wglMakeCurrent(null, null);
}
void swapBuffers(HDC hDC) {
SwapBuffers(hDC);
}
int multisampleFormat(HDC hdc, int samples)
{
GLint pixelFormat;
BOOL valid;
GLuint numFormats;
float[] fattribs = [0.0f, 0.0f];
int[] attribs =
[
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_COLOR_BITS_ARB, 24,
WGL_ALPHA_BITS_ARB, 8,
WGL_DEPTH_BITS_ARB, 24,
WGL_STENCIL_BITS_ARB, 0,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
WGL_SAMPLES_ARB, Platform.instance.multisamples,
0
];
valid = wglChoosePixelFormatARB(hdc, attribs.ptr, fattribs.ptr, 1, &pixelFormat, &numFormats);
if(!valid)
{
Log.e("wglChoosePixelFormatARB failed. GetLastError=%x".format(GetLastError()));
return 0;
}
return pixelFormat;
}
bool createCoreRC(HDC hDC)
{
int[] attribs =
[
WGL_CONTEXT_MAJOR_VERSION_ARB, Platform.instance.GLVersionMajor,
WGL_CONTEXT_MINOR_VERSION_ARB, Platform.instance.GLVersionMinor,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
0
];
bind(hDC);
wglCreateContextAttribsARB = cast(PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
HGLRC tmpRC = wglCreateContextAttribsARB(hDC, null, attribs.ptr);
if(!tmpRC)
return false;
wglMakeCurrent(hDC, null);
wglDeleteContext(_hGLRC);
_hGLRC = tmpRC;
wglMakeCurrent(hDC, tmpRC);
unbind(hDC);
return true;
}
}
/// OpenGL context to share between windows
__gshared SharedGLContext sharedGLContext;
}
interface UnknownWindowMessageHandler {
/// return true if message is handled, put return value into result
bool onUnknownWindowMessage(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, ref LRESULT result);
}
class Win32Window : Window {
Win32Platform _platform;
HWND _hwnd;
dstring _caption;
Win32ColorDrawBuf _drawbuf;
private Win32Window _w32parent;
bool useOpengl;
/// win32 only - return window handle
@property HWND windowHandle() {
return _hwnd;
}
this(Win32Platform platform, dstring windowCaption, Window parent, uint flags, uint width = 0, uint height = 0) {
_w32parent = cast(Win32Window)parent;
HWND parenthwnd = _w32parent ? _w32parent._hwnd : null;
_dx = width;
_dy = height;
if (!_dx)
_dx = 600;
if (!_dy)
_dy = 400;
_platform = platform;
_caption = windowCaption;
_windowState = WindowState.hidden;
_flags = flags;
uint ws = WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
if (flags & WindowFlag.Resizable)
ws |= WS_OVERLAPPEDWINDOW;
else
ws |= WS_OVERLAPPED | WS_CAPTION | WS_CAPTION | WS_BORDER | WS_SYSMENU;
//if (flags & WindowFlag.Fullscreen)
// ws |= SDL_WINDOW_FULLSCREEN;
Rect screenRc = getScreenDimensions();
Log.d("Screen dimensions: ", screenRc);
int x = CW_USEDEFAULT;
int y = CW_USEDEFAULT;
if (flags & WindowFlag.Fullscreen) {
// fullscreen
x = screenRc.left;
y = screenRc.top;
_dx = screenRc.width;
_dy = screenRc.height;
ws = WS_POPUP;
}
if (flags & WindowFlag.Borderless) {
ws = WS_POPUP | WS_SYSMENU;
}
_hwnd = CreateWindowW(toUTF16z(WIN_CLASS_NAME), // window class name
toUTF16z(windowCaption), // window caption
ws, // window style
x, // initial x position
y, // initial y position
_dx, // initial x size
_dy, // initial y size
parenthwnd, // parent window handle
null, // window menu handle
_hInstance, // program instance handle
platform.getMultisamples ? cast(void*)null : cast(void*)this); // creation parameters
static if (ENABLE_OPENGL) {
/* initialize OpenGL rendering */
HDC hDC = GetDC(_hwnd);
if (openglEnabled) {
useOpengl = sharedGLContext.init(hDC);
if(platform.multisamples != 0)
{
sharedGLContext.uninit();
ReleaseDC(_hwnd, hDC);
// Recreate window with multisampling (copy-paste from above)
DestroyWindow(_hwnd);
_hwnd = CreateWindowW(toUTF16z(WIN_CLASS_NAME), // window class name
toUTF16z(windowCaption), // window caption
ws, // window style
x, // initial x position
y, // initial y position
_dx, // initial x size
_dy, // initial y size
parenthwnd, // parent window handle
null, // window menu handle
_hInstance, // program instance handle
cast(void*)this); // creation parameters
hDC = GetDC(_hwnd);
useOpengl = sharedGLContext.reinit(hDC, platform.multisamples);
if(!sharedGLContext.createCoreRC(hDC))
{
Log.d("Unable to create Core OpenGL");
throw new Exception("Unable to create Core OpenGL");
}
}
}
sharedGLContext.initGLBindings(hDC);
}
isInitialized = true;
RECT rect;
GetWindowRect(_hwnd, &rect);
handleWindowStateChange(WindowState.unspecified, Rect(rect.left, rect.top, _dx, _dy));
// HACK: This allows drag and drop when ran as admin. Preferable solution is to implement IDragDrop as MS suggests
// See https://stackoverflow.com/questions/64485600/wm-dropfiles-not-called-on-x64
ChangeWindowMessageFilter (WM_DROPFILES, MSGFLT_ADD);
ChangeWindowMessageFilter (WM_COPYDATA, MSGFLT_ADD);
ChangeWindowMessageFilter (0x0049, MSGFLT_ADD);
if (platform.defaultWindowIcon.length != 0)
windowIcon = drawableCache.getImage(platform.defaultWindowIcon);
}
static if (ENABLE_OPENGL) {
private void paintUsingOpenGL() {
// hack to stop infinite WM_PAINT loop
PAINTSTRUCT ps;
HDC hdc2 = BeginPaint(_hwnd, &ps);
EndPaint(_hwnd, &ps);
import bindbc.opengl; //3.gl3;
import bindbc.opengl; //3.wgl;
import dlangui.graphics.gldrawbuf;
//Log.d("onPaint() start drawing opengl viewport: ", _dx, "x", _dy);
//PAINTSTRUCT ps;
//HDC hdc = BeginPaint(_hwnd, &ps);
//scope(exit) EndPaint(_hwnd, &ps);
HDC hdc = GetDC(_hwnd);
sharedGLContext.bind(hdc);
//_glSupport = _gl;
glDisable(GL_DEPTH_TEST);
glViewport(0, 0, _dx, _dy);
float a = 1.0f;
float r = ((_backgroundColor >> 16) & 255) / 255.0f;
float g = ((_backgroundColor >> 8) & 255) / 255.0f;
float b = ((_backgroundColor >> 0) & 255) / 255.0f;
glClearColor(r, g, b, a);
glClear(GL_COLOR_BUFFER_BIT);
GLDrawBuf buf = new GLDrawBuf(_dx, _dy, false);
buf.beforeDrawing();
static if (false) {
// for testing for render
buf.fillRect(Rect(100, 100, 200, 200), 0x704020);
buf.fillRect(Rect(40, 70, 100, 120), 0x000000);
buf.fillRect(Rect(80, 80, 150, 150), 0x80008000); // green
drawableCache.get("exit").drawTo(buf, Rect(300, 100, 364, 164));
drawableCache.get("btn_default_pressed").drawTo(buf, Rect(300, 200, 564, 264));
drawableCache.get("btn_default_normal").drawTo(buf, Rect(300, 0, 400, 50));
drawableCache.get("btn_default_selected").drawTo(buf, Rect(0, 0, 100, 50));
FontRef fnt = currentTheme.font;
fnt.drawText(buf, 40, 40, "Some Text 1234567890 !@#$^*", 0x80FF0000);
} else {
onDraw(buf);
}
buf.afterDrawing();
sharedGLContext.swapBuffers(hdc);
sharedGLContext.unbind(hdc);
destroy(buf);
}
}
protected Rect getScreenDimensions() {
MONITORINFO monitor_info;
monitor_info.cbSize = monitor_info.sizeof;
HMONITOR hMonitor;
if (_hwnd) {
hMonitor = MonitorFromWindow(_hwnd, MONITOR_DEFAULTTONEAREST);
} else {
hMonitor = MonitorFromPoint(POINT(0,0), MONITOR_DEFAULTTOPRIMARY);
}
GetMonitorInfo(hMonitor,
&monitor_info);
Rect res;
res.left = monitor_info.rcMonitor.left;
res.top = monitor_info.rcMonitor.top;
res.right = monitor_info.rcMonitor.right;
res.bottom = monitor_info.rcMonitor.bottom;
return res;
}
protected bool _destroying;
~this() {
debug Log.d("Window destructor");
_destroying = true;
if (_drawbuf) {
destroy(_drawbuf);
_drawbuf = null;
}
/*
static if (ENABLE_OPENGL) {
import derelict.opengl3.wgl;
if (_hGLRC) {
//glSupport.uninitShaders();
//destroy(_glSupport);
//_glSupport = null;
//_gl = null;
wglMakeCurrent (null, null) ;
wglDeleteContext(_hGLRC);
_hGLRC = null;
}
}
*/
if (_hwnd)
DestroyWindow(_hwnd);
_hwnd = null;
}
/// post event to handle in UI thread (this method can be used from background thread)
override void postEvent(CustomEvent event) {
super.postEvent(event);
PostMessageW(_hwnd, CUSTOM_MESSAGE_ID, 0, event.uniqueId);
}
/// set handler for files dropped to app window
override @property Window onFilesDropped(void delegate(string[]) handler) {
super.onFilesDropped(handler);
DragAcceptFiles(_hwnd, handler ? TRUE : FALSE);
return this;
}
private long _nextExpectedTimerTs;
private UINT_PTR _timerId = 1;
/// schedule timer for interval in milliseconds - call window.onTimer when finished
override protected void scheduleSystemTimer(long intervalMillis) {
if (intervalMillis < 10)
intervalMillis = 10;
long nextts = currentTimeMillis + intervalMillis;
if (_timerId && _nextExpectedTimerTs && _nextExpectedTimerTs < nextts + 10)
return; // don't reschedule timer, timer event will be received soon
if (_hwnd) {
//_timerId =
SetTimer(_hwnd, _timerId, cast(uint)intervalMillis, null);
_nextExpectedTimerTs = nextts;
}
}
void handleTimer(UINT_PTR timerId) {
//Log.d("handleTimer id=", timerId);
if (timerId == _timerId) {
KillTimer(_hwnd, timerId);
//_timerId = 0;
_nextExpectedTimerTs = 0;
onTimer();
}
}
/// custom window message handler
Signal!UnknownWindowMessageHandler onUnknownWindowMessage;
private LRESULT handleUnknownWindowMessage(UINT message, WPARAM wParam, LPARAM lParam) {
if (onUnknownWindowMessage.assigned) {
LRESULT res;
if (onUnknownWindowMessage(_hwnd, message, wParam, lParam, res))
return res;
}
return DefWindowProc(_hwnd, message, wParam, lParam);
}
Win32ColorDrawBuf getDrawBuf() {
//RECT rect;
//GetClientRect(_hwnd, &rect);
//int dx = rect.right - rect.left;
//int dy = rect.bottom - rect.top;
if (_drawbuf is null)
_drawbuf = new Win32ColorDrawBuf(_dx, _dy);
else
_drawbuf.resize(_dx, _dy);
_drawbuf.resetClipping();
return _drawbuf;
}
override void show() {
if (!_mainWidget) {
Log.e("Window is shown without main widget");
_mainWidget = new Widget();
}
ReleaseCapture();
if (_mainWidget) {
_mainWidget.measure(SIZE_UNSPECIFIED, SIZE_UNSPECIFIED);
if (flags & WindowFlag.MeasureSize)
resizeWindow(Point(_mainWidget.measuredWidth, _mainWidget.measuredHeight));
else
adjustWindowOrContentSize(_mainWidget.measuredWidth, _mainWidget.measuredHeight);
}
adjustPositionDuringShow();
if (_flags & WindowFlag.Fullscreen) {
Rect rc = getScreenDimensions();
SetWindowPos(_hwnd, HWND_TOPMOST, 0, 0, rc.width, rc.height, SWP_SHOWWINDOW);
_windowState = WindowState.fullscreen;
} else {
ShowWindow(_hwnd, SW_SHOWNORMAL);
_windowState = WindowState.normal;
}
if (_mainWidget)
_mainWidget.setFocus();
SetFocus(_hwnd);
//UpdateWindow(_hwnd);
}
override @property Window parentWindow() {
return _w32parent;
}
override protected void handleWindowActivityChange(bool isWindowActive) {
super.handleWindowActivityChange(isWindowActive);
}
override @property bool isActive() {
return _hwnd == GetForegroundWindow();
}
override @property dstring windowCaption() const {
return _caption;
}
override @property void windowCaption(dstring caption) {
_caption = caption;
if (_hwnd) {
Log.d("windowCaption ", caption);
SetWindowTextW(_hwnd, toUTF16z(_caption));
}
}
/// change window state, position, or size; returns true if successful, false if not supported by platform
override bool setWindowState(WindowState newState, bool activate = false, Rect newWindowRect = RECT_VALUE_IS_NOT_SET) {
if (!_hwnd)
return false;
bool res = false;
// change state and activate support
switch(newState) {
case WindowState.unspecified:
if (activate) {
switch (_windowState) {
case WindowState.hidden:
// show hidden window
ShowWindow(_hwnd, SW_SHOW);
res = true;
break;
case WindowState.normal:
ShowWindow(_hwnd, SW_SHOWNORMAL);
res = true;
break;
case WindowState.fullscreen:
ShowWindow(_hwnd, SW_SHOWNORMAL);
res = true;
break;
case WindowState.minimized:
ShowWindow(_hwnd, SW_SHOWMINIMIZED);
res = true;
break;
case WindowState.maximized:
ShowWindow(_hwnd, SW_SHOWMAXIMIZED);
res = true;
break;
default:
break;
}
res = true;
}
break;
case WindowState.maximized:
if (_windowState != WindowState.maximized || activate) {
ShowWindow(_hwnd, activate ? SW_SHOWMAXIMIZED : SW_MAXIMIZE);
res = true;
}
break;
case WindowState.minimized:
if (_windowState != WindowState.minimized || activate) {
ShowWindow(_hwnd, activate ? SW_SHOWMINIMIZED : SW_MINIMIZE);
res = true;
}
break;
case WindowState.hidden:
if (_windowState != WindowState.hidden) {
ShowWindow(_hwnd, SW_HIDE);
res = true;
}
break;
case WindowState.normal:
if (_windowState != WindowState.normal || activate) {
ShowWindow(_hwnd, activate ? SW_SHOWNORMAL : SW_SHOWNA); // SW_RESTORE
res = true;
}
break;
default:
break;
}
// change size and/or position
bool rectChanged = false;
if (newWindowRect != RECT_VALUE_IS_NOT_SET && (newState == WindowState.normal || newState == WindowState.unspecified)) {
UINT flags = SWP_NOOWNERZORDER | SWP_NOZORDER;
if (!activate)
flags |= SWP_NOACTIVATE;
if (newWindowRect.top == int.min || newWindowRect.left == int.min) {
// no position specified
if (newWindowRect.bottom != int.min && newWindowRect.right != int.min) {
// change size only
SetWindowPos(_hwnd, NULL, 0, 0, newWindowRect.right + 2 * GetSystemMetrics(SM_CXDLGFRAME), newWindowRect.bottom + GetSystemMetrics(SM_CYCAPTION) + 2 * GetSystemMetrics(SM_CYDLGFRAME), flags | SWP_NOMOVE);
rectChanged = true;
res = true;
}
} else {
if (newWindowRect.bottom != int.min && newWindowRect.right != int.min) {
// change size and position
SetWindowPos(_hwnd, NULL, newWindowRect.left, newWindowRect.top, newWindowRect.right + 2 * GetSystemMetrics(SM_CXDLGFRAME), newWindowRect.bottom + GetSystemMetrics(SM_CYCAPTION) + 2 * GetSystemMetrics(SM_CYDLGFRAME), flags);
rectChanged = true;
res = true;
} else {
// change position only
SetWindowPos(_hwnd, NULL, newWindowRect.left, newWindowRect.top, 0, 0, flags | SWP_NOSIZE);
rectChanged = true;
res = true;
}
}
}
if (rectChanged) {
handleWindowStateChange(newState, Rect(newWindowRect.left == int.min ? _windowRect.left : newWindowRect.left,
newWindowRect.top == int.min ? _windowRect.top : newWindowRect.top, newWindowRect.right == int.min ? _windowRect.right : newWindowRect.right,
newWindowRect.bottom == int.min ? _windowRect.bottom : newWindowRect.bottom));
}
else
handleWindowStateChange(newState, RECT_VALUE_IS_NOT_SET);
return res;
}
void onCreate() {
Log.d("Window onCreate");
_platform.onWindowCreated(_hwnd, this);
}
void onDestroy() {
Log.d("Window onDestroy");
_platform.onWindowDestroyed(_hwnd, this);
}
protected bool _closeCalled;
/// close window
override void close() {
if (_closeCalled)
return;
_closeCalled = true;
Log.d("Window.close()");
_platform.closeWindow(this);
}
override protected void handleWindowStateChange(WindowState newState, Rect newWindowRect = RECT_VALUE_IS_NOT_SET) {
if (_destroying)
return;
super.handleWindowStateChange(newState, newWindowRect);
}
HICON _icon;
uint _cursorType;
HANDLE[ushort] _cursorCache;
HANDLE loadCursor(ushort id) {
if (id in _cursorCache)
return _cursorCache[id];
HANDLE h = LoadCursor(null, MAKEINTRESOURCE(id));
_cursorCache[id] = h;
return h;
}
void onSetCursorType() {
HANDLE winCursor = null;
switch (_cursorType) with(CursorType)
{
case None:
winCursor = null;
break;
case NotSet:
break;
case Arrow:
winCursor = loadCursor(IDC_ARROW);
break;
case IBeam:
winCursor = loadCursor(IDC_IBEAM);
break;
case Wait:
winCursor = loadCursor(IDC_WAIT);
break;
case Crosshair:
winCursor = loadCursor(IDC_CROSS);
break;
case WaitArrow:
winCursor = loadCursor(IDC_APPSTARTING);
break;
case SizeNWSE:
winCursor = loadCursor(IDC_SIZENWSE);
break;
case SizeNESW:
winCursor = loadCursor(IDC_SIZENESW);
break;
case SizeWE:
winCursor = loadCursor(IDC_SIZEWE);
break;
case SizeNS:
winCursor = loadCursor(IDC_SIZENS);
break;
case SizeAll:
winCursor = loadCursor(IDC_SIZEALL);
break;
case No:
winCursor = loadCursor(IDC_NO);
break;
case Hand:
winCursor = loadCursor(IDC_HAND);
break;
default:
break;
}
SetCursor(winCursor);
}
/// sets cursor type for window
override protected void setCursorType(uint cursorType) {
// override to support different mouse cursors
_cursorType = cursorType;
onSetCursorType();
}
/// sets window icon
@property override void windowIcon(DrawBufRef buf) {
if (_icon)
DestroyIcon(_icon);
_icon = null;
ColorDrawBuf icon = cast(ColorDrawBuf)buf.get;
if (!icon) {
Log.e("Trying to set null icon for window");
return;
}
Win32ColorDrawBuf resizedicon = new Win32ColorDrawBuf(icon, 32, 32);
resizedicon.invertAlpha();
ICONINFO ii;
HBITMAP mask = resizedicon.createTransparencyBitmap();
HBITMAP color = resizedicon.destroyLeavingBitmap();
ii.fIcon = TRUE;
ii.xHotspot = 0;
ii.yHotspot = 0;
ii.hbmMask = mask;
ii.hbmColor = color;
_icon = CreateIconIndirect(&ii);
if (_icon) {
SendMessageW(_hwnd, WM_SETICON, ICON_SMALL, cast(LPARAM)_icon);
SendMessageW(_hwnd, WM_SETICON, ICON_BIG, cast(LPARAM)_icon);
} else {
Log.e("failed to create icon");
}
if (mask)
DeleteObject(mask);
DeleteObject(color);
}
private void paintUsingGDI() {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(_hwnd, &ps);
scope(exit) EndPaint(_hwnd, &ps);
Win32ColorDrawBuf buf = getDrawBuf();
buf.fill(_backgroundColor);
onDraw(buf);
buf.drawTo(hdc, 0, 0);
}
void onPaint() {
debug(DebugRedraw) Log.d("onPaint()");
long paintStart = currentTimeMillis;
static if (ENABLE_OPENGL) {
if (useOpengl && sharedGLContext._hGLRC) {
paintUsingOpenGL();
} else {
paintUsingGDI();
}
} else {
paintUsingGDI();
}
long paintEnd = currentTimeMillis;
debug(DebugRedraw) Log.d("WM_PAINT handling took ", paintEnd - paintStart, " ms");
}
protected ButtonDetails _lbutton;
protected ButtonDetails _mbutton;
protected ButtonDetails _rbutton;
private void updateButtonsState(uint flags) {
if (!(flags & MK_LBUTTON) && _lbutton.isDown)
_lbutton.reset();
if (!(flags & MK_MBUTTON) && _mbutton.isDown)
_mbutton.reset();
if (!(flags & MK_RBUTTON) && _rbutton.isDown)
_rbutton.reset();
}
private bool _mouseTracking;
private bool onMouse(uint message, uint flags, short x, short y) {
debug(DebugMouseEvents) Log.d("Win32 Mouse Message ", message, " flags=", flags, " x=", x, " y=", y);