/
Window.c
3433 lines (2844 loc) · 112 KB
/
Window.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Window.h"
#include "Platform.h"
#include "Input.h"
#include "Event.h"
#include "Logger.h"
#include "Funcs.h"
int Display_BitsPerPixel;
Rect2D Display_Bounds;
bool Window_Exists, Window_Focused;
Rect2D Window_Bounds, Window_ClientBounds;
static bool win_cursorVisible = true;
bool Cursor_GetVisible(void) { return win_cursorVisible; }
void Window_CreateSimple(int width, int height) {
struct GraphicsMode mode;
int x, y;
x = Display_Bounds.X + (Display_Bounds.Width - width) / 2;
y = Display_Bounds.Y + (Display_Bounds.Height - height) / 2;
GraphicsMode_MakeDefault(&mode);
Window_Create(x, y, width, height, &mode);
}
static Point2D cursorPrev;
static void Window_CentreMousePosition(void) {
int cenX = Window_ClientBounds.X + Window_ClientBounds.Width / 2;
int cenY = Window_ClientBounds.Y + Window_ClientBounds.Height / 2;
Cursor_SetScreenPos(cenX, cenY);
/* Fixes issues with large DPI displays on Windows >= 8.0. */
cursorPrev = Cursor_GetScreenPos();
}
static void Window_RegrabMouse(void) {
if (!Window_Focused || !Window_Exists) return;
Window_CentreMousePosition();
}
#if !defined(CC_BUILD_SDL) && !defined(CC_BUILD_WEBCANVAS)
void Window_EnableRawMouse(void) {
Window_RegrabMouse();
Cursor_SetVisible(false);
}
void Window_UpdateRawMouse(void) {
Point2D p = Cursor_GetScreenPos();
Event_RaiseMouseMove(&MouseEvents.RawMoved, p.X - cursorPrev.X, p.Y - cursorPrev.Y);
Window_CentreMousePosition();
}
void Window_DisableRawMouse(void) {
Window_RegrabMouse();
Cursor_SetVisible(true);
}
#endif
/*########################################################################################################################*
*------------------------------------------------------GraphicsMode-------------------------------------------------------*
*#########################################################################################################################*/
void GraphicsMode_Make(struct GraphicsMode* m, int bpp, int depth, int stencil) {
m->DepthBits = depth;
m->StencilBits = stencil;
m->IsIndexed = bpp < 15;
m->BitsPerPixel = bpp;
m->A = 0;
switch (bpp) {
case 32:
m->R = 8; m->G = 8; m->B = 8; m->A = 8; break;
case 24:
m->R = 8; m->G = 8; m->B = 8; break;
case 16:
m->R = 5; m->G = 6; m->B = 5; break;
case 15:
m->R = 5; m->G = 5; m->B = 5; break;
case 8:
m->R = 3; m->G = 3; m->B = 2; break;
case 4:
m->R = 2; m->G = 2; m->B = 1; break;
default:
/* mode->R = 0; mode->G = 0; mode->B = 0; */
Logger_Abort2(bpp, "Unsupported bits per pixel"); break;
}
}
void GraphicsMode_MakeDefault(struct GraphicsMode* m) {
GraphicsMode_Make(m, Display_BitsPerPixel, 24, 0);
}
/*########################################################################################################################*
*------------------------------------------------------Win32 window-------------------------------------------------------*
*#########################################################################################################################*/
#ifdef CC_BUILD_WINGUI
#define WIN32_LEAN_AND_MEAN
#define NOSERVICE
#define NOMCX
#define NOIME
#ifndef UNICODE
#define UNICODE
#define _UNICODE
#endif
#include <windows.h>
#define CC_WIN_STYLE WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN
#define CC_WIN_CLASSNAME TEXT("ClassiCube_Window")
#define Rect_Width(rect) (rect.right - rect.left)
#define Rect_Height(rect) (rect.bottom - rect.top)
#ifndef WM_XBUTTONDOWN
/* Missing if _WIN32_WINNT isn't defined */
#define WM_XBUTTONDOWN 0x020B
#define WM_XBUTTONUP 0x020C
#endif
static HINSTANCE win_instance;
static HWND win_handle;
static HDC win_DC;
static int win_state;
static int suppress_resize; /* Used in WindowBorder and WindowState in order to avoid rapid, consecutive resize events */
static Rect2D prev_bounds; /* Used to restore previous size when leaving fullscreen mode */
/*########################################################################################################################*
*-----------------------------------------------------Private details-----------------------------------------------------*
*#########################################################################################################################*/
const static uint8_t key_map[14 * 16] = {
0, 0, 0, 0, 0, 0, 0, 0, KEY_BACKSPACE, KEY_TAB, 0, 0, 0, KEY_ENTER, 0, 0,
0, 0, 0, KEY_PAUSE, KEY_CAPSLOCK, 0, 0, 0, 0, 0, 0, KEY_ESCAPE, 0, 0, 0, 0,
KEY_SPACE, KEY_PAGEUP, KEY_PAGEDOWN, KEY_END, KEY_HOME, KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN, 0, KEY_PRINTSCREEN, 0, KEY_PRINTSCREEN, KEY_INSERT, KEY_DELETE, 0,
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 0, 0, 0, 0, 0, 0,
0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', KEY_LWIN, KEY_RWIN, KEY_MENU, 0, 0,
KEY_KP0, KEY_KP1, KEY_KP2, KEY_KP3, KEY_KP4, KEY_KP5, KEY_KP6, KEY_KP7, KEY_KP8, KEY_KP9, KEY_KP_MULTIPLY, KEY_KP_PLUS, 0, KEY_KP_MINUS, KEY_KP_DECIMAL, KEY_KP_DIVIDE,
KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_F13, KEY_F14, KEY_F15, KEY_F16,
KEY_F17, KEY_F18, KEY_F19, KEY_F20, KEY_F21, KEY_F22, KEY_F23, KEY_F24, 0, 0, 0, 0, 0, 0, 0, 0,
KEY_NUMLOCK, KEY_SCROLLLOCK, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
KEY_LSHIFT, KEY_RSHIFT, KEY_LCTRL, KEY_RCTRL, KEY_LALT, KEY_RALT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_SEMICOLON, KEY_EQUALS, KEY_COMMA, KEY_MINUS, KEY_PERIOD, KEY_SLASH,
KEY_TILDE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_LBRACKET, KEY_BACKSLASH, KEY_RBRACKET, KEY_QUOTE, 0,
};
static Key Window_MapKey(WPARAM key) { return key < Array_Elems(key_map) ? key_map[key] : 0; }
static void Window_ResetWindowState(void) {
suppress_resize++;
Window_SetWindowState(WINDOW_STATE_NORMAL);
Window_ProcessEvents();
suppress_resize--;
}
static bool win_hiddenBorder;
static void Window_DoSetHiddenBorder(bool value) {
bool wasVisible;
RECT rect;
if (win_hiddenBorder == value) return;
/* We wish to avoid making an invisible window visible just to change the border.
However, it's a good idea to make a visible window invisible temporarily, to
avoid garbage caused by the border change. */
wasVisible = Window_GetVisible();
/* To ensure maximized/minimized windows work correctly, reset state to normal,
change the border, then go back to maximized/minimized. */
int state = win_state;
Window_ResetWindowState();
DWORD style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
style |= (value ? WS_POPUP : WS_OVERLAPPEDWINDOW);
/* Make sure client size doesn't change when changing the border style.*/
rect.left = Window_Bounds.X; rect.top = Window_Bounds.Y;
rect.right = rect.left + Window_Bounds.Width;
rect.bottom = rect.top + Window_Bounds.Height;
AdjustWindowRect(&rect, style, false);
/* This avoids leaving garbage on the background window. */
if (wasVisible) Window_SetVisible(false);
SetWindowLong(win_handle, GWL_STYLE, style);
SetWindowPos(win_handle, NULL, 0, 0, Rect_Width(rect), Rect_Height(rect),
SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
/* Force window to redraw update its borders, but only if it's
already visible (invisible windows will change borders when
they become visible, so no need to make them visiable prematurely).*/
if (wasVisible) Window_SetVisible(true);
Window_SetWindowState(state);
}
static void Window_SetHiddenBorder(bool hidden) {
suppress_resize++;
Window_DoSetHiddenBorder(hidden);
Window_ProcessEvents();
suppress_resize--;
}
static CC_INLINE void Window_SetRect(Rect2D* dst, const RECT* src) {
dst->X = src->left;
dst->Y = src->top;
dst->Width = src->right - src->left;
dst->Height = src->bottom - src->top;
}
static void Window_RefreshBounds(void) {
RECT rect;
POINT topLeft = { 0, 0 };
GetWindowRect(win_handle, &rect);
Window_SetRect(&Window_Bounds, &rect);
GetClientRect(win_handle, &rect);
Window_SetRect(&Window_ClientBounds, &rect);
/* MSDN says GetClientRect always returns 0,0 for top left */
ClientToScreen(win_handle, &topLeft);
Window_ClientBounds.X = topLeft.x;
Window_ClientBounds.Y = topLeft.y;
}
static LRESULT CALLBACK Window_Procedure(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) {
char keyChar;
bool wasFocused;
float wheelDelta;
switch (message) {
case WM_ACTIVATE:
wasFocused = Window_Focused;
Window_Focused = LOWORD(wParam) != 0;
if (Window_Focused != wasFocused) {
Event_RaiseVoid(&WindowEvents.FocusChanged);
}
break;
case WM_ERASEBKGND:
Event_RaiseVoid(&WindowEvents.Redraw);
return 1;
case WM_WINDOWPOSCHANGED:
{
WINDOWPOS* pos = (WINDOWPOS*)lParam;
if (pos->hwnd != win_handle) break;
bool moved = pos->x != Window_Bounds.X || pos->y != Window_Bounds.Y;
bool sized = pos->cx != Window_Bounds.Width || pos->cy != Window_Bounds.Height;
if (moved) {
Window_RefreshBounds();
Event_RaiseVoid(&WindowEvents.Moved);
}
if (sized) {
Window_RefreshBounds();
SetWindowPos(win_handle, NULL,
Window_Bounds.X, Window_Bounds.Y, Window_Bounds.Width, Window_Bounds.Height,
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
if (suppress_resize <= 0) {
Event_RaiseVoid(&WindowEvents.Resized);
}
}
} break;
case WM_STYLECHANGED:
if (wParam == GWL_STYLE) {
DWORD style = ((STYLESTRUCT*)lParam)->styleNew;
if (style & WS_POPUP) {
win_hiddenBorder = true;
} else if (style & WS_THICKFRAME) {
win_hiddenBorder = false;
}
}
break;
case WM_SIZE:
{
int new_state = win_state;
switch (wParam) {
case SIZE_RESTORED: new_state = WINDOW_STATE_NORMAL; break;
case SIZE_MINIMIZED: new_state = WINDOW_STATE_MINIMISED; break;
case SIZE_MAXIMIZED: new_state = win_hiddenBorder ? WINDOW_STATE_FULLSCREEN : WINDOW_STATE_MAXIMISED; break;
}
if (new_state != win_state) {
win_state = new_state;
Event_RaiseVoid(&WindowEvents.StateChanged);
}
} break;
case WM_CHAR:
if (Convert_TryUnicodeToCP437((Codepoint)wParam, &keyChar)) {
Event_RaiseInt(&KeyEvents.Press, keyChar);
}
break;
case WM_MOUSEMOVE:
/* Set before position change, in case mouse buttons changed when outside window */
Mouse_SetPressed(MOUSE_LEFT, (wParam & 0x01) != 0);
Mouse_SetPressed(MOUSE_RIGHT, (wParam & 0x02) != 0);
Mouse_SetPressed(MOUSE_MIDDLE, (wParam & 0x10) != 0);
/* TODO: do we need to set XBUTTON1/XBUTTON2 here */
Mouse_SetPosition(LOWORD(lParam), HIWORD(lParam));
break;
case WM_MOUSEWHEEL:
wheelDelta = ((short)HIWORD(wParam)) / (float)WHEEL_DELTA;
Mouse_SetWheel(Mouse_Wheel + wheelDelta);
return 0;
case WM_LBUTTONDOWN:
Mouse_SetPressed(MOUSE_LEFT, true); break;
case WM_MBUTTONDOWN:
Mouse_SetPressed(MOUSE_MIDDLE, true); break;
case WM_RBUTTONDOWN:
Mouse_SetPressed(MOUSE_RIGHT, true); break;
case WM_XBUTTONDOWN:
Key_SetPressed(HIWORD(wParam) == 1 ? KEY_XBUTTON1 : KEY_XBUTTON2, true);
break;
case WM_LBUTTONUP:
Mouse_SetPressed(MOUSE_LEFT, false); break;
case WM_MBUTTONUP:
Mouse_SetPressed(MOUSE_MIDDLE, false); break;
case WM_RBUTTONUP:
Mouse_SetPressed(MOUSE_RIGHT, false); break;
case WM_XBUTTONUP:
Key_SetPressed(HIWORD(wParam) == 1 ? KEY_XBUTTON1 : KEY_XBUTTON2, false);
break;
case WM_KEYDOWN:
case WM_KEYUP:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
{
bool pressed = message == WM_KEYDOWN || message == WM_SYSKEYDOWN;
/* Shift/Control/Alt behave strangely when e.g. ShiftRight is held down and ShiftLeft is pressed
and released. It looks like neither key is released in this case, or that the wrong key is
released in the case of Control and Alt.
To combat this, we are going to release both keys when either is released. Hacky, but should work.
Win95 does not distinguish left/right key constants (GetAsyncKeyState returns 0).
In this case, both keys will be reported as pressed. */
bool ext = (lParam & (1UL << 24)) != 0;
bool lShiftDown, rShiftDown;
Key mappedKey;
switch (wParam)
{
case VK_SHIFT:
/* The behavior of this key is very strange. Unlike Control and Alt, there is no extended bit
to distinguish between left and right keys. Moreover, pressing both keys and releasing one
may result in both keys being held down (but not always).*/
lShiftDown = ((USHORT)GetKeyState(VK_LSHIFT)) >> 15;
rShiftDown = ((USHORT)GetKeyState(VK_RSHIFT)) >> 15;
if (!pressed || lShiftDown != rShiftDown) {
Key_SetPressed(KEY_LSHIFT, lShiftDown);
Key_SetPressed(KEY_RSHIFT, rShiftDown);
}
return 0;
case VK_CONTROL:
Key_SetPressed(ext ? KEY_RCTRL : KEY_LCTRL, pressed);
return 0;
case VK_MENU:
Key_SetPressed(ext ? KEY_RALT : KEY_LALT, pressed);
return 0;
case VK_RETURN:
Key_SetPressed(ext ? KEY_KP_ENTER : KEY_ENTER, pressed);
return 0;
default:
mappedKey = Window_MapKey(wParam);
if (mappedKey) Key_SetPressed(mappedKey, pressed);
return 0;
}
} break;
case WM_SYSCHAR:
return 0;
case WM_KILLFOCUS:
/* TODO: Keep track of keyboard when focus is lost */
Key_Clear();
break;
case WM_CLOSE:
Event_RaiseVoid(&WindowEvents.Closing);
if (Window_Exists) DestroyWindow(win_handle);
Window_Exists = false;
break;
case WM_DESTROY:
Window_Exists = false;
UnregisterClass(CC_WIN_CLASSNAME, win_instance);
if (win_DC) ReleaseDC(win_handle, win_DC);
Event_RaiseVoid(&WindowEvents.Destroyed);
break;
}
return DefWindowProc(handle, message, wParam, lParam);
}
/*########################################################################################################################*
*--------------------------------------------------Public implementation--------------------------------------------------*
*#########################################################################################################################*/
void Window_Init(void) {
HDC hdc = GetDC(NULL);
Display_Bounds.Width = GetSystemMetrics(SM_CXSCREEN);
Display_Bounds.Height = GetSystemMetrics(SM_CYSCREEN);
Display_BitsPerPixel = GetDeviceCaps(hdc, BITSPIXEL);
ReleaseDC(NULL, hdc);
}
void Window_Create(int x, int y, int width, int height, struct GraphicsMode* mode) {
win_instance = GetModuleHandle(NULL);
/* TODO: UngroupFromTaskbar(); */
/* Find out the final window rectangle, after the WM has added its chrome (titlebar, sidebars etc). */
RECT rect = { x, y, x + width, y + height };
AdjustWindowRect(&rect, CC_WIN_STYLE, false);
WNDCLASSEX wc = { 0 };
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_OWNDC;
wc.hInstance = win_instance;
wc.lpfnWndProc = Window_Procedure;
wc.lpszClassName = CC_WIN_CLASSNAME;
wc.hIcon = (HICON)LoadImage(win_instance, MAKEINTRESOURCE(1), IMAGE_ICON,
GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), 0);
wc.hIconSm = (HICON)LoadImage(win_instance, MAKEINTRESOURCE(1), IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
ATOM atom = RegisterClassEx(&wc);
if (!atom) Logger_Abort2(GetLastError(), "Failed to register window class");
win_handle = CreateWindowEx(0, MAKEINTATOM(atom), NULL, CC_WIN_STYLE,
rect.left, rect.top, Rect_Width(rect), Rect_Height(rect),
NULL, NULL, win_instance, NULL);
if (!win_handle) Logger_Abort2(GetLastError(), "Failed to create window");
Window_RefreshBounds();
win_DC = GetDC(win_handle);
if (!win_DC) Logger_Abort2(GetLastError(), "Failed to get device context");
Window_Exists = true;
}
void Window_SetTitle(const String* title) {
TCHAR str[300];
Platform_ConvertString(str, title);
SetWindowText(win_handle, str);
}
void Window_GetClipboardText(String* value) {
/* retry up to 50 times*/
int i;
value->length = 0;
for (i = 0; i < 50; i++) {
if (!OpenClipboard(win_handle)) {
Thread_Sleep(10);
continue;
}
bool isUnicode = true;
HANDLE hGlobal = GetClipboardData(CF_UNICODETEXT);
if (!hGlobal) {
hGlobal = GetClipboardData(CF_TEXT);
isUnicode = false;
}
if (!hGlobal) { CloseClipboard(); return; }
LPVOID src = GlobalLock(hGlobal);
SIZE_T size = GlobalSize(hGlobal);
/* ignore trailing NULL at end */
/* TODO: Verify it's always there */
if (isUnicode) {
Convert_DecodeUtf16(value, (Codepoint*)src, size - 2);
} else {
Convert_DecodeAscii(value, (uint8_t*)src, size - 1);
}
GlobalUnlock(hGlobal);
CloseClipboard();
return;
}
}
void Window_SetClipboardText(const String* value) {
/* retry up to 10 times */
int i;
for (i = 0; i < 10; i++) {
if (!OpenClipboard(win_handle)) {
Thread_Sleep(100);
continue;
}
HANDLE hGlobal = GlobalAlloc(GMEM_MOVEABLE, (value->length + 1) * 2);
if (!hGlobal) { CloseClipboard(); return; }
Codepoint* text = GlobalLock(hGlobal);
for (i = 0; i < value->length; i++, text++) {
*text = Convert_CP437ToUnicode(value->buffer[i]);
}
*text = '\0';
GlobalUnlock(hGlobal);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, hGlobal);
CloseClipboard();
return;
}
}
void Window_SetLocation(int x, int y) {
SetWindowPos(win_handle, NULL, x, y, 0, 0, SWP_NOSIZE);
}
void Window_SetSize(int width, int height) {
DWORD style = GetWindowLong(win_handle, GWL_STYLE);
RECT rect = { 0, 0, width, height };
AdjustWindowRect(&rect, style, false);
SetWindowPos(win_handle, NULL, 0, 0,
Rect_Width(rect), Rect_Height(rect), SWP_NOMOVE);
}
void* Window_GetWindowHandle(void) { return win_handle; }
bool Window_GetVisible(void) { return IsWindowVisible(win_handle); }
void Window_SetVisible(bool visible) {
if (visible) {
ShowWindow(win_handle, SW_SHOW);
BringWindowToTop(win_handle);
SetForegroundWindow(win_handle);
} else {
ShowWindow(win_handle, SW_HIDE);
}
}
void Window_Close(void) {
PostMessage(win_handle, WM_CLOSE, 0, 0);
}
int Window_GetWindowState(void) { return win_state; }
void Window_SetWindowState(int state) {
if (win_state == state) return;
DWORD command = 0;
bool exiting_fullscreen = false;
switch (state) {
case WINDOW_STATE_NORMAL:
command = SW_RESTORE;
/* If we are leaving fullscreen mode we need to restore the border. */
if (win_state == WINDOW_STATE_FULLSCREEN)
exiting_fullscreen = true;
break;
case WINDOW_STATE_MAXIMISED:
/* Reset state to avoid strange interactions with fullscreen/minimized windows. */
Window_ResetWindowState();
command = SW_MAXIMIZE;
break;
case WINDOW_STATE_MINIMISED:
command = SW_MINIMIZE;
break;
case WINDOW_STATE_FULLSCREEN:
/* We achieve fullscreen by hiding the window border and sending the MAXIMIZE command.
We cannot use the WindowState.Maximized directly, as that will not send the MAXIMIZE
command for windows with hidden borders. */
/* Reset state to avoid strange side-effects from maximized/minimized windows. */
Window_ResetWindowState();
prev_bounds = Window_Bounds;
Window_SetHiddenBorder(true);
command = SW_MAXIMIZE;
SetForegroundWindow(win_handle);
break;
}
if (command != 0) ShowWindow(win_handle, command);
/* Restore previous window border or apply pending border change when leaving fullscreen mode. */
if (exiting_fullscreen) Window_SetHiddenBorder(false);
/* Restore previous window size/location if necessary */
if (command == SW_RESTORE && (prev_bounds.Width || prev_bounds.Height)) {
Rect2D rect = prev_bounds;
/* NOTE: the bounds variable is updated when the resize/move message arrives. */
SetWindowPos(win_handle, NULL, rect.X, rect.Y, rect.Width, rect.Height, 0);
prev_bounds.Width = 0; prev_bounds.Height = 0;
}
}
void Window_ProcessEvents(void) {
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, 1)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
HWND foreground = GetForegroundWindow();
if (foreground) {
Window_Focused = foreground == win_handle;
}
}
Point2D Cursor_GetScreenPos(void) {
POINT point; GetCursorPos(&point);
Point2D p = { point.x, point.y }; return p;
}
void Cursor_SetScreenPos(int x, int y) {
SetCursorPos(x, y);
}
void Cursor_SetVisible(bool visible) {
win_cursorVisible = visible;
ShowCursor(visible ? 1 : 0);
}
void Window_ShowDialog(const char* title, const char* msg) {
MessageBoxA(win_handle, msg, title, 0);
}
static HGDIOBJ draw_DC;
static HBITMAP draw_DIB;
void Window_InitRaw(Bitmap* bmp) {
BITMAPINFO hdr = { 0 };
if (!draw_DC) draw_DC = CreateCompatibleDC(win_DC);
if (draw_DIB) DeleteObject(draw_DIB);
hdr.bmiHeader.biSize = sizeof(BITMAPINFO);
hdr.bmiHeader.biWidth = bmp->Width;
hdr.bmiHeader.biHeight = -bmp->Height;
hdr.bmiHeader.biBitCount = 32;
hdr.bmiHeader.biPlanes = 1;
draw_DIB = CreateDIBSection(draw_DC, &hdr, 0, &bmp->Scan0, NULL, 0);
}
void Window_DrawRaw(Rect2D r) {
HGDIOBJ oldSrc = SelectObject(draw_DC, draw_DIB);
BOOL success = BitBlt(win_DC, r.X, r.Y, r.Width, r.Height, draw_DC, r.X, r.Y, SRCCOPY);
SelectObject(draw_DC, oldSrc);
}
#endif
/*########################################################################################################################*
*-------------------------------------------------------X11 window--------------------------------------------------------*
*#########################################################################################################################*/
#ifdef CC_BUILD_X11
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#define _NET_WM_STATE_REMOVE 0
#define _NET_WM_STATE_ADD 1
#define _NET_WM_STATE_TOGGLE 2
static Display* win_display;
static int win_screen;
static Window win_rootWin;
static Window win_handle;
static XVisualInfo win_visual;
static int borderLeft, borderRight, borderTop, borderBottom;
static Atom wm_destroy, net_wm_state;
static Atom net_wm_state_minimized;
static Atom net_wm_state_fullscreen;
static Atom net_wm_state_maximized_horizontal;
static Atom net_wm_state_maximized_vertical;
static Atom net_wm_icon, net_frame_extents;
static Atom xa_clipboard, xa_targets, xa_utf8_string, xa_data_sel;
static Atom xa_atom = 4, xa_cardinal = 6;
static long win_eventMask;
/*########################################################################################################################*
*-----------------------------------------------------Private details-----------------------------------------------------*
*#########################################################################################################################*/
static Key Window_MapKey(KeySym key) {
if (key >= XK_0 && key <= XK_9) { return '0' + (key - XK_0); }
if (key >= XK_A && key <= XK_Z) { return 'A' + (key - XK_A); }
if (key >= XK_a && key <= XK_z) { return 'A' + (key - XK_a); }
if (key >= XK_F1 && key <= XK_F35) { return KEY_F1 + (key - XK_F1); }
if (key >= XK_KP_0 && key <= XK_KP_9) { return KEY_KP0 + (key - XK_KP_0); }
switch (key) {
case XK_Escape: return KEY_ESCAPE;
case XK_Return: return KEY_ENTER;
case XK_space: return KEY_SPACE;
case XK_BackSpace: return KEY_BACKSPACE;
case XK_Shift_L: return KEY_LSHIFT;
case XK_Shift_R: return KEY_RSHIFT;
case XK_Alt_L: return KEY_LALT;
case XK_Alt_R: return KEY_RALT;
case XK_Control_L: return KEY_LCTRL;
case XK_Control_R: return KEY_RCTRL;
case XK_Super_L: return KEY_LWIN;
case XK_Super_R: return KEY_RWIN;
case XK_Meta_L: return KEY_LWIN;
case XK_Meta_R: return KEY_RWIN;
case XK_Menu: return KEY_MENU;
case XK_Tab: return KEY_TAB;
case XK_minus: return KEY_MINUS;
case XK_plus: return KEY_EQUALS;
case XK_equal: return KEY_EQUALS;
case XK_Caps_Lock: return KEY_CAPSLOCK;
case XK_Num_Lock: return KEY_NUMLOCK;
case XK_Pause: return KEY_PAUSE;
case XK_Break: return KEY_PAUSE;
case XK_Scroll_Lock: return KEY_SCROLLLOCK;
case XK_Insert: return KEY_INSERT;
case XK_Print: return KEY_PRINTSCREEN;
case XK_Sys_Req: return KEY_PRINTSCREEN;
case XK_backslash: return KEY_BACKSLASH;
case XK_bar: return KEY_BACKSLASH;
case XK_braceleft: return KEY_LBRACKET;
case XK_bracketleft: return KEY_LBRACKET;
case XK_braceright: return KEY_RBRACKET;
case XK_bracketright: return KEY_RBRACKET;
case XK_colon: return KEY_SEMICOLON;
case XK_semicolon: return KEY_SEMICOLON;
case XK_quoteright: return KEY_QUOTE;
case XK_quotedbl: return KEY_QUOTE;
case XK_quoteleft: return KEY_TILDE;
case XK_asciitilde: return KEY_TILDE;
case XK_comma: return KEY_COMMA;
case XK_less: return KEY_COMMA;
case XK_period: return KEY_PERIOD;
case XK_greater: return KEY_PERIOD;
case XK_slash: return KEY_SLASH;
case XK_question: return KEY_SLASH;
case XK_Left: return KEY_LEFT;
case XK_Down: return KEY_DOWN;
case XK_Right: return KEY_RIGHT;
case XK_Up: return KEY_UP;
case XK_Delete: return KEY_DELETE;
case XK_Home: return KEY_HOME;
case XK_End: return KEY_END;
case XK_Page_Up: return KEY_PAGEUP;
case XK_Page_Down: return KEY_PAGEDOWN;
case XK_KP_Add: return KEY_KP_PLUS;
case XK_KP_Subtract: return KEY_KP_MINUS;
case XK_KP_Multiply: return KEY_KP_MULTIPLY;
case XK_KP_Divide: return KEY_KP_DIVIDE;
case XK_KP_Decimal: return KEY_KP_DECIMAL;
case XK_KP_Insert: return KEY_KP0;
case XK_KP_End: return KEY_KP1;
case XK_KP_Down: return KEY_KP2;
case XK_KP_Page_Down: return KEY_KP3;
case XK_KP_Left: return KEY_KP4;
case XK_KP_Begin: return KEY_KP5;
case XK_KP_Right: return KEY_KP6;
case XK_KP_Home: return KEY_KP7;
case XK_KP_Up: return KEY_KP8;
case XK_KP_Page_Up: return KEY_KP9;
case XK_KP_Delete: return KEY_KP_DECIMAL;
case XK_KP_Enter: return KEY_KP_ENTER;
}
return KEY_NONE;
}
static void Window_RegisterAtoms(void) {
Display* display = win_display;
wm_destroy = XInternAtom(display, "WM_DELETE_WINDOW", true);
net_wm_state = XInternAtom(display, "_NET_WM_STATE", false);
net_wm_state_minimized = XInternAtom(display, "_NET_WM_STATE_MINIMIZED", false);
net_wm_state_fullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", false);
net_wm_state_maximized_horizontal = XInternAtom(display, "_NET_WM_STATE_MAXIMIZED_HORZ", false);
net_wm_state_maximized_vertical = XInternAtom(display, "_NET_WM_STATE_MAXIMIZED_VERT", false);
net_wm_icon = XInternAtom(display, "_NEW_WM_ICON", false);
net_frame_extents = XInternAtom(display, "_NET_FRAME_EXTENTS", false);
xa_clipboard = XInternAtom(display, "CLIPBOARD", false);
xa_targets = XInternAtom(display, "TARGETS", false);
xa_utf8_string = XInternAtom(display, "UTF8_STRING", false);
xa_data_sel = XInternAtom(display, "CC_SEL_DATA", false);
}
static void Window_RefreshBorders(void) {
Atom prop_type;
int prop_format;
unsigned long items, after;
long* borders = NULL;
XGetWindowProperty(win_display, win_handle, net_frame_extents, 0, 16, false,
xa_cardinal, &prop_type, &prop_format, &items, &after, &borders);
if (!borders) return;
if (items == 4) {
borderLeft = borders[0]; borderRight = borders[1];
borderTop = borders[2]; borderBottom = borders[3];
}
XFree(borders);
}
static void Window_RefreshBounds(const XConfigureEvent* e) {
Window_RefreshBorders();
if (e->x != Window_ClientBounds.X || e->y != Window_ClientBounds.Y) {
Window_ClientBounds.X = e->x; Window_ClientBounds.Y = e->y;
/* To get the external (window) position, need to add the border */
Window_Bounds.X = e->x - borderLeft;
Window_Bounds.Y = e->y - borderTop;
Event_RaiseVoid(&WindowEvents.Moved);
}
if (e->width != Window_ClientBounds.Width || e->height != Window_ClientBounds.Height) {
Window_ClientBounds.Width = e->width;
Window_ClientBounds.Height = e->height;
/* To get the external (window) size, need to add the border size */
Window_Bounds.Width = e->width + borderLeft + borderRight;
Window_Bounds.Height = e->height + borderTop + borderBottom;
Event_RaiseVoid(&WindowEvents.Resized);
}
}
/*########################################################################################################################*
*--------------------------------------------------Public implementation--------------------------------------------------*
*#########################################################################################################################*/
static XVisualInfo GLContext_SelectVisual(struct GraphicsMode* mode);
void Window_Init(void) {
Display* display = XOpenDisplay(NULL);
int screen;
if (!display) Logger_Abort("Failed to open display");
screen = DefaultScreen(display);
win_display = display;
win_screen = screen;
win_rootWin = RootWindow(display, screen);
/* TODO: Use Xinerama and XRandR for querying these */
Display_Bounds.Width = DisplayWidth(display, screen);
Display_Bounds.Height = DisplayHeight(display, screen);
Display_BitsPerPixel = DefaultDepth(display, screen);
}
void Window_Create(int x, int y, int width, int height, struct GraphicsMode* mode) {
XSetWindowAttributes attributes = { 0 };
XSizeHints hints = { 0 };
uintptr_t addr;
int supported;
/* Open a display connection to the X server, and obtain the screen and root window */
addr = (uintptr_t)win_display;
Platform_Log3("Display: %x, Screen %i, Root window: %h", &addr, &win_screen, &win_rootWin);
Window_RegisterAtoms();
win_eventMask = StructureNotifyMask /*| SubstructureNotifyMask*/ | ExposureMask |
KeyReleaseMask | KeyPressMask | KeymapStateMask | PointerMotionMask |
FocusChangeMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask |
LeaveWindowMask | PropertyChangeMask;
win_visual = GLContext_SelectVisual(mode);
Platform_LogConst("Opening render window... ");
attributes.colormap = XCreateColormap(win_display, win_rootWin, win_visual.visual, AllocNone);
attributes.event_mask = win_eventMask;
win_handle = XCreateWindow(win_display, win_rootWin, x, y, width, height,
0, win_visual.depth /* CopyFromParent*/, InputOutput, win_visual.visual,
CWColormap | CWEventMask | CWBackPixel | CWBorderPixel, &attributes);
if (!win_handle) Logger_Abort("XCreateWindow failed");
hints.base_width = width;
hints.base_height = height;
hints.flags = PSize | PPosition;
XSetWMNormalHints(win_display, win_handle, &hints);
/* Register for window destroy notification */
Atom atoms[1] = { wm_destroy };
XSetWMProtocols(win_display, win_handle, atoms, 1);
/* Set the initial window size to ensure X, Y, Width, Height and the rest
return the correct values inside the constructor and the Load event. */
XEvent e;
e.xconfigure.x = x;
e.xconfigure.y = y;
e.xconfigure.width = width;
e.xconfigure.height = height;
Window_RefreshBounds(&e.xconfigure);
/* Request that auto-repeat is only set on devices that support it physically.
This typically means that it's turned off for keyboards (which is what we want).
We prefer this method over XAutoRepeatOff/On, because the latter needs to
be reset before the program exits. */
XkbSetDetectableAutoRepeat(win_display, true, &supported);
Window_Exists = true;
}
void Window_SetTitle(const String* title) {
char str[600];
Platform_ConvertString(str, title);
XStoreName(win_display, win_handle, str);
}
static char clipboard_copy_buffer[256];
static char clipboard_paste_buffer[256];
static String clipboard_copy_text = String_FromArray(clipboard_copy_buffer);
static String clipboard_paste_text = String_FromArray(clipboard_paste_buffer);
void Window_GetClipboardText(String* value) {
Window owner = XGetSelectionOwner(win_display, xa_clipboard);
int i;
if (!owner) return; /* no window owner */
XConvertSelection(win_display, xa_clipboard, xa_utf8_string, xa_data_sel, win_handle, 0);
clipboard_paste_text.length = 0;
/* wait up to 1 second for SelectionNotify event to arrive */
for (i = 0; i < 100; i++) {
Window_ProcessEvents();
if (clipboard_paste_text.length) {
String_Copy(value, &clipboard_paste_text);
return;
} else {
Thread_Sleep(10);
}
}
}
void Window_SetClipboardText(const String* value) {
String_Copy(&clipboard_copy_text, value);
XSetSelectionOwner(win_display, xa_clipboard, win_handle, 0);
}
bool Window_GetVisible(void) {
XWindowAttributes attr;
XGetWindowAttributes(win_display, win_handle, &attr);
return attr.map_state == IsViewable;
}
void Window_SetVisible(bool visible) {
if (visible) {
XMapWindow(win_display, win_handle);
} else {
XUnmapWindow(win_display, win_handle);
}
}
void* Window_GetWindowHandle(void) { return win_handle; }
int Window_GetWindowState(void) {
Atom prop_type;
unsigned long items, after;
int prop_format;
Atom* data = NULL;
XGetWindowProperty(win_display, win_handle,
net_wm_state, 0, 256, false, xa_atom, &prop_type,
&prop_format, &items, &after, &data);
bool fullscreen = false, minimised = false;
int maximised = 0, i;
/* TODO: Check this works right */
if (data && items) {
for (i = 0; i < items; i++) {
Atom atom = data[i];
if (atom == net_wm_state_maximized_horizontal ||
atom == net_wm_state_maximized_vertical) {
maximised++;
} else if (atom == net_wm_state_minimized) {
minimised = true;
} else if (atom == net_wm_state_fullscreen) {
fullscreen = true;
}
}
}