aboutsummaryrefslogtreecommitdiff
path: root/src/window/window.c
blob: 6927992350e4017557cffdc44ddd6ac6460bd7aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
#include "../../include/mgl/window/window.h"
#include "../../include/mgl/window/event.h"
#include "../../include/mgl/mgl.h"
#include "../../include/mgl/system/utf8.h"
#include <X11/Xutil.h>
#include <X11/cursorfont.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xrender.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <assert.h>
#include <unistd.h>

/* TODO: Handle XIM better. Set XIM position to text position on screen (for text input) and reset input when selecting a new text input, etc */

/* Should be in range [2,] */
#define MAX_STACKED_EVENTS 32

typedef struct {
    mgl_event stack[MAX_STACKED_EVENTS];
    int start;
    int end;
    int size;
} x11_events_circular_buffer;

static void x11_events_circular_buffer_init(x11_events_circular_buffer *self) {
    self->start = 0;
    self->end = 0;
    self->size = 0;
}

static bool x11_events_circular_buffer_append(x11_events_circular_buffer *self, const mgl_event *event) {
    if(self->size == MAX_STACKED_EVENTS)
        return false;

    self->stack[self->end] = *event;
    self->end = (self->end + 1) % MAX_STACKED_EVENTS;
    ++self->size;
    return true;
}

static bool x11_events_circular_buffer_pop(x11_events_circular_buffer *self, mgl_event *event) {
    if(self->size == 0)
        return false;

    *event = self->stack[self->start];
    self->start = (self->start + 1) % MAX_STACKED_EVENTS;
    --self->size;
    return true;
}

typedef struct {
    GLXContext glx_context;
    XIM xim;
    XIC xic;
    Atom clipboard_atom;
    Atom targets_atom;
    Atom text_atom;
    Atom utf8_string_atom;
    Atom image_png;
    Atom image_jpg;
    Atom image_jpeg;
    Atom image_gif;
    Atom incr_atom;
    Cursor default_cursor;
    Cursor invisible_cursor;
    unsigned int prev_keycode_pressed;
    bool key_was_released;
    Colormap color_map;
    GLXFBConfig *fbconfigs;
    GLXFBConfig fbconfig;
    XVisualInfo *visual_info;
    /*
        Used to stack text event on top of key press/release events and other text events.
        For example pressing a key should give the user both key press and text events
        and for IM with multiple characters entered (such as chinese), we want to trigger
        an event for all of them.
    */
    x11_events_circular_buffer events;
} x11_context;

static void x11_context_deinit(x11_context *self);

static bool glx_context_choose(mgl_context *context, GLXFBConfig **fbconfigs, GLXFBConfig *fbconfig, XVisualInfo **visual_info, bool alpha) {
    const int attr[] = {
        GLX_RENDER_TYPE, GLX_RGBA_BIT,
        GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
        GLX_DOUBLEBUFFER, True,
        GLX_RED_SIZE, 8,
        GLX_GREEN_SIZE, 8,
        GLX_BLUE_SIZE, 8,
        GLX_ALPHA_SIZE, alpha ? 8 : 0,
        GLX_DEPTH_SIZE, 0,
        None
    };

    *fbconfigs = NULL;
    *visual_info = NULL;
    *fbconfig = NULL;

    int numfbconfigs = 0;
    *fbconfigs = context->gl.glXChooseFBConfig(context->connection, DefaultScreen(context->connection), attr, &numfbconfigs);
    for(int i = 0; i < numfbconfigs; i++) {
        *visual_info = (XVisualInfo*)context->gl.glXGetVisualFromFBConfig(context->connection, (*fbconfigs)[i]);
        if(!*visual_info)
            continue;

        XRenderPictFormat *pict_format = XRenderFindVisualFormat(context->connection, (*visual_info)->visual);
        if(!pict_format) {
            XFree(*visual_info);
            *visual_info = NULL;
            continue;
        }

        *fbconfig = (*fbconfigs)[i];
        if((alpha && pict_format->direct.alphaMask > 0) || (!alpha && pict_format->direct.alphaMask == 0))
            break;

        XFree(*visual_info);
        *visual_info = NULL;
        *fbconfig = NULL;
    }

    if(!*visual_info) {
        fprintf(stderr, "mgl error: no appropriate visual found\n");
        return false;
    }

    return true;
}

static int x11_context_init(x11_context *self, bool alpha) {
    mgl_context *context = mgl_get_context();

    self->glx_context = NULL;
    self->xim = NULL;
    self->xic = NULL;
    self->clipboard_atom = XInternAtom(context->connection, "CLIPBOARD", False);
    self->targets_atom = XInternAtom(context->connection, "TARGETS", False);
    self->text_atom = XInternAtom(context->connection, "TEXT", False);
    self->utf8_string_atom = XInternAtom(context->connection, "UTF8_STRING", False);
    self->image_png = XInternAtom(context->connection, "image/png", False);
    self->image_jpg = XInternAtom(context->connection, "image/jpg", False);
    self->image_jpeg = XInternAtom(context->connection, "image/jpeg", False);
    self->image_gif = XInternAtom(context->connection, "image/gif", False);
    self->incr_atom = XInternAtom(context->connection, "INCR", False);
    self->default_cursor = None;
    self->invisible_cursor = None;

    self->prev_keycode_pressed = 0;
    self->key_was_released = false;
    self->color_map = None;

    self->fbconfigs = NULL;
    self->fbconfig = NULL;
    self->visual_info = NULL;

    if(!glx_context_choose(context, &self->fbconfigs, &self->fbconfig, &self->visual_info, alpha)) {
        x11_context_deinit(self);
        return -1;
    }

    self->default_cursor = XCreateFontCursor(context->connection, XC_arrow);
    if(!self->default_cursor) {
        x11_context_deinit(self);
        return -1;
    }

    const char data[1] = {0};
    Pixmap blank_bitmap = XCreateBitmapFromData(context->connection, DefaultRootWindow(context->connection), data, 1, 1);
    if(!blank_bitmap)
        return -1;

    XColor dummy;
    self->invisible_cursor = XCreatePixmapCursor(context->connection, blank_bitmap, blank_bitmap, &dummy, &dummy, 0, 0);
    XFreePixmap(context->connection, blank_bitmap);
    if(!self->invisible_cursor) {
        x11_context_deinit(self);
        return -1;
    }
    
    x11_events_circular_buffer_init(&self->events);

    return 0;
}

void x11_context_deinit(x11_context *self) {
    mgl_context *context = mgl_get_context();

    if(self->color_map) {
        XFreeColormap(context->connection, self->color_map);
        self->color_map = None;
    }

    if(self->invisible_cursor) {
        XFreeCursor(context->connection, self->invisible_cursor);
        self->invisible_cursor = None;
    }

    if(self->default_cursor) {
        XFreeCursor(context->connection, self->default_cursor);
        self->default_cursor = None;
    }

    if(self->xic) {
        XDestroyIC(self->xic);
        self->xic = NULL;
    }

    if(self->xim) {
        XCloseIM(self->xim);
        self->xim = NULL;
    }

    if(self->glx_context) {
        context->gl.glXDestroyContext(context->connection, self->glx_context);
        self->glx_context = NULL;
    }

    if(self->visual_info) {
        XFree(self->visual_info);
        self->visual_info = NULL;
    }

    if(self->fbconfigs) {
        XFree(self->fbconfigs);
        self->fbconfigs = NULL;
    }

    self->fbconfig = NULL;
}

static bool x11_context_append_event(x11_context *self, const mgl_event *event) {
    return x11_events_circular_buffer_append(&self->events, event);
}

static bool x11_context_pop_event(x11_context *self, mgl_event *event) {
    return x11_events_circular_buffer_pop(&self->events, event);
}

/* TODO: Use gl OML present for other platforms than nvidia? nvidia doesn't support present yet */

/* TODO: check for glx swap control extension string (GLX_EXT_swap_control, etc) */
static void set_vertical_sync_enabled(Window window, int enabled) {
    int result = 0;
    mgl_context *context = mgl_get_context();

    if(context->gl.glXSwapIntervalEXT) {
        context->gl.glXSwapIntervalEXT(context->connection, window, enabled ? 1 : 0);
    } else if(context->gl.glXSwapIntervalMESA) {
        result = context->gl.glXSwapIntervalMESA(enabled ? 1 : 0);
    } else if(context->gl.glXSwapIntervalSGI) {
        result = context->gl.glXSwapIntervalSGI(enabled ? 1 : 0);
    } else {
        static int warned = 0;
        if (!warned) {
            warned = 1;
            fprintf(stderr, "mgl warning: setting vertical sync not supported\n");
        }
    }

    if(result != 0)
        fprintf(stderr, "mgl warning: setting vertical sync failed\n");
}

static void mgl_window_on_resize(mgl_window *self, int width, int height) {
    self->size.x = width;
    self->size.y = height;

    mgl_view view;
    view.position = (mgl_vec2i){ 0, 0 };
    view.size = self->size;
    mgl_window_set_view(self, &view);
    mgl_window_set_scissor(self, &(mgl_scissor){ .position = { 0, 0 }, .size = self->size });
}

static int mgl_window_init(mgl_window *self, const char *title, const mgl_window_create_params *params, Window existing_window) {
    self->window = 0;
    self->context = NULL;
    self->open = false;
    self->focused = false;
    self->key_repeat_enabled = true;
    self->frame_time_limit = 0.0;
    mgl_clock_init(&self->frame_timer);
    self->clipboard_string = NULL;
    self->clipboard_size = 0;

    mgl_vec2i window_size = params ? params->size : (mgl_vec2i){ 0, 0 };
    if(window_size.x <= 0 || window_size.y <= 0) {
        window_size.x = 640;
        window_size.y = 480;
    }
    self->size = window_size;

    self->context = malloc(sizeof(x11_context));
    if(!self->context) {
        fprintf(stderr, "mgl error: failed to allocate x11 context\n");
        return -1;
    }

    x11_context *x11_context = self->context;
    if(x11_context_init(x11_context, params ? params->support_alpha : false) != 0) {
        fprintf(stderr, "mgl error: x11_context_init failed\n");
        mgl_window_deinit(self);
        return -1;
    }

    mgl_context *context = mgl_get_context();

    Window parent_window = params ? params->parent_window : None;
    if(parent_window == 0)
        parent_window = DefaultRootWindow(context->connection);

    x11_context->glx_context = context->gl.glXCreateNewContext(context->connection, x11_context->fbconfig, GLX_RGBA_TYPE, 0, True);
    if(!x11_context->glx_context) {
        fprintf(stderr, "mgl error: glXCreateContext failed\n");
        mgl_window_deinit(self);
        return -1;
    }

    x11_context->color_map = XCreateColormap(context->connection, DefaultRootWindow(context->connection), x11_context->visual_info->visual, AllocNone);
    if(!x11_context->color_map) {
        fprintf(stderr, "mgl error: XCreateColormap failed\n");
        mgl_window_deinit(self);
        return -1;
    }

    XSetWindowAttributes window_attr;
    window_attr.override_redirect = params ? params->override_redirect : false;
    window_attr.colormap = x11_context->color_map;
    window_attr.background_pixmap = None;
    window_attr.border_pixel = 0;
    window_attr.event_mask = 
        KeyPressMask | KeyReleaseMask |
        ButtonPressMask | ButtonReleaseMask |
        PointerMotionMask | Button1MotionMask | Button2MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask | ButtonMotionMask |
        StructureNotifyMask | EnterWindowMask | LeaveWindowMask | VisibilityChangeMask | PropertyChangeMask | FocusChangeMask;

    const bool hide_window = params ? params->hidden : false;

    if(existing_window) {
        if(!XChangeWindowAttributes(context->connection, existing_window, CWColormap | CWEventMask | CWOverrideRedirect | CWBorderPixel | CWBackPixmap, &window_attr)) {
            fprintf(stderr, "mgl error: XChangeWindowAttributes failed\n");
            mgl_window_deinit(self);
            return -1;
        }

        self->window = existing_window;
        if(hide_window)
            XUnmapWindow(context->connection, existing_window);
    } else {
        self->window = XCreateWindow(context->connection, parent_window, params->position.x, params->position.y,
            window_size.x, window_size.y, 0,
            x11_context->visual_info->depth, InputOutput, x11_context->visual_info->visual,
            CWColormap | CWEventMask | CWOverrideRedirect | CWBorderPixel | CWBackPixmap, &window_attr);
        if(!self->window) {
            fprintf(stderr, "mgl error: XCreateWindow failed\n");
            mgl_window_deinit(self);
            return -1;
        }

        XStoreName(context->connection, self->window, title);
        if(!hide_window)
            XMapWindow(context->connection, self->window);
    }

    if(params)
        mgl_window_set_size_limits(self, params->min_size, params->max_size);

    /* TODO: Call XGetWMProtocols and add wm_delete_window_atom on top, to not overwrite existing wm protocol atoms */
    Atom wm_protocol_atoms[2] = {
        context->wm_delete_window_atom,
        context->net_wm_ping_atom
    };
    XSetWMProtocols(context->connection, self->window, wm_protocol_atoms, 2);

    if(context->net_wm_pid_atom) {
        const long pid = getpid();
        XChangeProperty(context->connection, self->window, context->net_wm_pid_atom, XA_CARDINAL,
                        32, PropModeReplace, (const unsigned char*)&pid, 1);
    }

    XFlush(context->connection);

    /* TODO: Check for failure? */
    if(!context->gl.glXMakeContextCurrent(context->connection, self->window, self->window, x11_context->glx_context)) {
        fprintf(stderr, "mgl error: failed to make opengl context current!\n");
        mgl_window_deinit(self);
        return -1;
    }
    set_vertical_sync_enabled(self->window, 1);
    context->gl.glEnable(GL_TEXTURE_2D);
    context->gl.glEnable(GL_BLEND);
    context->gl.glEnable(GL_SCISSOR_TEST);
    context->gl.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    context->gl.glEnableClientState(GL_VERTEX_ARRAY);
    context->gl.glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    context->gl.glEnableClientState(GL_COLOR_ARRAY);
    context->gl.glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    Window dummy_w;
    int dummy_i;
    unsigned int dummy_u;
    XQueryPointer(context->connection, self->window, &dummy_w, &dummy_w, &dummy_i, &dummy_i, &self->cursor_position.x, &self->cursor_position.y, &dummy_u);

    mgl_window_on_resize(self, self->size.x, self->size.y);

    x11_context->xim = XOpenIM(context->connection, NULL, NULL, NULL);
    if(!x11_context->xim) {
        fprintf(stderr, "mgl error: XOpenIM failed\n");
        mgl_window_deinit(self);
        return -1;
    }

    x11_context->xic = XCreateIC(x11_context->xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, self->window, NULL);
    if(!x11_context->xic) {
        fprintf(stderr, "mgl error: XCreateIC failed\n");
        mgl_window_deinit(self);
        return -1;
    }

    self->open = true;
    self->focused = false; /* TODO: Check if we need to call XGetInputFocus for this, or just wait for focus event */
    return 0;
}

int mgl_window_create(mgl_window *self, const char *title, const mgl_window_create_params *params) {
    return mgl_window_init(self, title, params, None);
}

/* TODO: Test this */
int mgl_window_init_from_existing_window(mgl_window *self, mgl_window_handle existing_window) {
    return mgl_window_init(self, "", NULL, existing_window);
}

void mgl_window_deinit(mgl_window *self) {
    mgl_context *context = mgl_get_context();
    x11_context *x11_context = self->context;

    if(self->window) {
        XDestroyWindow(context->connection, self->window);
        self->window = 0;
    }

    if(x11_context) {
        x11_context_deinit(x11_context);
        free(x11_context);
        self->context = NULL;
    }

    if(self->clipboard_string) {
        free(self->clipboard_string);
        self->clipboard_string = NULL;
    }
    self->clipboard_size = 0;

    self->open = false;
}

/* Returns MGL_KEY_UNKNOWN on no match */
static mgl_key x11_keysym_to_mgl_key(KeySym key_sym) {
    if(key_sym >= XK_A && key_sym <= XK_Z)
        return MGL_KEY_A + (key_sym - XK_A);
    /* TODO: Check if this ever happens */
    if(key_sym >= XK_a && key_sym <= XK_z)
        return MGL_KEY_A + (key_sym - XK_a);
    if(key_sym >= XK_0 && key_sym <= XK_9)
        return MGL_KEY_NUM0 + (key_sym - XK_0);
    if(key_sym >= XK_KP_0 && key_sym <= XK_KP_9)
        return MGL_KEY_NUMPAD0 + (key_sym - XK_KP_0);

    /* TODO: Fill in the rest */
    switch(key_sym) {
        case XK_space:      return MGL_KEY_SPACE;
        case XK_BackSpace:  return MGL_KEY_BACKSPACE;
        case XK_Tab:        return MGL_KEY_TAB;
        case XK_Return:     return MGL_KEY_ENTER;
        case XK_Escape:     return MGL_KEY_ESCAPE;
        case XK_Control_L:  return MGL_KEY_LCONTROL;
        case XK_Shift_L:    return MGL_KEY_LSHIFT;
        case XK_Alt_L:      return MGL_KEY_LALT;
        case XK_Super_L:    return MGL_KEY_LSYSTEM;
        case XK_Control_R:  return MGL_KEY_RCONTROL;
        case XK_Shift_R:    return MGL_KEY_RSHIFT;
        case XK_Alt_R:      return MGL_KEY_RALT;
        case XK_Super_R:    return MGL_KEY_RSYSTEM;
        case XK_Delete:     return MGL_KEY_DELETE;
        case XK_Home:       return MGL_KEY_HOME;
        case XK_Left:       return MGL_KEY_LEFT;
        case XK_Up:         return MGL_KEY_UP;
        case XK_Right:      return MGL_KEY_RIGHT;
        case XK_Down:       return MGL_KEY_DOWN;
        case XK_Page_Up:    return MGL_KEY_PAGEUP;
        case XK_Page_Down:  return MGL_KEY_PAGEDOWN;
        case XK_End:        return MGL_KEY_END;
        case XK_F1:         return MGL_KEY_F1;
        case XK_F2:         return MGL_KEY_F2;
        case XK_F3:         return MGL_KEY_F3;
        case XK_F4:         return MGL_KEY_F4;
        case XK_F5:         return MGL_KEY_F5;
        case XK_F6:         return MGL_KEY_F6;
        case XK_F7:         return MGL_KEY_F7;
        case XK_F8:         return MGL_KEY_F8;
        case XK_F9:         return MGL_KEY_F9;
        case XK_F10:        return MGL_KEY_F10;
        case XK_F11:        return MGL_KEY_F11;
        case XK_F12:        return MGL_KEY_F12;
        case XK_F13:        return MGL_KEY_F13;
        case XK_F14:        return MGL_KEY_F14;
        case XK_F15:        return MGL_KEY_F15;
    }
    return MGL_KEY_UNKNOWN;
}

/* Returns XK_VoidSymbol on no match */
static KeySym mgl_key_to_x11_keysym(mgl_key key) {
    if(key >= MGL_KEY_A && key <= MGL_KEY_Z)
        return XK_A + (key - MGL_KEY_A);
    if(key >= MGL_KEY_NUM0 && key <= MGL_KEY_NUM9)
        return XK_0 + (key - MGL_KEY_NUM0);
    if(key >= MGL_KEY_NUMPAD0 && key <= MGL_KEY_NUMPAD9)
        return XK_KP_0 + (key - MGL_KEY_NUMPAD0);

    /* TODO: Fill in the rest */
    switch(key) {
        case MGL_KEY_SPACE:      return XK_space;
        case MGL_KEY_BACKSPACE:  return XK_BackSpace;
        case MGL_KEY_TAB:        return XK_Tab;
        case MGL_KEY_ENTER:      return XK_Return;
        case MGL_KEY_ESCAPE:     return XK_Escape;
        case MGL_KEY_LCONTROL:   return XK_Control_L;
        case MGL_KEY_LSHIFT:     return XK_Shift_L;
        case MGL_KEY_LALT:       return XK_Alt_L;
        case MGL_KEY_LSYSTEM:    return XK_Super_L;
        case MGL_KEY_RCONTROL:   return XK_Control_R;
        case MGL_KEY_RSHIFT:     return XK_Shift_R;
        case MGL_KEY_RALT:       return XK_Alt_R;
        case MGL_KEY_RSYSTEM:    return XK_Super_R;
        case MGL_KEY_DELETE:     return XK_Delete;
        case MGL_KEY_HOME:       return XK_Home;
        case MGL_KEY_LEFT:       return XK_Left;
        case MGL_KEY_UP:         return XK_Up;
        case MGL_KEY_RIGHT:      return XK_Right;
        case MGL_KEY_DOWN:       return XK_Down;
        case MGL_KEY_PAGEUP:     return XK_Page_Up;
        case MGL_KEY_PAGEDOWN:   return XK_Page_Down;
        case MGL_KEY_END:        return XK_End;
        case MGL_KEY_F1:         return XK_F1;
        case MGL_KEY_F2:         return XK_F2;
        case MGL_KEY_F3:         return XK_F3;
        case MGL_KEY_F4:         return XK_F4;
        case MGL_KEY_F5:         return XK_F5;
        case MGL_KEY_F6:         return XK_F6;
        case MGL_KEY_F7:         return XK_F7;
        case MGL_KEY_F8:         return XK_F8;
        case MGL_KEY_F9:         return XK_F9;
        case MGL_KEY_F10:        return XK_F10;
        case MGL_KEY_F11:        return XK_F11;
        case MGL_KEY_F12:        return XK_F12;
        case MGL_KEY_F13:        return XK_F13;
        case MGL_KEY_F14:        return XK_F14;
        case MGL_KEY_F15:        return XK_F15;
        default:                 return XK_VoidSymbol;
    }
    return XK_VoidSymbol;
}

static mgl_mouse_button x11_button_to_mgl_button(unsigned int button) {
    switch(button) {
        case Button1: return MGL_BUTTON_LEFT;
        case Button2: return MGL_BUTTON_MIDDLE;
        case Button3: return MGL_BUTTON_RIGHT;
        case 8:       return MGL_BUTTON_XBUTTON1;
        case 9:       return MGL_BUTTON_XBUTTON2;
    }
    return MGL_BUTTON_UNKNOWN;
}

static void mgl_window_handle_key_event(mgl_window *self, XKeyEvent *xkey, mgl_event *event, mgl_context *context, bool pressed) {
    event->key.code = x11_keysym_to_mgl_key(XKeycodeToKeysym(context->connection, xkey->keycode, 0));
    event->key.alt = ((xkey->state & Mod1Mask) != 0);
    event->key.control = ((xkey->state & ControlMask) != 0);
    event->key.shift = ((xkey->state & ShiftMask) != 0);
    event->key.system = ((xkey->state & Mod4Mask) != 0);
}

static void mgl_window_handle_text_event(mgl_window *self, XEvent *xev) {
    /* Ignore silent keys */
    if(XFilterEvent(xev, None))
        return;

    x11_context *x11_context = self->context;
    char buf[128];

    Status status;
    KeySym ksym;
    const size_t input_str_len = Xutf8LookupString(x11_context->xic, &xev->xkey, buf, sizeof(buf), &ksym, &status);
    /* TODO: Handle XBufferOverflow */
    if(status == XBufferOverflow || input_str_len == 0)
        return;

    /* TODO: Set XIC location on screen with XSetICValues */

    for(size_t i = 0; i < input_str_len;) {
        const unsigned char *cp = (const unsigned char*)&buf[i];
        uint32_t codepoint;
        size_t clen;
        if(!mgl_utf8_decode(cp, input_str_len - i, &codepoint, &clen)) {
            codepoint = *cp;
            clen = 1;
        }

        mgl_event text_event;
        text_event.type = MGL_EVENT_TEXT_ENTERED;
        text_event.text.codepoint = codepoint;
        text_event.text.size = clen;
        memcpy(text_event.text.str, &buf[i], clen);
        text_event.text.str[clen] = '\0';
        /* Text may contain multiple codepoints so they need to separated into multiple events */
        if(!x11_context_append_event(x11_context, &text_event))
            break;

        i += clen;
    }
}

static void mgl_window_on_receive_event(mgl_window *self, XEvent *xev, mgl_event *event, mgl_context *context) {
    switch(xev->type) {
        case KeyPress: {
            x11_context *x11_context = self->context;

            if(!self->key_repeat_enabled && xev->xkey.keycode == x11_context->prev_keycode_pressed && !x11_context->key_was_released) {
                event->type = MGL_EVENT_UNKNOWN;
                return;
            }

            x11_context->prev_keycode_pressed = xev->xkey.keycode;
            x11_context->key_was_released = false;

            event->type = MGL_EVENT_KEY_PRESSED;
            mgl_window_handle_key_event(self, &xev->xkey, event, context, true);
            mgl_window_handle_text_event(self, xev);
            return;
        }
        case KeyRelease: {
            x11_context *x11_context = self->context;
            if(xev->xkey.keycode == x11_context->prev_keycode_pressed)
                x11_context->key_was_released = true;

            event->type = MGL_EVENT_KEY_RELEASED;
            mgl_window_handle_key_event(self, &xev->xkey, event, context, false);
            return;
        }
        case ButtonPress: {
            if(xev->xbutton.button == Button4) {
                /* Mouse scroll up */
                event->type = MGL_EVENT_MOUSE_WHEEL_SCROLLED;
                event->mouse_wheel_scroll.delta = 1;
                event->mouse_wheel_scroll.x = xev->xbutton.x;
                event->mouse_wheel_scroll.y = xev->xbutton.y;
            } else if(xev->xbutton.button == Button5) {
                /* Mouse scroll down */
                event->type = MGL_EVENT_MOUSE_WHEEL_SCROLLED;
                event->mouse_wheel_scroll.delta = -1;
                event->mouse_wheel_scroll.x = xev->xbutton.x;
                event->mouse_wheel_scroll.y = xev->xbutton.y;
            } else {
                event->type = MGL_EVENT_MOUSE_BUTTON_PRESSED;
                event->mouse_button.button = x11_button_to_mgl_button(xev->xbutton.button);
                event->mouse_button.x = xev->xbutton.x;
                event->mouse_button.y = xev->xbutton.y;
            }
            return;
        }
        case ButtonRelease: {
            event->type = MGL_EVENT_MOUSE_BUTTON_RELEASED;
            event->mouse_button.button = x11_button_to_mgl_button(xev->xbutton.button);
            event->mouse_button.x = xev->xbutton.x;
            event->mouse_button.y = xev->xbutton.y;
            return;
        }
        case FocusIn: {
            x11_context *x11_context = self->context;
            XSetICFocus(x11_context->xic);

            XWMHints* hints = XGetWMHints(context->connection, self->window);
            if(hints) {
                hints->flags &= ~XUrgencyHint;
                XSetWMHints(context->connection, self->window, hints);
                XFree(hints);
            }

            event->type = MGL_EVENT_GAINED_FOCUS;
            self->focused = true;
            return;
        }
        case FocusOut: {
            x11_context *x11_context = self->context;
            XUnsetICFocus(x11_context->xic);
            event->type = MGL_EVENT_LOST_FOCUS;
            self->focused = false;
            return;
        }
        case ConfigureNotify: {
            while(XCheckTypedWindowEvent(context->connection, self->window, ConfigureNotify, xev)) {}
            if(xev->xconfigure.width != self->size.x || xev->xconfigure.height != self->size.y) {
                mgl_window_on_resize(self, xev->xconfigure.width, xev->xconfigure.height);

                event->type = MGL_EVENT_RESIZED;
                event->size.width = self->size.x;
                event->size.height = self->size.y;
                return;
            }
            event->type = MGL_EVENT_UNKNOWN;
            return;
        }
        case MotionNotify: {
            while(XCheckTypedWindowEvent(context->connection, self->window, MotionNotify, xev)) {}
            self->cursor_position.x = xev->xmotion.x;
            self->cursor_position.y = xev->xmotion.y;

            event->type = MGL_EVENT_MOUSE_MOVED;
            event->mouse_move.x = self->cursor_position.x;
            event->mouse_move.y = self->cursor_position.y;
            return;
        }
        case SelectionClear: {
            event->type = MGL_EVENT_UNKNOWN;
            return;
        }
        case SelectionRequest: {
            x11_context *x11_context = self->context;

            XSelectionEvent selection_event;
            selection_event.type = SelectionNotify;
            selection_event.requestor = xev->xselectionrequest.requestor;
            selection_event.selection = xev->xselectionrequest.selection;
            selection_event.property = xev->xselectionrequest.property;
            selection_event.time = xev->xselectionrequest.time;
            selection_event.target = xev->xselectionrequest.target;

            if(selection_event.selection == x11_context->clipboard_atom) {
                /* TODO: Support ascii text separately by unsetting the 8th bit in the clipboard string? */
                if(selection_event.target == x11_context->targets_atom) {
                    /* A client requested for our valid conversion targets */
                    int num_targets = 3;
                    Atom targets[4];
                    targets[0] = x11_context->targets_atom;
                    targets[1] = x11_context->text_atom;
                    targets[2] = XA_STRING;
                    if(x11_context->utf8_string_atom) {
                        targets[3] = x11_context->utf8_string_atom;
                        num_targets = 4;
                    }

                    XChangeProperty(context->connection, selection_event.requestor, selection_event.property, XA_ATOM, 32, PropModeReplace, (unsigned char*)targets, num_targets);
                    selection_event.target = x11_context->targets_atom;
                    XSendEvent(context->connection, selection_event.requestor, True, NoEventMask, (XEvent*)&selection_event);
                    XFlush(context->connection);
                    event->type = MGL_EVENT_UNKNOWN;
                    return;
                } else if(selection_event.target == XA_STRING || (!x11_context->utf8_string_atom && selection_event.target == x11_context->text_atom)) {
                    /* A client requested ascii clipboard */
                    XChangeProperty(context->connection, selection_event.requestor, selection_event.property, XA_STRING, 8, PropModeReplace, self->clipboard_string, self->clipboard_size);
                    selection_event.target = XA_STRING;
                    XSendEvent(context->connection, selection_event.requestor, True, NoEventMask, (XEvent*)&selection_event);
                    XFlush(context->connection);
                    event->type = MGL_EVENT_UNKNOWN;
                    return;
                } else if(x11_context->utf8_string_atom && (selection_event.target == x11_context->utf8_string_atom || selection_event.target == x11_context->text_atom)) {
                    /* A client requested utf8 clipboard */
                    XChangeProperty(context->connection, selection_event.requestor, selection_event.property, x11_context->utf8_string_atom, 8, PropModeReplace, self->clipboard_string, self->clipboard_size);
                    selection_event.target = x11_context->utf8_string_atom;
                    XSendEvent(context->connection, selection_event.requestor, True, NoEventMask, (XEvent*)&selection_event);
                    XFlush(context->connection);
                    event->type = MGL_EVENT_UNKNOWN;
                    return;
                }
            }

            selection_event.property = None;
            XSendEvent(context->connection, selection_event.requestor, True, NoEventMask, (XEvent*)&selection_event);
            XFlush(context->connection);
            event->type = MGL_EVENT_UNKNOWN;
            return;
        }
        case ClientMessage: {
            if(xev->xclient.format == 32 && (unsigned long)xev->xclient.data.l[0] == context->wm_delete_window_atom) {
                event->type = MGL_EVENT_CLOSED;
                self->open = false;
                return;
            } else if(xev->xclient.format == 32 && (unsigned long)xev->xclient.data.l[0] == context->net_wm_ping_atom) {
                xev->xclient.window = DefaultRootWindow(context->connection);
                XSendEvent(context->connection, DefaultRootWindow(context->connection), False, SubstructureNotifyMask | SubstructureRedirectMask, xev);
                XFlush(context->connection);
            }
            event->type = MGL_EVENT_UNKNOWN;
            return;
        }
        default: {
            event->type = MGL_EVENT_UNKNOWN;
            return;
        }
    }
}

void mgl_window_clear(mgl_window *self, mgl_color color) {
    mgl_context *context = mgl_get_context();
    context->gl.glClear(GL_COLOR_BUFFER_BIT);
    context->gl.glClearColor((float)color.r / 255.0f, (float)color.g / 255.0f, (float)color.b / 255.0f, (float)color.a / 255.0f);
}

bool mgl_window_poll_event(mgl_window *self, mgl_event *event) {
    mgl_context *context = mgl_get_context();
    Display *display = context->connection;
    x11_context *x11_context = self->context;

    if(x11_context_pop_event(x11_context, event))
        return true;

    if(XPending(display)) {
        XEvent xev; /* TODO: Move to window struct */
        XNextEvent(display, &xev);
        if(xev.xany.window == self->window || event->type == ClientMessage)
            mgl_window_on_receive_event(self, &xev, event, context);
        else
            event->type = MGL_EVENT_UNKNOWN;
        return true;
    } else {
        return false;
    }
}

void mgl_window_display(mgl_window *self) {
    mgl_context *context = mgl_get_context();
    context->gl.glXSwapBuffers(context->connection, self->window);

    if(self->frame_time_limit > 0.000001) {
        double time_left_to_sleep = self->frame_time_limit - mgl_clock_get_elapsed_time_seconds(&self->frame_timer);
        if(time_left_to_sleep > 0.000001)
            usleep(time_left_to_sleep * 1000000.0);
        mgl_clock_restart(&self->frame_timer);
    }
}

void mgl_window_set_view(mgl_window *self, mgl_view *new_view) {
    mgl_context *context = mgl_get_context();
    self->view = *new_view;
    context->gl.glViewport(new_view->position.x, self->size.y - new_view->size.y - new_view->position.y, new_view->size.x, new_view->size.y);
    context->gl.glMatrixMode(GL_PROJECTION);
    context->gl.glLoadIdentity();
    context->gl.glOrtho(0.0, new_view->size.x, new_view->size.y, 0.0, 0.0, 1.0);
    context->gl.glMatrixMode(GL_MODELVIEW);
}

void mgl_window_get_view(mgl_window *self, mgl_view *view) {
    *view = self->view;
}

void mgl_window_set_scissor(mgl_window *self, mgl_scissor *new_scissor) {
    mgl_context *context = mgl_get_context();
    self->scissor = *new_scissor;
    context->gl.glScissor(self->scissor.position.x, self->size.y - self->scissor.position.y - self->scissor.size.y, self->scissor.size.x, self->scissor.size.y);
}

void mgl_window_get_scissor(mgl_window *self, mgl_scissor *scissor) {
    *scissor = self->scissor;
}

void mgl_window_set_visible(mgl_window *self, bool visible) {
    mgl_context *context = mgl_get_context();
    if(visible)
        XMapWindow(context->connection, self->window);
    else
        XUnmapWindow(context->connection, self->window);
}

bool mgl_window_is_open(const mgl_window *self) {
    return self->open;
}

bool mgl_window_has_focus(const mgl_window *self) {
    return self->focused;
}

/* TODO: Track keys with events instead, but somehow handle window focus lost */
bool mgl_window_is_key_pressed(const mgl_window *self, mgl_key key) {
    if(key < 0 || key >= __MGL_NUM_KEYS__)
        return false;
    
    mgl_context *context = mgl_get_context();
    const KeySym keysym = mgl_key_to_x11_keysym(key);
    if(keysym == XK_VoidSymbol)
        return false;

    KeyCode keycode = XKeysymToKeycode(context->connection, keysym);
    if(keycode == 0)
        return false;

    char keys[32];
    XQueryKeymap(context->connection, keys);

    return (keys[keycode / 8] & (1 << (keycode % 8))) != 0;
}

/* TODO: Track keys with events instead, but somehow handle window focus lost */
bool mgl_window_is_mouse_button_pressed(const mgl_window *self, mgl_mouse_button button) {
    if(button < 0 || button >= __MGL_NUM_MOUSE_BUTTONS__)
        return false;

    mgl_context *context = mgl_get_context();
    Window root, child;
    int root_x, root_y, win_x, win_y;

    unsigned int buttons_mask = 0;
    XQueryPointer(context->connection, DefaultRootWindow(context->connection), &root, &child, &root_x, &root_y, &win_x, &win_y, &buttons_mask);

    switch(button) {
        case MGL_BUTTON_LEFT:      return buttons_mask & Button1Mask;
        case MGL_BUTTON_MIDDLE:    return buttons_mask & Button2Mask;
        case MGL_BUTTON_RIGHT:     return buttons_mask & Button3Mask;
        case MGL_BUTTON_XBUTTON1:  return false; /* Not supported by x11 */
        case MGL_BUTTON_XBUTTON2:  return false; /* Not supported by x11 */
        default:                   return false;
    }

    return false;
}

void mgl_window_close(mgl_window *self) {
    mgl_context *context = mgl_get_context();
    XDestroyWindow(context->connection, self->window);
    XSync(context->connection, False);
    self->window = None;
    self->open = false;
}

void mgl_window_set_title(mgl_window *self, const char *title) {
    mgl_context *context = mgl_get_context();
    XStoreName(context->connection, self->window, title);
}

void mgl_window_set_cursor_visible(mgl_window *self, bool visible) {
    mgl_context *context = mgl_get_context();
    x11_context *x11_context = self->context;
    XDefineCursor(context->connection, self->window, visible ? x11_context->default_cursor : x11_context->invisible_cursor);
}

void mgl_window_set_framerate_limit(mgl_window *self, int fps) {
    if(fps <= 0)
        self->frame_time_limit = 0.0;
    else
        self->frame_time_limit = 1.0 / fps;
}

void mgl_window_set_position(mgl_window *self, mgl_vec2i position) {
    XMoveWindow(mgl_get_context()->connection, self->window, position.x, position.y);
}

void mgl_window_set_size(mgl_window *self, mgl_vec2i size) {
    XResizeWindow(mgl_get_context()->connection, self->window, size.x, size.y);
}

void mgl_window_set_size_limits(mgl_window *self, mgl_vec2i minimum, mgl_vec2i maximum) {
    XSizeHints *size_hints = XAllocSizeHints();
    if(size_hints) {
        size_hints->width = self->size.x;
        size_hints->min_width = minimum.x;
        size_hints->max_width = maximum.x;

        size_hints->height = self->size.y;
        size_hints->min_height = minimum.y;
        size_hints->max_height = maximum.y;

        size_hints->flags = PSize;
        if(size_hints->min_width || size_hints->min_height)
            size_hints->flags |= PMinSize;
        if(size_hints->max_width || size_hints->max_height)
            size_hints->flags |= PMaxSize;

        mgl_context *context = mgl_get_context();
        XSetWMNormalHints(context->connection, self->window, size_hints);
        XFree(size_hints);
        XSync(context->connection, False);
    } else {
        fprintf(stderr, "mgl warning: failed to set window size hints\n");
    }
}

void mgl_window_set_clipboard(mgl_window *self, const char *str, size_t size) {
    mgl_context *context = mgl_get_context();
    x11_context *x11_context = self->context;

    if(self->clipboard_string) {
        free(self->clipboard_string);
        self->clipboard_string = NULL;
        self->clipboard_size = 0;
    }

    XSetSelectionOwner(context->connection, x11_context->clipboard_atom, self->window, CurrentTime);
    XFlush(context->connection);

    /* Check if setting the selection owner was successful */
    if(XGetSelectionOwner(context->connection, x11_context->clipboard_atom) != self->window) {
        fprintf(stderr, "mgl error: mgl_window_set_clipboard failed\n");
        return;
    }

    self->clipboard_string = malloc(size + 1);
    if(!self->clipboard_string) {
        fprintf(stderr, "mgl error: failed to allocate string for clipboard\n");
        return;
    }
    memcpy(self->clipboard_string, str, size);
    self->clipboard_string[size] = '\0';
    self->clipboard_size = size;
}

static Atom find_matching_atom(const Atom *supported_atoms, size_t num_supported_atoms, const Atom *atoms, size_t num_atoms) {
    for(size_t j = 0; j < num_supported_atoms; ++j) {
        for(size_t i = 0; i < num_atoms; ++i) {
            if(atoms[i] == supported_atoms[j])
                return atoms[i];
        }
    }
    return None;
}

static mgl_clipboard_type atom_type_to_supported_clipboard_type(x11_context *x11_context, Atom type, int format) {
    if((type == x11_context->utf8_string_atom || type == XA_STRING || type == x11_context->text_atom) && format == 8) {
        return MGL_CLIPBOARD_TYPE_STRING;
    } else if(type == x11_context->image_png && format == 8){
        return MGL_CLIPBOARD_TYPE_IMAGE_PNG;
    } else if((type == x11_context->image_jpg || type == x11_context->image_jpeg) && format == 8){
        return MGL_CLIPBOARD_TYPE_IMAGE_JPG;
    } else if(type == x11_context->image_gif && format == 8){
        return MGL_CLIPBOARD_TYPE_IMAGE_GIF;
    } else {
        return -1;
    }
}

bool mgl_window_get_clipboard(mgl_window *self, mgl_clipboard_callback callback, void *userdata, uint32_t clipboard_types) {
    assert(callback);

    mgl_context *context = mgl_get_context();
    x11_context *x11_context = self->context;

    Window selection_owner = XGetSelectionOwner(context->connection, x11_context->clipboard_atom);

    if(!selection_owner)
        return false;

    /* Return data immediately if we are the owner of the clipboard, because we can't process other events in the below event loop */
    if(selection_owner == self->window) {
        if(!self->clipboard_string)
            return false;

        return callback((const unsigned char*)self->clipboard_string, self->clipboard_size, MGL_CLIPBOARD_TYPE_STRING, userdata);
    }

    XEvent xev;
    while(XCheckTypedWindowEvent(context->connection, self->window, SelectionNotify, &xev)) {}

    /* Sorted by preference */
    /* TODO: Support more types (BITMAP?, PIXMAP?) */
    Atom supported_clipboard_types[7];

    int supported_clipboard_type_index = 0;
    if(clipboard_types & MGL_CLIPBOARD_TYPE_IMAGE_PNG) {
        supported_clipboard_types[supported_clipboard_type_index++] = x11_context->image_png;
    }

    if(clipboard_types & MGL_CLIPBOARD_TYPE_IMAGE_JPG) {
        supported_clipboard_types[supported_clipboard_type_index++] = x11_context->image_jpeg;
    }

    if(clipboard_types & MGL_CLIPBOARD_TYPE_IMAGE_GIF) {
        supported_clipboard_types[supported_clipboard_type_index++] = x11_context->image_gif;
    }

    if(clipboard_types & MGL_CLIPBOARD_TYPE_STRING) {
        supported_clipboard_types[supported_clipboard_type_index++] = x11_context->utf8_string_atom;
        supported_clipboard_types[supported_clipboard_type_index++] = XA_STRING;
        supported_clipboard_types[supported_clipboard_type_index++] = x11_context->text_atom;
    }

    const unsigned long num_supported_clipboard_types = supported_clipboard_type_index;

    Atom requested_clipboard_type = None;
    const Atom XA_TARGETS = XInternAtom(context->connection, "TARGETS", False);
    XConvertSelection(context->connection, x11_context->clipboard_atom, XA_TARGETS, x11_context->clipboard_atom, self->window, CurrentTime);

    mgl_clock timeout_timer;
    mgl_clock_init(&timeout_timer);
    bool success = false;

    const double timeout_seconds = 5.0;
    while(mgl_clock_get_elapsed_time_seconds(&timeout_timer) < timeout_seconds) {
        /* TODO: Wait for SelectionNotify event instead */
        while(XCheckTypedWindowEvent(context->connection, self->window, SelectionNotify, &xev)) {
            if(mgl_clock_get_elapsed_time_seconds(&timeout_timer) >= timeout_seconds)
                break;

            if(!xev.xselection.property)
                continue;

            if(!xev.xselection.target || xev.xselection.selection != x11_context->clipboard_atom)
                continue;

            Atom type = None;
            int format;
            unsigned long items;
            unsigned long remaining_bytes = 0;
            unsigned char *data = NULL;

            if(xev.xselection.target == XA_TARGETS && requested_clipboard_type == None) {
                /* TODO: Wait for PropertyNotify event instead */
                if(XGetWindowProperty(context->connection, xev.xselection.requestor, xev.xselection.property, 0, 1024, False, PropertyNewValue, &type, &format, &items, &remaining_bytes, &data) == Success && data) {
                    if(type != x11_context->incr_atom && type == XA_ATOM && format == 32) {
                        requested_clipboard_type = find_matching_atom(supported_clipboard_types, num_supported_clipboard_types, (Atom*)data, items);
                        if(requested_clipboard_type == None) {
                            /* Pasting clipboard data type we dont support */
                            XFree(data);
                            goto done;
                        } else {
                            XConvertSelection(context->connection, x11_context->clipboard_atom, requested_clipboard_type, x11_context->clipboard_atom, self->window, CurrentTime);
                        }
                    }

                    XFree(data);
                }
            } else if(xev.xselection.target == requested_clipboard_type) {
                bool got_data = false;
                long chunk_size = 65536;

                //XDeleteProperty(context->connection, self->window, x11_context->incr_atom);
                //XFlush(context->connection);

                while(mgl_clock_get_elapsed_time_seconds(&timeout_timer) < timeout_seconds) {
                    unsigned long offset = 0;

                    /* offset is specified in XGetWindowProperty as a multiple of 32-bit (4 bytes) */
                    /* TODO: Wait for PropertyNotify event instead */
                    while(XGetWindowProperty(context->connection, xev.xselection.requestor, xev.xselection.property, offset/4, chunk_size, True, PropertyNewValue, &type, &format, &items, &remaining_bytes, &data) == Success) {
                        if(mgl_clock_get_elapsed_time_seconds(&timeout_timer) >= timeout_seconds)
                            break;

                        if(type == x11_context->incr_atom) {
                            if(data)
                                chunk_size = *(long*)data;
                            XDeleteProperty(context->connection, self->window, x11_context->incr_atom);
                            XFlush(context->connection);
                            XFree(data);
                            data = NULL;
                            break;
                        } else if(type == requested_clipboard_type) {
                            got_data = true;
                        }

                        if(!got_data && items == 0) {
                            XDeleteProperty(context->connection, self->window, type);
                            XFlush(context->connection);
                            if(data) {
                                XFree(data);
                                data = NULL;
                            }
                            break;
                        }

                        const size_t num_items_bytes = items * (format/8); /* format is the bit size of the data */
                        if(got_data) {
                            const mgl_clipboard_type clipboard_type = atom_type_to_supported_clipboard_type(x11_context, type, format);
                            if(data && num_items_bytes > 0 && clipboard_type != -1) {
                                if(!callback(data, num_items_bytes, clipboard_type, userdata)) {
                                    XFree(data);
                                    goto done;
                                }
                            }
                        }
                        offset += num_items_bytes;

                        if(data) {
                            XFree(data);
                            data = NULL;
                        }

                        if(got_data && num_items_bytes == 0/* && format == 8*/) {
                            success = true;
                            goto done;
                        }

                        if(remaining_bytes == 0)
                           break;
                    }
                }

                goto done;
            }
        }
    }

    done:
    if(requested_clipboard_type)
        XDeleteProperty(context->connection, self->window, requested_clipboard_type);
    return success;
}

typedef struct {
    char **str;
    size_t *size;
} ClipboardStringCallbackData;

static bool clipboard_copy_string_callback(const unsigned char *data, size_t size, mgl_clipboard_type clipboard_type, void *userdata) {
    ClipboardStringCallbackData *callback_data = userdata;
    if(clipboard_type != MGL_CLIPBOARD_TYPE_STRING) {
        free(*callback_data->str);
        *callback_data->str = NULL;
        *callback_data->size = 0;
        return false;
    }

    char *new_data = realloc(*callback_data->str, *callback_data->size + size);
    if(!new_data) {
        free(*callback_data->str);
        *callback_data->str = NULL;
        *callback_data->size = 0;
        return false;
    }

    memcpy(new_data + *callback_data->size, data, size);

    *callback_data->str = new_data;
    *callback_data->size += size;
    return true;
}

bool mgl_window_get_clipboard_string(mgl_window *self, char **str, size_t *size) {
    assert(str);
    assert(size);

    *str = NULL;
    *size = 0;

    ClipboardStringCallbackData callback_data;
    callback_data.str = str;
    callback_data.size = size;
    const bool success = mgl_window_get_clipboard(self, clipboard_copy_string_callback, &callback_data, MGL_CLIPBOARD_TYPE_STRING);
    if(!success) {
        free(*str);
        *str = NULL;
        *size = 0;
    }
    return success;
}

void mgl_window_set_key_repeat_enabled(mgl_window *self, bool enabled) {
    self->key_repeat_enabled = enabled;
}