-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplatform_linux.cpp
More file actions
739 lines (638 loc) · 30 KB
/
platform_linux.cpp
File metadata and controls
739 lines (638 loc) · 30 KB
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
#include "global.hpp"
#include <poll.h>
#include "platform.hpp"
#include <GL/glx.h>
#include "platform_linux_autogen.cpp"
#include <zlib.h>
#define PLATFORM_INCLUDES
#include "factorio_gui.cpp"
#include <alloca.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/Xrandr.h>
#include <time.h>
#include <locale.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <unistd.h>
typedef GLXContext (*glXCreateContextAttribsARB_t) (
Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list
);
struct Platform_state {
enum Constants: u64 {
MAGIC_REDRAW_FD = 0xdadfe724903e0b4aull
};
Display* display = nullptr;
Window window;
GLXWindow window_glx;
Atom sel_primary, sel_clipboard, sel_target, sel_utf8str, sel_string, sel_incr;
Atom net_wm_state, net_wm_state_fullscreen, type_atom;
Application app_context;
timespec t_start; // Time of program start
u64 now = 0; // ns since t_start
u64 redraw_next = -1; // next redraw, in ns since t_start
u64 frame_count = 0; // number of frames since program start
Array_dyn<pollfd> redraw_fds; // We will redraw when one of these polls
Array_dyn<pollfd> redraw_fds_result; // after the redraw, you can read the results here
s64 rate = -1;
Array_dyn<u8> clipboard_recv;
Array_dyn<u8> clipboard_send[Platform_clipboard::COUNT] = {};
bool keys_dirty = true;
char keys_map[32];
u32 keys_mask;
};
Platform_state global_platform;
void linux_get_event_key(Array_dyn<Key>* keys, XKeyEvent e) {
KeySym keysym;
// You would think that we could do some dynamic resizing here if the buffer is too
// small. However, the API does not seem to support it.
u8 buffer_[64];
Array<u8> buffer {buffer_, sizeof(buffer)};
buffer.size = XLookupString(&e, (char*)buffer.data, buffer.size, &keysym, NULL);
s64 special = Key::INVALID;
u64 mod = 0;
u64 shiftctrl = ShiftMask | ControlMask;
switch (keysym) {
case XK_Escape: special = Key::ESCAPE; break;
case XK_Page_Up: special = Key::PAGE_U; break;
case XK_Page_Down: special = Key::PAGE_D; break;
case XK_Tab: special = Key::TAB; break;
case XK_F1: special = Key::F1; break;
case XK_F2: special = Key::F2; break;
case XK_F3: special = Key::F3; break;
case XK_F4: special = Key::F4; break;
case XK_F5: special = Key::F5; break;
case XK_F6: special = Key::F6; break;
case XK_F7: special = Key::F7; break;
case XK_F8: special = Key::F8; break;
case XK_F9: special = Key::F9; break;
case XK_F10: special = Key::F10; break;
case XK_F11: special = Key::F11; break;
case XK_F12: special = Key::F12; break;
case XK_Return: special = Key::RETURN; break;
case XK_Left: special = Key::ARROW_L; mod = e.state & shiftctrl; break;
case XK_Right: special = Key::ARROW_R; mod = e.state & shiftctrl; break;
case XK_Down: special = Key::ARROW_D; mod = e.state & shiftctrl; break;
case XK_Up: special = Key::ARROW_U; mod = e.state & shiftctrl; break;
case XK_Home: special = Key::HOME; mod = e.state & shiftctrl; break;
case XK_End: special = Key::END; mod = e.state & shiftctrl; break;
case XK_Delete: special = Key::DELETE; mod = e.state & shiftctrl; break;
case XK_BackSpace: special = Key::BACKSPACE; mod = e.state & shiftctrl; break;
case XK_ISO_Left_Tab: special = Key::SHIFT_TAB; mod = ShiftMask; break;
case XK_c: special = Key::C_COPY; mod = ControlMask; break;
case XK_v: special = Key::C_PASTE; mod = ControlMask; break;
case XK_x: special = Key::C_CUT; mod = ControlMask; break;
case XK_a: special = Key::C_SELECTALL; mod = ControlMask; break;
case XK_q: special = Key::C_QUIT; mod = ControlMask; break;
case XK_s: special = Key::C_SAVE; mod = ControlMask; break;
case XK_z: special = Key::C_UNDO; mod = ControlMask; break;
case XK_plus: special = Key::C_ZOOM_IN; mod = ControlMask; break;
case XK_minus: special = Key::C_ZOOM_OUT; mod = ControlMask; break;
case XK_0: special = Key::C_ZOOM_ZERO; mod = ControlMask; break;
case XK_Z: special = Key::C_REDO; mod = ControlMask | ShiftMask; break;
case XK_S: special = Key::C_SAVEAS; mod = ControlMask | ShiftMask; break;
}
// Exclude NumLock (Mod2) and CapsLock (Lock) from the modifier list, as our shortcuts should
// still work if they are pressed.
u64 mod_mask = ShiftMask | ControlMask | Mod1Mask | Mod3Mask | Mod4Mask | Mod5Mask;
if (special != Key::INVALID and (e.state & mod_mask) == mod) {
u8 flags = 0;
if (e.state & ShiftMask) flags |= Key::MOD_SHIFT;
if (e.state & ControlMask) flags |= Key::MOD_CTRL;
array_push(keys, Key::create_special(special, flags));
} else {
s64 chunk = sizeof(Key::text);
for (s64 i = 0; i < buffer.size; i += chunk) {
s64 end = i + chunk < buffer.size ? i + chunk : buffer.size;
array_push(keys, Key::create_text(array_subarray(buffer, i, end)));
}
}
}
void linux_set_wm_prop(Display* display, Window window, char const* property, char const* data) {
Atom prop = XInternAtom(display, property, true);
assert(prop != None);
Atom type_string = XInternAtom(display, "STRING", true);
assert(type_string != None);
XChangeProperty(display, window, prop, type_string, 8, PropModeReplace, (u8*)data, strlen(data));
}
void linux_set_wm_class(Display* display, Window window, int argc, char** argv) {
char* instance = nullptr;
for (s64 i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-name") == 0 and i+1 < argc) {
instance = argv[i+1];
}
}
if (not instance) {
instance = getenv("RESOURCE_NAME");
}
if (not instance) {
s64 last_sep = 0;
for (s64 i = 0; argv[0][i]; ++i) {
if (argv[0][i] == '/') last_sep = i;
}
if (argv[0][last_sep] and argv[0][last_sep+1]) {
instance = &argv[0][last_sep + 1];
}
}
if (not instance) {
instance = (char*)"obst";
}
char* cls = (char*)"obst";
s64 buf_size = strlen(instance) + strlen(cls) + 2;
char* buf = (char*)alloca(buf_size);
assert( snprintf(buf, buf_size, "%s %s", instance, cls) < buf_size );
linux_set_wm_prop(display, window, "WM_CLASS", buf);
}
Array<u8> platform_clipboard_get(s64 index) {
s64 size = *(s64*)&global_platform.clipboard_recv[index];
index += sizeof(s64);
return array_subarray(global_platform.clipboard_recv, index, index+size);
}
void platform_clipboard_free(s64 index) {
auto arr = platform_clipboard_get(index);
if (arr.end() == global_platform.clipboard_recv.end()) {
global_platform.clipboard_recv.size = 0;
}
}
void platform_clipboard_set(u8 type, Array<u8> data) {
assert(type <= Platform_clipboard::COUNT);
global_platform.clipboard_send[type].size = 0;
array_append(&global_platform.clipboard_send[type], data);
auto type_x = type == Platform_clipboard::CONTROL_C ? global_platform.sel_clipboard : global_platform.sel_primary;
XSetSelectionOwner(global_platform.display, type_x, global_platform.window, CurrentTime);
}
void linux_handle_selection_request(Platform_state* platform, XSelectionRequestEvent* ev) {
XSelectionEvent ev_out;
memset(&ev_out, 0, sizeof(ev_out));
ev_out.type = SelectionNotify;
ev_out.requestor = ev->requestor;
ev_out.selection = ev->selection;
ev_out.target = ev->target;
ev_out.time = ev->time;
if (ev->target == platform->sel_utf8str or ev->target == platform->sel_string) {
Atom property = ev->property;
if (property == None) {
property = ev->target;
}
u8 sel_type = ev->selection == platform->sel_primary ? Platform_clipboard::MIDDLE_BUTTON : Platform_clipboard::CONTROL_C;
auto buf = platform->clipboard_send[sel_type];
XChangeProperty(platform->display, ev->requestor, property, ev->target, 8, PropModeReplace, buf.data, buf.size);
ev_out.property = property;
} else {
ev_out.property = None;
}
XSendEvent(platform->display, ev_out.requestor, false, 0, (XEvent*)&ev_out);
}
void linux_handle_selection_response(Platform_state* platform, XSelectionEvent* ev) {
if (ev->property == None) {
// Try to fall back to STRING type
XConvertSelection(platform->display, ev->selection, platform->sel_target, platform->sel_string, platform->window, ev->time);
} else {
Atom actual_type;
int actual_format;
unsigned long n_items, bytes_after;
u8* prop;
XGetWindowProperty(platform->display, platform->window, platform->sel_target, 0, -1, 0,
AnyPropertyType, &actual_type, &actual_format, &n_items, &bytes_after, &prop);
if (actual_type == platform->sel_incr) {
fprintf(stderr, "Warning: Received clipboard of type INCR, which obst does not implement.\n");
return;
} else if (actual_type == None or actual_format != 8) {
return;
}
s64 index = global_platform.clipboard_recv.size;
s64 n_items_ = n_items;
array_append(&global_platform.clipboard_recv, {(u8*)&n_items_, sizeof(s64)});
array_append(&global_platform.clipboard_recv, {prop, (s64)n_items});
XFree(prop);
XDeleteProperty(platform->display, platform->window, platform->sel_target);
// TODO this is broken in this version of platform_linux
/*if (ev->selection == platform->sel_primary) {
// TODO This should not press buttons
Key key1 = Key::create_mouse(Key::LEFT_DOWN, platform->app_context.pointer_x, platform->app_context.pointer_y);
Key key2 = Key::create_mouse(Key::LEFT_UP, platform->app_context.pointer_x, platform->app_context.pointer_y);
array_append(&global_platform.app_context.input_queue, {key1, key2});
}*/
Key key = Key::create_special(Key::C_PASTE, 0, index);
array_push(&global_platform.app_context.input_queue, key);
}
}
void linux_fullscreen(Platform_state* platform) {
// This tries to go to fullscreen via NET_WM_STATE, which might not work for some window managers
if (platform->net_wm_state != None and platform->net_wm_state_fullscreen != None) {
XEvent ev;
memset(&ev, 0, sizeof(ev));
ev.type = ClientMessage;
ev.xclient.window = platform->window;
ev.xclient.format = 32;
ev.xclient.message_type = platform->net_wm_state;
ev.xclient.data.l[0] = 2; // _NET_WM_STATE_TOGGLE
ev.xclient.data.l[1] = platform->net_wm_state_fullscreen;
ev.xclient.data.l[2] = 0;
ev.xclient.data.l[3] = 1;
ev.xclient.data.l[4] = 0;
XSendEvent(platform->display, DefaultRootWindow(platform->display), false,
SubstructureNotifyMask | SubstructureRedirectMask, &ev);
}
}
void platform_redraw(u64 t) {
global_platform.redraw_next = min(global_platform.redraw_next, t);
}
s64 platform_redraw_fd(pollfd fd) {
array_push(&global_platform.redraw_fds, fd);
s64 index = global_platform.redraw_fds.size - 1;
u64 tok = (u64)index << 8ull | (global_platform.frame_count & 0xff);
return tok ^ Platform_state::MAGIC_REDRAW_FD;
}
pollfd platform_redraw_fd_result(s64 tok) {
tok ^= Platform_state::MAGIC_REDRAW_FD;
u8 epoch = tok & 0xff;
s64 index = (u64)tok >> 8ull;
if (((epoch + 1) & 0xff) == (global_platform.frame_count & 0xff)) {
return global_platform.redraw_fds_result[index];
} else if (epoch == (global_platform.frame_count & 0xff)) {
return global_platform.redraw_fds[index];
} else {
assert(false);
return {};
}
}
bool platform_key_get(Key key) {
KeySym sym = NoSymbol;
s32 mask = 0;
if (key.type == Key::TEXT) {
sym = XStringToKeysym((char*)key.text);
} else if (key.type == Key::SPECIAL) {
switch (key.special) {
case Key::ESCAPE: sym = XK_Escape; break;
case Key::PAGE_U: sym = XK_Page_Up; break;
case Key::PAGE_D: sym = XK_Page_Down; break;
case Key::TAB: sym = XK_Tab; break;
case Key::F1: sym = XK_F1; break;
case Key::F2: sym = XK_F2; break;
case Key::F3: sym = XK_F3; break;
case Key::F4: sym = XK_F4; break;
case Key::F5: sym = XK_F5; break;
case Key::F6: sym = XK_F6; break;
case Key::F7: sym = XK_F7; break;
case Key::F8: sym = XK_F8; break;
case Key::F9: sym = XK_F9; break;
case Key::F10: sym = XK_F10; break;
case Key::F11: sym = XK_F11; break;
case Key::F12: sym = XK_F12; break;
case Key::RETURN: sym = XK_Return; break;
case Key::ARROW_L: sym = XK_Left; break;
case Key::ARROW_R: sym = XK_Right; break;
case Key::ARROW_D: sym = XK_Down; break;
case Key::ARROW_U: sym = XK_Up; break;
case Key::HOME: sym = XK_Home; break;
case Key::END: sym = XK_End; break;
case Key::DELETE: sym = XK_Delete; break;
case Key::BACKSPACE: sym = XK_BackSpace; break;
case Key::SHIFT: mask = ShiftMask; break;
case Key::CONTROL: mask = ControlMask; break;
case Key::ALT: mask = Mod1Mask; break;
default: assert(false); return false;
}
} else if (key.type == Key::MOUSE) {
u8 action;
key.get_mouse_param(&action, nullptr, nullptr);
switch (action) {
case Key::LEFT_DOWN: mask = Button1Mask; break;
case Key::MIDDLE_DOWN: mask = Button2Mask; break;
case Key::RIGHT_DOWN: mask = Button3Mask; break;
default: assert(false); return false;
}
} else {
assert(false);
return false;
}
if (global_platform.keys_dirty) {
XQueryKeymap(global_platform.display, global_platform.keys_map);
Window a0, a1; int a2, a3, a4, a5;
XQueryPointer(global_platform.display, global_platform.window,
&a0, &a1, &a2, &a3, &a4, &a5, &global_platform.keys_mask);
global_platform.keys_dirty = false;
}
if (sym != NoSymbol) {
KeyCode code = XKeysymToKeycode(global_platform.display, sym);
if (code == 0) {
assert(false);
return false;
}
assert(code < sizeof(global_platform.keys_map) * 8);
return global_platform.keys_map[code/8] >> code%8 & 1;
} else if (mask != 0) {
return global_platform.keys_mask & mask;
} else {
assert(false);
return false;
}
}
u64 platform_now() {
return global_platform.now;
}
u64 platform_frame_count() {
return global_platform.frame_count;
}
void _platform_init(Platform_state* platform) {
_platform_init_gl_pointers();
// WebGL has no vertex array objects, OpenGL requires them. Yay. However, creating a single one
// is fine, and we can do everything else WebGL style.
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
application_init(&platform->app_context);
}
void _platform_render(Platform_state* platform) {
application_render(&platform->app_context);
glXSwapBuffers(platform->display, platform->window_glx);
}
int main(int argc, char** argv) {
bool flag_print_help = false;
bool flag_print_font_license = false;
bool flag_pack_assets = false;
bool flag_fullscreen = false;
if (argc == 2) {
Array<u8> arg = {(u8*)argv[1], (s64)strlen(argv[1])};
if (array_equal_str(arg, "--font-license")) {
flag_print_font_license = true;
} else if (array_equal_str(arg, "--pack")) {
flag_pack_assets = true;
} else if (array_equal_str(arg, "--fullscreen")) {
flag_fullscreen = true;
} else {
flag_print_help = true;
}
} else if (argc != 1) {
flag_print_help = true;
}
application_init_assets(&global_platform.app_context, flag_pack_assets);
if (flag_pack_assets) exit(0);
if (flag_print_help) {
application_print_help(&global_platform.app_context, argv[0]);
exit(2);
}
if (flag_print_font_license) {
application_print_license(&global_platform.app_context);
exit(0);
}
// Do the OpenGL and X dance. I would recommend everyone to not read this code, if at all
// possible, to preserve sanity. This should have been a single function call. If you must,
// refer to the GLX 1.4 specification, the GLX_ARB_create_context extension, and the Xlib
// specification to understand what all of this does.
if (setlocale(LC_ALL, "") == nullptr) {
fprintf(stderr, "Warning: Could not set default locale.\n");
}
// Create the display, connect to the X server
Display* display = XOpenDisplay(nullptr);
if (not display) {
fprintf(stderr, "Error: could not open display (is the DISPLAY environment variable set correctly?)\n");
exit(101);
}
global_platform.display = display;
int screen = DefaultScreen(display);
// Check for GLX 1.4 and extensions
int glx_version[] = {1, 4};
if (not glXQueryVersion(display, &glx_version[0], &glx_version[1])) {
fprintf(stderr, "Error: glX version %d.%d not present\n", glx_version[0], glx_version[1]);
exit(102);
}
char* gl_ext_present = (char*)glXQueryExtensionsString(display, screen);
char* gl_ext_want[] = {(char*)"GLX_ARB_create_context_profile"};
for (s64 i = 0; i < (s64)(sizeof(gl_ext_want) / sizeof(gl_ext_want[0])); ++i) {
if (not strstr(gl_ext_present, gl_ext_want[i])) {
fprintf(stderr, "Error: OpenGL extension %s not present\n", gl_ext_want[i]);
exit(105);
}
}
int config_size;
int config_attribs[] = {
GLX_DOUBLEBUFFER, true,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_DEPTH_SIZE, 8,
None
};
GLXFBConfig* config = glXChooseFBConfig(display, screen, config_attribs, &config_size);
//defer { XFree(config); };
if (not config or config_size == 0) {
fprintf(stderr, "Error: did not find a GLXFBConfig with the required attributes\n");
exit(103);
}
// TODO: This seems to be unnecessary? Try to test on some older systems.
// Create old OpenGL context, to be able to get the function pointer for creating the new one.
//GLXContext context_old = glXCreateNewContext(display, *config, GLX_RGBA_TYPE, 0, true);
//if (not context_old) {
// fprintf(stderr, "Error: failed to initialise old GLXContext\n");
// exit(104);
//}
glXCreateContextAttribsARB_t glXCreateContextAttribsARB
= (glXCreateContextAttribsARB_t)glXGetProcAddress((u8*)"glXCreateContextAttribsARB");
assert(glXCreateContextAttribsARB); // We already checked for the presence of the extension
//glXDestroyContext(display, context_old);
// Create an OpenGL 3.3 context
int context_attribs[] = {
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 3,
GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
None
};
GLXContext context = glXCreateContextAttribsARB(display, *config, 0, true, context_attribs);
// Create the window
XVisualInfo* visual = glXGetVisualFromFBConfig(display, *config);
assert(visual);
//defer { XFree(visual); };
XSetWindowAttributes window_attrs = {};
window_attrs.colormap = XCreateColormap(display, DefaultRootWindow(display), visual->visual, AllocNone); // Apparently you need the colormap, else XCreateWindow gives a BadMatch error. No worries, this fact features prominently in the documentation and it was no bother at all.
window_attrs.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask
| ButtonReleaseMask | StructureNotifyMask | PointerMotionMask | FocusChangeMask;
Window window = XCreateWindow(display, DefaultRootWindow(display), 0, 0, 1300, 800, 0,
visual->depth, InputOutput, visual->visual, CWColormap | CWEventMask, &window_attrs); // We pass a type of InputOutput explicitly, as visual->c_class is an illegal value for some reason. A good reason, I hope.
global_platform.window = window;
// Set up xrandr
int xrandr_event, xrandr_error;
if (XRRQueryExtension(display, &xrandr_event, &xrandr_error)) {
XRRSelectInput(display, window, RRScreenChangeNotifyMask);
XRRScreenConfiguration* config = XRRGetScreenInfo(display, window);
global_platform.rate = XRRConfigCurrentRate(config);
XRRFreeScreenConfigInfo(config);
} else {
fprintf(stderr, "Warning: Xrandr extension not present on X server, assuming refresh rate of 60 Hz.\n");
global_platform.rate = 60;
}
// Initialise window properties
linux_set_wm_prop(display, window, "WM_NAME", PROGRAM_NAME " - " PROGRAM_TITLE);
linux_set_wm_prop(display, window, "WM_ICON_NAME", PROGRAM_NAME);
linux_set_wm_class(display, window, argc, argv);
// Set WM_PROTOCOLS
Atom wm_protocols = XInternAtom(display, "WM_PROTOCOLS", true);
Atom wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", true);
Atom type_atom = XInternAtom(display, "ATOM", true);
assert(wm_protocols != None and wm_delete_window != None and type_atom != None);
XChangeProperty(display, window, wm_protocols, type_atom, 32, PropModeReplace, (u8*)&wm_delete_window, 1);
// Query some atom we will later need for the clipboard
Atom sel_primary = XInternAtom(display, "PRIMARY", true);
Atom sel_clipboard = XInternAtom(display, "CLIPBOARD", true);
Atom sel_utf8str = XInternAtom(display, "UTF8_STRING", true);
Atom sel_string = XInternAtom(display, "STRING", true);
Atom sel_target = XInternAtom(display, "SELECTION_TARGET", false); // This one is arbitrary
Atom sel_incr = XInternAtom(display, "INCR", true);
global_platform.sel_primary = sel_primary;
global_platform.sel_clipboard = sel_clipboard;
global_platform.sel_utf8str = sel_utf8str;
global_platform.sel_string = sel_string;
global_platform.sel_target = sel_target;
global_platform.sel_incr = sel_incr;
// And some atoms needed for fullscreen mode
global_platform.net_wm_state = XInternAtom(display, "_NET_WM_STATE", true);
global_platform.net_wm_state_fullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", true);
global_platform.type_atom = type_atom;
// Map the context to the window
GLXWindow window_glx = glXCreateWindow(display, *config, window, nullptr);
global_platform.window_glx = window_glx;
glXMakeContextCurrent(display, window_glx, window_glx, context); // This returns a bool, but I cannot find what it means in the spec, so just ignore it. The greatness continues.
// Do application-specific initialisation
_platform_init(&global_platform);
// Show the window
XMapWindow(display, window);
if (flag_fullscreen) linux_fullscreen(&global_platform);
int x_fd = ConnectionNumber(display);
clock_gettime(CLOCK_MONOTONIC_RAW, &global_platform.t_start);
global_platform.now = 0;
while (true) {
bool redraw = false;
if (XPending(display) <= 0) {
// No events left to process, now we redraw or wait
u64 wait = global_platform.redraw_next > global_platform.now
? global_platform.redraw_next - global_platform.now : 0;
if (wait <= 5000000000ull / global_platform.rate) {
wait = 0;
}
array_push(&global_platform.redraw_fds, pollfd {x_fd, POLLIN, 0});
timespec t;
t.tv_sec = (long)(wait / 1000000000ull);
t.tv_nsec = (long)(wait % 1000000000ull);
int code = ppoll(global_platform.redraw_fds.data, global_platform.redraw_fds.size, &t, nullptr);
auto pfd = global_platform.redraw_fds.back();
--global_platform.redraw_fds.size;
if (code > 0) {
if (pfd.revents & POLLERR) {
fprintf(stderr, "Error: polling the X fd returned POLLERR, the session is terminating, I guess?\n");
exit(2);
} else if (pfd.revents & POLLHUP) {
fprintf(stderr, "Error: polling the X fd returned POLLHUP, the session is terminating, I guess?\n");
exit(2);
} else if (pfd.revents & POLLIN) {
// Check whether there is really an event there
if (XPending(display) <= 0) continue;
// An event arrived, process.
} else {
// One of the other fds triggered, redraw
redraw = true;
}
} else if (code == 0) {
// Got timeout, redraw
redraw = true;
} else {
platform_error_printf("$ while trying to call poll");
platform_error_print();
exit(2);
}
}
if (redraw) {
simple_swap(&global_platform.redraw_fds, &global_platform.redraw_fds_result);
global_platform.redraw_fds.size = 0;
global_platform.now = platform_now_real();
global_platform.redraw_next = -1;
global_platform.keys_dirty = true;
_platform_render(&global_platform);
++global_platform.frame_count;
continue;
}
XEvent event;
XNextEvent(display, &event);
global_platform.now = platform_now_real();
switch (event.type) {
case Expose:
platform_redraw(0);
break;
case ButtonPress: {
u32 buttons[] = {Button1, Button2, Button3, Button4, Button5};
u32 keys[] = {Key::LEFT_DOWN, Key::MIDDLE_DOWN, Key::RIGHT_DOWN,
Key::SCROLL_UPWARDS, Key::SCROLL_DOWNWARDS};
for (s64 i = 0; i < sizeof(keys) / sizeof(keys[0]); ++i) {
if (event.xbutton.button == buttons[i]) {
Key key = Key::create_mouse(keys[i], event.xbutton.x, event.xbutton.y);
array_push(&global_platform.app_context.input_queue, key);
platform_redraw(0);
}
}
if (event.xbutton.button == Button2) {
XConvertSelection(display, sel_primary, sel_utf8str, sel_target, window, event.xbutton.time);
}
} break;
case ButtonRelease: {
u32 buttons[] = {Button1, Button2, Button3};
u32 keys[] = {Key::LEFT_UP, Key::MIDDLE_UP, Key::RIGHT_UP};
for (s64 i = 0; i < sizeof(keys) / sizeof(keys[0]); ++i) {
if (event.xbutton.button == buttons[i]) {
Key key = Key::create_mouse(keys[i], event.xbutton.x, event.xbutton.y);
array_push(&global_platform.app_context.input_queue, key);
platform_redraw(0);
}
}
} break;
case MotionNotify: {
Key key = Key::create_mouse(Key::MOTION, event.xmotion.x, event.xmotion.y);
array_push(&global_platform.app_context.input_queue, key);
platform_redraw(0);
} break;
case KeyPress: {
auto* iq = &global_platform.app_context.input_queue;
linux_get_event_key(iq, event.xkey);
if (iq->size and (*iq)[iq->size-1].type == Key::SPECIAL and (*iq)[iq->size-1].special == Key::C_PASTE) {
// Query the contents of the clipboard, we need to wait for them to arrive
XConvertSelection(display, sel_clipboard, sel_utf8str, sel_target, window, event.xkey.time);
--iq->size;
} else if (iq->size and (*iq)[iq->size-1].type == Key::SPECIAL and (*iq)[iq->size-1].special == Key::F11) {
// Toggle fullscreen
linux_fullscreen(&global_platform);
--iq->size;
} else {
platform_redraw(0);
}
} break;
case SelectionNotify:
linux_handle_selection_response(&global_platform, &event.xselection);
platform_redraw(0);
break;
case SelectionRequest:
linux_handle_selection_request(&global_platform, &event.xselectionrequest);
break;
case MappingNotify:
if (event.xmapping.request == MappingModifier or event.xmapping.request == MappingKeyboard) {
XRefreshKeyboardMapping(&event.xmapping);
}
break;
case ClientMessage:
if (event.xclient.message_type == wm_protocols and event.xclient.data.l[0] - wm_delete_window == 0) {
array_push(&global_platform.app_context.input_queue, Key::create_special(Key::C_QUIT, 0));
platform_redraw(0);
}
break;
case ConfigureNotify:
application_handle_resize(&global_platform.app_context, event.xconfigure.width, event.xconfigure.height);
break;
default:
break;
}
if (event.type == xrandr_event + RRScreenChangeNotify) {
assert(XRRUpdateConfiguration(&event));
XRRScreenConfiguration* config = XRRGetScreenInfo(display, window);
global_platform.rate = XRRConfigCurrentRate(config);
XRRFreeScreenConfigInfo(config);
}
}
// Memory freed by OS
}