-
Notifications
You must be signed in to change notification settings - Fork 1
/
gral_windows.cpp
1511 lines (1375 loc) · 53.4 KB
/
gral_windows.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
/*
Copyright (c) 2016-2024 Elias Aebi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "gral.h"
#define UNICODE
#define _UNICODE
#include <Windows.h>
#include <windowsx.h>
#include <strsafe.h>
#include <d2d1.h>
#include <wincodec.h>
#include <dwrite.h>
#include <stdlib.h>
#include <mmdeviceapi.h>
#include <audioclient.h>
#include <mfapi.h>
#include <mferror.h>
#include <mftransform.h>
#include <wmcodecdsp.h>
template <class T> class ComPointer {
T *pointer;
public:
ComPointer(): pointer(NULL) {}
ComPointer(ComPointer const &com_pointer): pointer(com_pointer.pointer) {
if (pointer) {
pointer->AddRef();
}
}
~ComPointer() {
if (pointer) {
pointer->Release();
}
}
ComPointer &operator =(ComPointer const &com_pointer) {
if (pointer) {
pointer->Release();
}
pointer = com_pointer.pointer;
if (pointer) {
pointer->AddRef();
}
return *this;
}
T **operator &() {
return &pointer;
}
operator T *() const {
return pointer;
}
T *operator ->() const {
return pointer;
}
};
template <class T> class Buffer {
size_t length;
T *data;
public:
Buffer(size_t length): length(length), data(new T[length]) {}
Buffer(Buffer const &buffer): length(buffer.length), data(new T[length]) {
for (size_t i = 0; i < length; i++) {
data[i] = buffer.data[i];
}
}
~Buffer() {
delete[] data;
}
Buffer &operator =(Buffer const &buffer) {
if (buffer.length != length) {
delete[] data;
length = buffer.length;
data = new T[length];
}
for (size_t i = 0; i < length; i++) {
data[i] = buffer.data[i];
}
return *this;
}
size_t get_length() const {
return length;
}
operator T *() const {
return data;
}
};
static Buffer<wchar_t> utf8_to_utf16(char const *utf8) {
int length = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
Buffer<wchar_t> utf16(length);
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, utf16, length);
return utf16;
}
static Buffer<char> utf16_to_utf8(wchar_t const *utf16) {
int length = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL, 0, NULL, NULL);
Buffer<char> utf8(length);
WideCharToMultiByte(CP_UTF8, 0, utf16, -1, utf8, length, NULL, NULL);
return utf8;
}
static UINT32 get_next_code_point(wchar_t const *utf16, UINT32 i, UINT32 *code_point) {
if ((utf16[i] & 0xFC00) == 0xD800) {
*code_point = (((utf16[i] & 0x03FF) << 10) | (utf16[i+1] & 0x03FF)) + 0x10000;
return 2;
}
else {
*code_point = utf16[i];
return 1;
}
}
static UINT32 utf8_index_to_utf16(wchar_t const *utf16, int index) {
int i8 = 0;
UINT32 i16 = 0;
while (i8 < index) {
UINT32 c; // UTF-32 code point
i16 += get_next_code_point(utf16, i16, &c);
if (c <= 0x7F) i8 += 1;
else if (c <= 0x7FF) i8 += 2;
else if (c <= 0xFFFF) i8 += 3;
else i8 += 4;
}
return i16;
}
static int utf16_index_to_utf8(wchar_t const *utf16, UINT32 index) {
int i8 = 0;
UINT32 i16 = 0;
while (i16 < index) {
UINT32 c; // UTF-32 code point
i16 += get_next_code_point(utf16, i16, &c);
if (c <= 0x7F) i8 += 1;
else if (c <= 0x7FF) i8 += 2;
else if (c <= 0xFFFF) i8 += 3;
else i8 += 4;
}
return i8;
}
static HINSTANCE hInstance;
static ID2D1Factory *factory;
static ID2D1StrokeStyle *stroke_style;
static IWICImagingFactory *imaging_factory;
static IDWriteFactory *dwrite_factory;
static DWORD main_thread_id;
static int window_count = 0;
struct gral_draw_context {
ID2D1HwndRenderTarget *target;
ID2D1PathGeometry *path;
ID2D1GeometrySink *sink;
bool open;
gral_draw_context(): open(false) {}
};
struct gral_image {
int width;
int height;
void *data;
gral_image(int width, int height, void *data): width(width), height(height), data(data) {}
};
struct gral_text {
ComPointer<IDWriteTextLayout> layout;
Buffer<wchar_t> utf16;
gral_text(Buffer<wchar_t> const &utf16): utf16(utf16) {}
};
static void adjust_window_size(int &width, int &height) {
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = width;
rect.bottom = height;
AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
width = rect.right - rect.left;
height = rect.bottom - rect.top;
}
struct WindowData {
gral_window_interface const *iface;
void *user_data;
ID2D1HwndRenderTarget *target;
bool mouse_inside;
int minimum_width, minimum_height;
HCURSOR cursor;
bool is_pointer_locked;
POINT locked_pointer;
WindowData(): mouse_inside(false), minimum_width(0), minimum_height(0), is_pointer_locked(false) {}
};
struct gral_timer {
void (*callback)(void *user_data);
void *user_data;
HANDLE timer;
};
/*================
APPLICATION
================*/
struct gral_application {
gral_application_interface const *iface;
void *user_data;
};
static int get_key(UINT virtual_key, UINT scan_code) {
switch (virtual_key) {
case VK_RETURN:
return GRAL_KEY_ENTER;
case VK_TAB:
return GRAL_KEY_TAB;
case VK_BACK:
return GRAL_KEY_BACKSPACE;
case VK_DELETE:
return GRAL_KEY_DELETE;
case VK_LEFT:
return GRAL_KEY_ARROW_LEFT;
case VK_UP:
return GRAL_KEY_ARROW_UP;
case VK_RIGHT:
return GRAL_KEY_ARROW_RIGHT;
case VK_DOWN:
return GRAL_KEY_ARROW_DOWN;
case VK_PRIOR:
return GRAL_KEY_PAGE_UP;
case VK_NEXT:
return GRAL_KEY_PAGE_DOWN;
case VK_HOME:
return GRAL_KEY_HOME;
case VK_END:
return GRAL_KEY_END;
case VK_ESCAPE:
return GRAL_KEY_ESCAPE;
default:
{
BYTE keyboard_state[256];
GetKeyboardState(keyboard_state);
keyboard_state[VK_SHIFT] = 0;
keyboard_state[VK_CONTROL] = 0;
keyboard_state[VK_MENU] = 0;
keyboard_state[VK_LSHIFT] = 0;
keyboard_state[VK_RSHIFT] = 0;
keyboard_state[VK_LCONTROL] = 0;
keyboard_state[VK_RCONTROL] = 0;
keyboard_state[VK_LMENU] = 0;
keyboard_state[VK_RMENU] = 0;
WCHAR utf16[5];
if (ToUnicode(virtual_key, scan_code, keyboard_state, utf16, 5, 0) > 0) {
UINT32 code_point;
get_next_code_point(utf16, 0, &code_point);
return code_point;
}
return 0;
}
}
}
int get_modifiers() {
int modifiers = 0;
if (GetKeyState(VK_CONTROL) < 0) modifiers |= GRAL_MODIFIER_CONTROL;
if (GetKeyState(VK_MENU) < 0) modifiers |= GRAL_MODIFIER_ALT;
if (GetKeyState(VK_SHIFT) < 0) modifiers |= GRAL_MODIFIER_SHIFT;
return modifiers;
}
static LRESULT CALLBACK window_procedure(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
WindowData *window_data = (WindowData *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
switch (uMsg) {
case WM_PAINT:
{
if (window_data->target == NULL) {
RECT rc;
GetClientRect(hwnd, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
factory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hwnd, size, D2D1_PRESENT_OPTIONS_RETAIN_CONTENTS), &window_data->target);
}
RECT update_rect;
GetUpdateRect(hwnd, &update_rect, FALSE);
gral_draw_context draw_context;
draw_context.target = window_data->target;
factory->CreatePathGeometry(&draw_context.path);
draw_context.path->Open(&draw_context.sink);
draw_context.sink->SetFillMode(D2D1_FILL_MODE_WINDING);
draw_context.target->BeginDraw();
draw_context.target->PushAxisAlignedClip(D2D1::RectF((FLOAT)update_rect.left, (FLOAT)update_rect.top, (FLOAT)update_rect.right, (FLOAT)update_rect.bottom), D2D1_ANTIALIAS_MODE_ALIASED);
draw_context.target->Clear(D2D1::ColorF(D2D1::ColorF::White));
window_data->iface->draw(&draw_context, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, window_data->user_data);
draw_context.target->PopAxisAlignedClip();
if (draw_context.target->EndDraw() == D2DERR_RECREATE_TARGET) {
draw_context.target->Release();
window_data->target = NULL;
}
draw_context.sink->Release();
draw_context.path->Release();
ValidateRect(hwnd, NULL);
return 0;
}
case WM_MOUSEMOVE:
{
if (window_data->is_pointer_locked) {
POINT point;
GetCursorPos(&point);
if (point.x != window_data->locked_pointer.x || point.y != window_data->locked_pointer.y) {
window_data->iface->mouse_move_relative((float)(point.x - window_data->locked_pointer.x), (float)(point.y - window_data->locked_pointer.y), window_data->user_data);
SetCursorPos(window_data->locked_pointer.x, window_data->locked_pointer.y);
}
}
else {
if (!window_data->mouse_inside) {
SetCursor(window_data->cursor);
window_data->mouse_inside = true;
window_data->iface->mouse_enter(window_data->user_data);
TRACKMOUSEEVENT track_mouse_event;
track_mouse_event.cbSize = sizeof(TRACKMOUSEEVENT);
track_mouse_event.dwFlags = TME_LEAVE;
track_mouse_event.hwndTrack = hwnd;
TrackMouseEvent(&track_mouse_event);
}
window_data->iface->mouse_move((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), window_data->user_data);
}
return 0;
}
case WM_MOUSELEAVE:
{
window_data->iface->mouse_leave(window_data->user_data);
window_data->mouse_inside = false;
return 0;
}
case WM_LBUTTONDOWN:
{
SetCapture(hwnd);
window_data->iface->mouse_button_press((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_PRIMARY_MOUSE_BUTTON, get_modifiers(), window_data->user_data);
return 0;
}
case WM_MBUTTONDOWN:
{
SetCapture(hwnd);
window_data->iface->mouse_button_press((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_MIDDLE_MOUSE_BUTTON, get_modifiers(), window_data->user_data);
return 0;
}
case WM_RBUTTONDOWN:
{
SetCapture(hwnd);
window_data->iface->mouse_button_press((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_SECONDARY_MOUSE_BUTTON, get_modifiers(), window_data->user_data);
return 0;
}
case WM_LBUTTONUP:
{
if ((wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) == 0) {
ReleaseCapture();
}
window_data->iface->mouse_button_release((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_PRIMARY_MOUSE_BUTTON, window_data->user_data);
return 0;
}
case WM_MBUTTONUP:
{
if ((wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) == 0) {
ReleaseCapture();
}
window_data->iface->mouse_button_release((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_MIDDLE_MOUSE_BUTTON, window_data->user_data);
return 0;
}
case WM_RBUTTONUP:
{
if ((wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) == 0) {
ReleaseCapture();
}
window_data->iface->mouse_button_release((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_SECONDARY_MOUSE_BUTTON, window_data->user_data);
return 0;
}
case WM_LBUTTONDBLCLK:
{
SetCapture(hwnd);
int modifiers = get_modifiers();
window_data->iface->mouse_button_press((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_PRIMARY_MOUSE_BUTTON, modifiers, window_data->user_data);
window_data->iface->double_click((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_PRIMARY_MOUSE_BUTTON, modifiers, window_data->user_data);
return 0;
}
case WM_MBUTTONDBLCLK:
{
SetCapture(hwnd);
int modifiers = get_modifiers();
window_data->iface->mouse_button_press((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_MIDDLE_MOUSE_BUTTON, modifiers, window_data->user_data);
window_data->iface->double_click((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_MIDDLE_MOUSE_BUTTON, modifiers, window_data->user_data);
return 0;
}
case WM_RBUTTONDBLCLK:
{
SetCapture(hwnd);
int modifiers = get_modifiers();
window_data->iface->mouse_button_press((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_SECONDARY_MOUSE_BUTTON, modifiers, window_data->user_data);
window_data->iface->double_click((float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam), GRAL_SECONDARY_MOUSE_BUTTON, modifiers, window_data->user_data);
return 0;
}
case WM_MOUSEWHEEL:
window_data->iface->scroll(0.0f, (float)GET_WHEEL_DELTA_WPARAM(wParam)/(float)WHEEL_DELTA, window_data->user_data);
return 0;
case WM_MOUSEHWHEEL:
window_data->iface->scroll(-(float)GET_WHEEL_DELTA_WPARAM(wParam)/(float)WHEEL_DELTA, 0.0f, window_data->user_data);
return 0;
case WM_KEYDOWN:
{
UINT scan_code = (lParam >> 16) & 0xFF;
int key = get_key((UINT)wParam, scan_code);
if (key) {
window_data->iface->key_press(key, scan_code, get_modifiers(), window_data->user_data);
}
return 0;
}
case WM_KEYUP:
{
UINT scan_code = (lParam >> 16) & 0xFF;
int key = get_key((UINT)wParam, scan_code);
if (key) {
window_data->iface->key_release(key, scan_code, window_data->user_data);
}
return 0;
}
case WM_CHAR:
{
static WCHAR utf16[3];
if ((wParam & 0xFC00) == 0xD800) {
// high surrogate
utf16[0] = (WCHAR)wParam;
}
else {
if ((wParam & 0xFC00) == 0xDC00) {
// low surrogate
utf16[1] = (WCHAR)wParam;
utf16[2] = 0;
}
else {
utf16[0] = (WCHAR)wParam;
utf16[1] = 0;
}
CHAR utf8[5];
WideCharToMultiByte(CP_UTF8, 0, utf16, -1, utf8, 5, NULL, NULL);
if ((UCHAR)utf8[0] > 0x1F) {
window_data->iface->text(utf8, window_data->user_data);
}
}
return 0;
}
case WM_SETFOCUS:
window_data->iface->focus_enter(window_data->user_data);
return 0;
case WM_KILLFOCUS:
window_data->iface->focus_leave(window_data->user_data);
return 0;
case WM_SIZE:
{
WORD width = LOWORD(lParam);
WORD height = HIWORD(lParam);
window_data->iface->resize(width, height, window_data->user_data);
if (window_data->target) {
window_data->target->Resize(D2D1::SizeU(width, height));
}
RedrawWindow(hwnd, NULL, NULL, RDW_ERASE|RDW_INVALIDATE);
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
case WM_GETMINMAXINFO:
{
if (window_data) {
MINMAXINFO *mmi = (MINMAXINFO *)lParam;
mmi->ptMinTrackSize.x = window_data->minimum_width;
mmi->ptMinTrackSize.y = window_data->minimum_height;
}
return 0;
}
case WM_CLOSE:
{
if (window_data->iface->close(window_data->user_data)) {
DestroyWindow(hwnd);
}
return 0;
}
case WM_DESTROY:
{
window_data->iface->destroy(window_data->user_data);
if (window_data->target) {
window_data->target->Release();
}
delete window_data;
window_count--;
if (window_count == 0) {
PostQuitMessage(0);
}
return 0;
}
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
gral_application *gral_application_create(char const *id, gral_application_interface const *iface, void *user_data) {
hInstance = GetModuleHandle(NULL);
CoInitialize(NULL);
D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &factory);
factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND), NULL, 0, &stroke_style);
CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&imaging_factory));
DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), (IUnknown **)&dwrite_factory);
WNDCLASS window_class;
window_class.style = CS_DBLCLKS;
window_class.lpfnWndProc = &window_procedure;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hInstance = hInstance;
window_class.hIcon = NULL;
window_class.hCursor = NULL;
window_class.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
window_class.lpszMenuName = NULL;
window_class.lpszClassName = L"gral_window";
RegisterClass(&window_class);
static gral_application application;
application.iface = iface;
application.user_data = user_data;
return &application;
}
void gral_application_delete(gral_application *application) {
factory->Release();
stroke_style->Release();
imaging_factory->Release();
dwrite_factory->Release();
CoUninitialize();
}
int gral_application_run(gral_application *application, int argc_, char **argv_) {
main_thread_id = GetCurrentThreadId();
application->iface->start(application->user_data);
int argc;
LPWSTR *argv = CommandLineToArgvW(GetCommandLine(), &argc);
if (argc > 1) {
for (int i = 1; i < argc; i++) {
application->iface->open_file(utf16_to_utf8(argv[i]), application->user_data);
}
}
else {
application->iface->open_empty(application->user_data);
}
LocalFree(argv);
MSG message;
while (TRUE) {
while (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) {
if (message.message == WM_QUIT) {
application->iface->quit(application->user_data);
return 0;
}
TranslateMessage(&message);
DispatchMessage(&message);
}
MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_ALLINPUT, MWMO_ALERTABLE);
}
}
/*============
DRAWING
============*/
class ColorDrawingEffect: public IUnknown {
ULONG reference_count;
D2D1_COLOR_F color;
public:
ColorDrawingEffect(D2D1_COLOR_F const &color): reference_count(1), color(color) {}
D2D1_COLOR_F const &get_color() const {
return color;
}
IFACEMETHOD(QueryInterface)(REFIID riid, void **ppvObject) {
if (riid == __uuidof(IUnknown)) {
*ppvObject = this;
AddRef();
return S_OK;
}
else {
*ppvObject = NULL;
return E_NOINTERFACE;
}
}
IFACEMETHOD_(ULONG, AddRef)() {
return InterlockedIncrement(&reference_count);
}
IFACEMETHOD_(ULONG, Release)() {
ULONG new_reference_count = InterlockedDecrement(&reference_count);
if (new_reference_count == 0) {
delete this;
}
return new_reference_count;
}
};
class GralTextRenderer: public IDWriteTextRenderer {
ULONG reference_count;
ComPointer<ID2D1SolidColorBrush> brush;
public:
GralTextRenderer(ComPointer<ID2D1SolidColorBrush> const &brush): reference_count(1), brush(brush) {}
IFACEMETHOD(DrawGlyphRun)(void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE measuringMode, DWRITE_GLYPH_RUN const *glyphRun, DWRITE_GLYPH_RUN_DESCRIPTION const *glyphRunDescription, IUnknown *clientDrawingEffect) {
gral_draw_context *draw_context = (gral_draw_context *)clientDrawingContext;
if (brush) {
if (clientDrawingEffect) {
ColorDrawingEffect *color_drawing_effect = (ColorDrawingEffect *)clientDrawingEffect;
ComPointer<ID2D1SolidColorBrush> effect_brush;
draw_context->target->CreateSolidColorBrush(color_drawing_effect->get_color(), &effect_brush);
draw_context->target->DrawGlyphRun(D2D1::Point2F(baselineOriginX, baselineOriginY), glyphRun, effect_brush, measuringMode);
}
else {
draw_context->target->DrawGlyphRun(D2D1::Point2F(baselineOriginX, baselineOriginY), glyphRun, brush, measuringMode);
}
}
else {
ComPointer<ID2D1PathGeometry> path;
factory->CreatePathGeometry(&path);
ComPointer<ID2D1GeometrySink> sink;
path->Open(&sink);
glyphRun->fontFace->GetGlyphRunOutline(glyphRun->fontEmSize, glyphRun->glyphIndices, glyphRun->glyphAdvances, glyphRun->glyphOffsets, glyphRun->glyphCount, glyphRun->isSideways, glyphRun->bidiLevel % 2, sink);
sink->Close();
if (draw_context->open) {
draw_context->sink->EndFigure(D2D1_FIGURE_END_OPEN);
draw_context->open = false;
}
path->Outline(D2D1::Matrix3x2F(1.0f, 0.0f, 0.0f, 1.0f, baselineOriginX, baselineOriginY), draw_context->sink);
draw_context->sink->SetFillMode(D2D1_FILL_MODE_WINDING);
}
return S_OK;
}
IFACEMETHOD(DrawInlineObject)(void *clientDrawingContext, FLOAT originX, FLOAT originY, IDWriteInlineObject *inlineObject, BOOL isSideways, BOOL isRightToLeft, IUnknown *clientDrawingEffect) {
// TODO: implement
return S_OK;
}
IFACEMETHOD(DrawStrikethrough)(void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_STRIKETHROUGH const *strikethrough, IUnknown *clientDrawingEffect) {
// TODO: implement
return S_OK;
}
IFACEMETHOD(DrawUnderline)(void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_UNDERLINE const *underline, IUnknown *clientDrawingEffect) {
// TODO: implement
return S_OK;
}
IFACEMETHOD(IsPixelSnappingDisabled)(void *clientDrawingContext, BOOL *isDisabled) {
*isDisabled = FALSE;
return S_OK;
}
IFACEMETHOD(GetCurrentTransform)(void *clientDrawingContext, DWRITE_MATRIX *transform) {
gral_draw_context *draw_context = (gral_draw_context *)clientDrawingContext;
draw_context->target->GetTransform((D2D1_MATRIX_3X2_F *)transform);
return S_OK;
}
IFACEMETHOD(GetPixelsPerDip)(void *clientDrawingContext, FLOAT *pixelsPerDip) {
*pixelsPerDip = 1.0f;
return S_OK;
}
IFACEMETHOD(QueryInterface)(REFIID riid, void **ppvObject) {
if (riid == __uuidof(IDWriteTextRenderer) || riid == __uuidof(IDWritePixelSnapping) || riid == __uuidof(IUnknown)) {
*ppvObject = this;
AddRef();
return S_OK;
}
else {
*ppvObject = NULL;
return E_NOINTERFACE;
}
}
IFACEMETHOD_(ULONG, AddRef)() {
return InterlockedIncrement(&reference_count);
}
IFACEMETHOD_(ULONG, Release)() {
ULONG new_reference_count = InterlockedDecrement(&reference_count);
if (new_reference_count == 0) {
delete this;
}
return new_reference_count;
}
};
gral_image *gral_image_create(int width, int height, void *data) {
return new gral_image(width, height, data);
}
void gral_image_delete(gral_image *image) {
free(image->data);
delete image;
}
static gral_font *create_font(WCHAR const *name, float size) {
WCHAR locale_name[LOCALE_NAME_MAX_LENGTH];
GetUserDefaultLocaleName(locale_name, LOCALE_NAME_MAX_LENGTH);
IDWriteTextFormat *format;
dwrite_factory->CreateTextFormat(name, NULL, DWRITE_FONT_WEIGHT_REGULAR, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, size, locale_name, &format);
return (gral_font *)format;
}
gral_font *gral_font_create(gral_window *window, char const *name, float size) {
return create_font(utf8_to_utf16(name), size);
}
gral_font *gral_font_create_default(gral_window *window, float size) {
NONCLIENTMETRICS ncm;
ncm.cbSize = sizeof(NONCLIENTMETRICS);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0);
return create_font(ncm.lfMessageFont.lfFaceName, size);
}
gral_font *gral_font_create_monospace(gral_window *window, float size) {
return create_font(L"Consolas", size);
}
void gral_font_delete(gral_font *font) {
IDWriteTextFormat *format = (IDWriteTextFormat *)font;
format->Release();
}
void gral_font_get_metrics(gral_window *window, gral_font *font, float *ascent, float *descent) {
IDWriteTextFormat *format = (IDWriteTextFormat *)font;
UINT32 name_length = format->GetFontFamilyNameLength();
Buffer<WCHAR> name(name_length + 1);
format->GetFontFamilyName(name, name_length + 1);
ComPointer<IDWriteFontCollection> font_collection;
format->GetFontCollection(&font_collection);
UINT32 index;
BOOL exists;
font_collection->FindFamilyName(name, &index, &exists);
ComPointer<IDWriteFontFamily> font_family;
font_collection->GetFontFamily(index, &font_family);
ComPointer<IDWriteFont> dwrite_font;
font_family->GetFirstMatchingFont(DWRITE_FONT_WEIGHT_REGULAR, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL, &dwrite_font);
DWRITE_FONT_METRICS metrics;
dwrite_font->GetMetrics(&metrics);
if (ascent) *ascent = (float)metrics.ascent / (float)metrics.designUnitsPerEm * format->GetFontSize();
if (descent) *descent = (float)metrics.descent / (float)metrics.designUnitsPerEm * format->GetFontSize();
}
gral_text *gral_text_create(gral_window *window, char const *utf8, gral_font *font) {
IDWriteTextFormat *format = (IDWriteTextFormat *)font;
gral_text *text = new gral_text(utf8_to_utf16(utf8));
dwrite_factory->CreateTextLayout(text->utf16, (UINT32)text->utf16.get_length(), format, 1.0e30f, 1.0e30f, &text->layout);
return text;
}
void gral_text_delete(gral_text *text) {
delete text;
}
void gral_text_set_bold(gral_text *text, int start_index, int end_index) {
DWRITE_TEXT_RANGE range;
range.startPosition = utf8_index_to_utf16(text->utf16, start_index);
range.length = utf8_index_to_utf16(text->utf16, end_index) - range.startPosition;
text->layout->SetFontWeight(DWRITE_FONT_WEIGHT_BOLD, range);
}
void gral_text_set_italic(gral_text *text, int start_index, int end_index) {
DWRITE_TEXT_RANGE range;
range.startPosition = utf8_index_to_utf16(text->utf16, start_index);
range.length = utf8_index_to_utf16(text->utf16, end_index) - range.startPosition;
text->layout->SetFontStyle(DWRITE_FONT_STYLE_ITALIC, range);
}
void gral_text_set_color(gral_text *text, int start_index, int end_index, float red, float green, float blue, float alpha) {
DWRITE_TEXT_RANGE range;
range.startPosition = utf8_index_to_utf16(text->utf16, start_index);
range.length = utf8_index_to_utf16(text->utf16, end_index) - range.startPosition;
ComPointer<ColorDrawingEffect> drawing_effect;
*&drawing_effect = new ColorDrawingEffect(D2D1::ColorF(red, green, blue, alpha));
text->layout->SetDrawingEffect(drawing_effect, range);
}
float gral_text_get_width(gral_text *text, gral_draw_context *draw_context) {
DWRITE_TEXT_METRICS metrics;
text->layout->GetMetrics(&metrics);
return metrics.width;
}
float gral_text_index_to_x(gral_text *text, int index) {
float x, y;
DWRITE_HIT_TEST_METRICS metrics;
text->layout->HitTestTextPosition(utf8_index_to_utf16(text->utf16, index), false, &x, &y, &metrics);
return x;
}
int gral_text_x_to_index(gral_text *text, float x) {
BOOL trailing, inside;
DWRITE_HIT_TEST_METRICS metrics;
text->layout->HitTestPoint(x, 0.0f, &trailing, &inside, &metrics);
return utf16_index_to_utf8(text->utf16, inside && trailing ? metrics.textPosition + metrics.length : metrics.textPosition);
}
void gral_draw_context_draw_image(gral_draw_context *draw_context, gral_image *image, float x, float y) {
ComPointer<IWICBitmap> source_bitmap;
imaging_factory->CreateBitmapFromMemory(image->width, image->height, GUID_WICPixelFormat32bppRGBA, image->width * 4, image->width * image->height * 4, (PBYTE)image->data, &source_bitmap);
ComPointer<IWICFormatConverter> format_converter;
imaging_factory->CreateFormatConverter(&format_converter);
format_converter->Initialize(source_bitmap, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, NULL, 0.0, WICBitmapPaletteTypeCustom);
ComPointer<ID2D1Bitmap> bitmap;
draw_context->target->CreateBitmapFromWicBitmap(format_converter, &bitmap);
draw_context->target->DrawBitmap(bitmap, D2D1::RectF(x, y, x + image->width, y + image->height), 1.0f, D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, D2D1::RectF(0.0f, 0.0f, (FLOAT)image->width, (FLOAT)image->height));
}
void gral_draw_context_draw_text(gral_draw_context *draw_context, gral_text *text, float x, float y, float red, float green, float blue, float alpha) {
DWRITE_LINE_METRICS line_metrics;
UINT32 count = 1;
text->layout->GetLineMetrics(&line_metrics, count, &count);
ComPointer<ID2D1SolidColorBrush> brush;
draw_context->target->CreateSolidColorBrush(D2D1::ColorF(red, green, blue, alpha), &brush);
ComPointer<GralTextRenderer> renderer;
*&renderer = new GralTextRenderer(brush);
text->layout->Draw(draw_context, renderer, x, y-line_metrics.baseline);
}
void gral_draw_context_add_text(gral_draw_context *draw_context, gral_text *text, float x, float y) {
DWRITE_LINE_METRICS line_metrics;
UINT32 count = 1;
text->layout->GetLineMetrics(&line_metrics, count, &count);
ComPointer<ID2D1SolidColorBrush> brush;
ComPointer<GralTextRenderer> renderer;
*&renderer = new GralTextRenderer(brush);
text->layout->Draw(draw_context, renderer, x, y-line_metrics.baseline);
}
void gral_draw_context_close_path(gral_draw_context *draw_context) {
draw_context->sink->EndFigure(D2D1_FIGURE_END_CLOSED);
draw_context->open = false;
}
void gral_draw_context_move_to(gral_draw_context *draw_context, float x, float y) {
D2D1_POINT_2F point = D2D1::Point2F(x, y);
if (draw_context->open) {
draw_context->sink->EndFigure(D2D1_FIGURE_END_OPEN);
}
draw_context->sink->BeginFigure(point, D2D1_FIGURE_BEGIN_FILLED);
draw_context->open = true;
}
void gral_draw_context_line_to(gral_draw_context *draw_context, float x, float y) {
D2D1_POINT_2F point = D2D1::Point2F(x, y);
draw_context->sink->AddLine(point);
}
void gral_draw_context_curve_to(gral_draw_context *draw_context, float x1, float y1, float x2, float y2, float x, float y) {
D2D1_POINT_2F point = D2D1::Point2F(x, y);
draw_context->sink->AddBezier(D2D1::BezierSegment(D2D1::Point2F(x1, y1), D2D1::Point2F(x2, y2), point));
}
static ComPointer<ID2D1LinearGradientBrush> create_linear_gradient_brush(gral_draw_context *draw_context, float start_x, float start_y, float end_x, float end_y, gral_gradient_stop const *stops, int count) {
Buffer<D2D1_GRADIENT_STOP> gradient_stops(count);
for (int i = 0; i < count; i++) {
gradient_stops[i].position = stops[i].position;
gradient_stops[i].color = D2D1::ColorF(stops[i].red, stops[i].green, stops[i].blue, stops[i].alpha);
}
ComPointer<ID2D1GradientStopCollection> gradient_stop_collection;
draw_context->target->CreateGradientStopCollection(gradient_stops, count, &gradient_stop_collection);
ComPointer<ID2D1LinearGradientBrush> brush;
draw_context->target->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties(D2D1::Point2F(start_x, start_y), D2D1::Point2F(end_x, end_y)), gradient_stop_collection, &brush);
return brush;
}
void gral_draw_context_fill(gral_draw_context *draw_context, float red, float green, float blue, float alpha) {
if (draw_context->open) {
draw_context->sink->EndFigure(D2D1_FIGURE_END_OPEN);
draw_context->open = false;
}
draw_context->sink->Close();
ComPointer<ID2D1SolidColorBrush> brush;
draw_context->target->CreateSolidColorBrush(D2D1::ColorF(red, green, blue, alpha), &brush);
draw_context->target->FillGeometry(draw_context->path, brush);
draw_context->sink->Release();
draw_context->path->Release();
factory->CreatePathGeometry(&draw_context->path);
draw_context->path->Open(&draw_context->sink);
draw_context->sink->SetFillMode(D2D1_FILL_MODE_WINDING);
}
void gral_draw_context_fill_linear_gradient(gral_draw_context *draw_context, float start_x, float start_y, float end_x, float end_y, gral_gradient_stop const *stops, int count) {
if (draw_context->open) {
draw_context->sink->EndFigure(D2D1_FIGURE_END_OPEN);
draw_context->open = false;
}
draw_context->sink->Close();
ComPointer<ID2D1LinearGradientBrush> brush = create_linear_gradient_brush(draw_context, start_x, start_y, end_x, end_y, stops, count);
draw_context->target->FillGeometry(draw_context->path, brush);
draw_context->sink->Release();
draw_context->path->Release();
factory->CreatePathGeometry(&draw_context->path);
draw_context->path->Open(&draw_context->sink);
draw_context->sink->SetFillMode(D2D1_FILL_MODE_WINDING);
}
void gral_draw_context_stroke(gral_draw_context *draw_context, float line_width, float red, float green, float blue, float alpha) {
if (draw_context->open) {
draw_context->sink->EndFigure(D2D1_FIGURE_END_OPEN);
draw_context->open = false;
}
draw_context->sink->Close();
ComPointer<ID2D1SolidColorBrush> brush;
draw_context->target->CreateSolidColorBrush(D2D1::ColorF(red, green, blue, alpha), &brush);
draw_context->target->DrawGeometry(draw_context->path, brush, line_width, stroke_style);
draw_context->sink->Release();
draw_context->path->Release();
factory->CreatePathGeometry(&draw_context->path);
draw_context->path->Open(&draw_context->sink);
draw_context->sink->SetFillMode(D2D1_FILL_MODE_WINDING);
}
void gral_draw_context_stroke_linear_gradient(gral_draw_context *draw_context, float line_width, float start_x, float start_y, float end_x, float end_y, gral_gradient_stop const *stops, int count) {
if (draw_context->open) {
draw_context->sink->EndFigure(D2D1_FIGURE_END_OPEN);
draw_context->open = false;
}
draw_context->sink->Close();
ComPointer<ID2D1LinearGradientBrush> brush = create_linear_gradient_brush(draw_context, start_x, start_y, end_x, end_y, stops, count);
draw_context->target->DrawGeometry(draw_context->path, brush, line_width, stroke_style);
draw_context->sink->Release();
draw_context->path->Release();
factory->CreatePathGeometry(&draw_context->path);
draw_context->path->Open(&draw_context->sink);
draw_context->sink->SetFillMode(D2D1_FILL_MODE_WINDING);
}
void gral_draw_context_draw_clipped(gral_draw_context *draw_context, void (*callback)(gral_draw_context *draw_context, void *user_data), void *user_data) {
if (draw_context->open) {
draw_context->sink->EndFigure(D2D1_FIGURE_END_OPEN);
draw_context->open = false;
}
draw_context->sink->Close();
ComPointer<ID2D1Layer> layer;
draw_context->target->CreateLayer(&layer);
draw_context->target->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), draw_context->path), layer);
draw_context->sink->Release();
draw_context->path->Release();
factory->CreatePathGeometry(&draw_context->path);
draw_context->path->Open(&draw_context->sink);
draw_context->sink->SetFillMode(D2D1_FILL_MODE_WINDING);
callback(draw_context, user_data);
draw_context->target->PopLayer();
}
void gral_draw_context_draw_transformed(gral_draw_context *draw_context, float a, float b, float c, float d, float e, float f, void (*callback)(gral_draw_context *draw_context, void *user_data), void *user_data) {
D2D1_MATRIX_3X2_F matrix;
draw_context->target->GetTransform(&matrix);
draw_context->target->SetTransform(D2D1::Matrix3x2F(a, b, c, d, e, f) * matrix);
callback(draw_context, user_data);
draw_context->target->SetTransform(matrix);
}
/*===========
WINDOW
===========*/
gral_window *gral_window_create(gral_application *application, int width, int height, char const *title, gral_window_interface const *iface, void *user_data) {
adjust_window_size(width, height);
HWND hwnd = CreateWindow(L"gral_window", utf8_to_utf16(title), WS_OVERLAPPEDWINDOW, 0, 0, width, height, NULL, NULL, hInstance, NULL);
WindowData *window_data = new WindowData();
window_data->iface = iface;
window_data->user_data = user_data;
window_data->target = NULL;
window_data->cursor = LoadCursor(NULL, IDC_ARROW);
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)window_data);
window_count++;
return (gral_window *)hwnd;
}
void gral_window_show(gral_window *window) {
ShowWindow((HWND)window, SW_SHOW);
}
void gral_window_set_title(gral_window *window, char const *title) {
SetWindowText((HWND)window, utf8_to_utf16(title));
}
void gral_window_request_redraw(gral_window *window, int x, int y, int width, int height) {
RECT rect;
rect.left = x;
rect.top = y;
rect.right = x + width;
rect.bottom = y + height;
InvalidateRect((HWND)window, &rect, FALSE);
}
void gral_window_set_minimum_size(gral_window *window, int minimum_width, int minimum_height) {