aboutsummaryrefslogtreecommitdiff
path: root/src/x11_window.c
blob: 734a1c4be3ff5a64b510c8a477137cfa3f1e72f4 (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
#include "window.h"

#include <assert.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <GL/gl.h>
#include <GL/glx.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>

#include <xcb/xcb.h>
#include <xkbcommon/xkbcommon-x11.h>

#include "keyboard.h"
#include "log.h"

struct imv_window {
  Display    *x_display;
  Window     x_window;
  GLXContext x_glc;
  Atom       x_state;
  Atom       x_fullscreen;
  int width;
  int height;
  struct {
    struct {
      int x, y;
    } last;
    struct {
      int x, y;
    } current;
    bool mouse1;
  } pointer;

  struct imv_keyboard *keyboard;
  int pipe_fds[2];
  char *keymap;
};

static void set_nonblocking(int fd)
{
  int flags = fcntl(fd, F_GETFL);
  assert(flags != -1);
  flags |= O_NONBLOCK;
  int rc = fcntl(fd, F_SETFL, flags);
  assert(rc != -1);
}

static void setup_keymap(struct imv_window *window)
{
  xcb_connection_t *conn = xcb_connect(NULL, NULL);
  if (xcb_connection_has_error(conn)) {
    imv_log(IMV_ERROR, "x11_window: Failed to load keymap. Could not connect via xcb.");
    return;
  }

  if (!xkb_x11_setup_xkb_extension(conn,
        XKB_X11_MIN_MAJOR_XKB_VERSION,
        XKB_X11_MIN_MINOR_XKB_VERSION,
        0, NULL, NULL, NULL, NULL)) {
    xcb_disconnect(conn);
    imv_log(IMV_ERROR, "x11_window: Failed to load keymap. xkb extension not supported by server.");
    return;
  }

  int32_t device = xkb_x11_get_core_keyboard_device_id(conn);

  struct xkb_context *context = xkb_context_new(0);
  if (!context) {
    xcb_disconnect(conn);
    imv_log(IMV_ERROR, "x11_window: Failed to load keymap. Failed to initialise xkb context.");
    return;
  }

  struct xkb_keymap *keymap =
    xkb_x11_keymap_new_from_device(context, conn, device, 0);
  if (keymap) {
    window->keymap = xkb_keymap_get_as_string(keymap, XKB_KEYMAP_USE_ORIGINAL_FORMAT);
  } else {
    imv_log(IMV_ERROR, "x11_window: Failed to load keymap. xkb_x11_keymap_new_from_device returned NULL.");
  }
  xkb_context_unref(context);

  xcb_disconnect(conn);
}

struct imv_window *imv_window_create(int w, int h, const char *title)
{
  /* Ensure event writes will always be atomic */
  assert(sizeof(struct imv_event) <= PIPE_BUF);

  struct imv_window *window = calloc(1, sizeof *window);
  window->pointer.last.x = -1;
  window->pointer.last.y = -1;
  pipe(window->pipe_fds);
  set_nonblocking(window->pipe_fds[0]);
  set_nonblocking(window->pipe_fds[1]);

  window->x_display = XOpenDisplay(NULL);
  assert(window->x_display);
  Window root = DefaultRootWindow(window->x_display);
  assert(root);
  
  GLint att[] = {
    GLX_RGBA,
    GLX_DEPTH_SIZE,
    24,
    GLX_DOUBLEBUFFER,
    None
  };

  XVisualInfo *vi = glXChooseVisual(window->x_display, 0, att);
  assert(vi);

  Colormap cmap = XCreateColormap(window->x_display, root,
      vi->visual, AllocNone);

  XSetWindowAttributes wa = {
    .colormap = cmap,
    .event_mask = ExposureMask | KeyPressMask | KeyReleaseMask
                | ButtonPressMask | ButtonReleaseMask | PointerMotionMask
  };

  window->x_window = XCreateWindow(window->x_display, root, 0, 0, w, h,
      0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &wa);

  window->x_state = XInternAtom(window->x_display, "_NET_WM_STATE", true);
  window->x_fullscreen = XInternAtom(window->x_display, "_NET_WM_STATE_FULLSCREEN", true);

  XClassHint hint = {
    .res_name = "imv",
    .res_class= "imv",
  };
  XSetClassHint(window->x_display, window->x_window, &hint);
  XMapWindow(window->x_display, window->x_window);
  XStoreName(window->x_display, window->x_window, title);

  window->x_glc = glXCreateContext(window->x_display, vi, NULL, GL_TRUE);
  assert(window->x_glc);
  glXMakeCurrent(window->x_display, window->x_window, window->x_glc);

  window->keyboard = imv_keyboard_create();
  assert(window->keyboard);

  setup_keymap(window);
  imv_keyboard_set_keymap(window->keyboard, window->keymap);

  return window;
}

void imv_window_free(struct imv_window *window)
{
  imv_keyboard_free(window->keyboard);
  close(window->pipe_fds[0]);
  close(window->pipe_fds[1]);
  glXDestroyContext(window->x_display, window->x_glc);
  XCloseDisplay(window->x_display);
  free(window->keymap);
  free(window);
}

void imv_window_clear(struct imv_window *window, unsigned char r,
    unsigned char g, unsigned char b)
{
  (void)window;
  glClearColor(r / 255.0f, g / 255.0f, b / 255.0f, 1.0);
  glClear(GL_COLOR_BUFFER_BIT);
}

void imv_window_get_size(struct imv_window *window, int *w, int *h)
{
  if (w) {
    *w = window->width;
  }
  if (h) {
    *h = window->height;
  }
}

void imv_window_get_framebuffer_size(struct imv_window *window, int *w, int *h)
{
  if (w) {
    *w = window->width;
  }
  if (h) {
    *h = window->height;
  }
}

void imv_window_set_title(struct imv_window *window, const char *title)
{
  XStoreName(window->x_display, window->x_window, title);
}

bool imv_window_is_fullscreen(struct imv_window *window)
{
  size_t count = 0;
  Atom type;
  int format;
  size_t after;
  Atom *props = NULL;
  XGetWindowProperty(window->x_display, window->x_window, window->x_state,
      0, 1024, False, XA_ATOM, &type, &format, &count, &after, (unsigned char**)&props);

  bool fullscreen = false;
  for (size_t i = 0; i < count; ++i) {
    if (props[i] == window->x_fullscreen) {
      fullscreen = true;
      break;
    }
  }
  XFree(props);
  return fullscreen;
}

void imv_window_set_fullscreen(struct imv_window *window, bool fullscreen)
{
  Window root = DefaultRootWindow(window->x_display);
  XEvent event = {
    .xclient = {
      .type = ClientMessage,
      .window = window->x_window,
      .format = 32,
      .message_type = window->x_state,
      .data = {
        .l = {
          (fullscreen ? 1 : 0),
          window->x_fullscreen,
          0,
          1
        }
      }
    }
  };
  XSendEvent(window->x_display, root, False,
      SubstructureNotifyMask | SubstructureRedirectMask, &event );
}

bool imv_window_get_mouse_button(struct imv_window *window, int button)
{
  if (button == 1) {
    return window->pointer.mouse1;
  }
  return false;
}

void imv_window_get_mouse_position(struct imv_window *window, double *x, double *y)
{
  if (x) {
    *x = window->pointer.current.x;
  }
  if (y) {
    *y = window->pointer.current.y;
  }
}

void imv_window_present(struct imv_window *window)
{
  glXSwapBuffers(window->x_display, window->x_window);
}

void imv_window_wait_for_event(struct imv_window *window, double timeout)
{
  struct pollfd fds[] = {
    {.fd = ConnectionNumber(window->x_display), .events = POLLIN},
    {.fd = window->pipe_fds[0], .events = POLLIN}
  };
  nfds_t nfds = sizeof fds / sizeof *fds;

  poll(fds, nfds, timeout * 1000);
}

void imv_window_push_event(struct imv_window *window, struct imv_event *e)
{
  /* Push it down the pipe */
  write(window->pipe_fds[1], e, sizeof *e);
}

static void handle_keyboard(struct imv_window *window, imv_event_handler handler, void *data, const XEvent *xev)
{
  imv_keyboard_update_mods(window->keyboard, (int)xev->xkey.state, 0, 0);

  bool pressed = xev->type == KeyPress;
  int scancode = xev->xkey.keycode - 8;
  imv_keyboard_update_key(window->keyboard, scancode, pressed);

  if (!pressed) {
    return;
  }

  char keyname[32] = {0};
  imv_keyboard_keyname(window->keyboard, scancode, keyname, sizeof keyname);

  char text[64] = {0};
  imv_keyboard_get_text(window->keyboard, scancode, text, sizeof text);

  char *desc = imv_keyboard_describe_key(window->keyboard, scancode);
  if (!desc) {
    desc = strdup("");
  }

  struct imv_event e = {
    .type = IMV_EVENT_KEYBOARD,
    .data = {
      .keyboard = {
        .scancode = scancode,
        .keyname = keyname,
        .description = desc,
        .text = text,
      }
    }
  };

  if (handler) {
    handler(data, &e);
  }
  free(desc);
}

void imv_window_pump_events(struct imv_window *window, imv_event_handler handler, void *data)
{
  XEvent xev;

  while (XPending(window->x_display)) {
    XNextEvent(window->x_display, &xev);

    if (xev.type == Expose) {
      XWindowAttributes wa;
      XGetWindowAttributes(window->x_display, window->x_window, &wa);
      window->width = wa.width;
      window->height = wa.height;
      glViewport(0, 0, wa.width, wa.height);
      struct imv_event e = {
        .type = IMV_EVENT_RESIZE,
        .data = {
          .resize = {
            .width = wa.width,
            .height = wa.height,
            .buffer_width = wa.width,
            .buffer_height = wa.height
          }
        }
      };
      if (handler) {
        handler(data, &e);
      }
    } else if (xev.type == KeyPress || xev.type == KeyRelease) {
      handle_keyboard(window, handler, data, &xev);
    } else if (xev.type == ButtonPress || xev.type == ButtonRelease) {
      if (xev.xbutton.button == Button1) {
        window->pointer.mouse1 = xev.type == ButtonPress;
        struct imv_event e = {
          .type = IMV_EVENT_MOUSE_BUTTON,
          .data = {
            .mouse_button = {
              .button = 1,
              .pressed = xev.type == ButtonPress
            }
          }
        };
        if (handler) {
          handler(data, &e);
        }
      } else if (xev.xbutton.button == Button4 || xev.xbutton.button == Button5) {
        struct imv_event e = {
          .type = IMV_EVENT_MOUSE_SCROLL,
          .data = {
            .mouse_scroll = {
              .dx = 0,
              .dy = xev.xbutton.button == Button4 ? -1 : 1
            }
          }
        };
        if (handler) {
          handler(data, &e);
        }
      }
    } else if (xev.type == MotionNotify) {
      window->pointer.current.x = xev.xmotion.x;
      window->pointer.current.y = xev.xmotion.y;
      int dx = window->pointer.current.x - window->pointer.last.x;
      int dy = window->pointer.current.y - window->pointer.last.y;
      if (window->pointer.last.x == -1) {
        dx = 0;
      }
      if (window->pointer.last.y == -1) {
        dy = 0;
      }
      window->pointer.last.x = window->pointer.current.x;
      window->pointer.last.y = window->pointer.current.y;

      struct imv_event e = {
        .type = IMV_EVENT_MOUSE_MOTION,
        .data = {
          .mouse_motion = {
            .x = window->pointer.current.x,
            .y = window->pointer.current.y,
            .dx = dx,
            .dy = dy
          }
        }
      };
      if (handler) {
        handler(data, &e);
      }
    }
  }

  /* Handle any events in the pipe */
  while (1) {
    struct imv_event e;
    ssize_t len = read(window->pipe_fds[0], &e, sizeof e);
    if (len <= 0) {
      break;
    }
    assert(len == sizeof e);
    if (handler) {
      handler(data, &e);
    }
  }
}

const char *imv_window_get_keymap(struct imv_window *window)
{
  return window->keymap;
}