]> git.sesse.net Git - pistorm/blob - raylib_pi4_test/external/glfw/src/wl_window.c
7b315d70ff3a3615387a43b7c4e39d37019829ec
[pistorm] / raylib_pi4_test / external / glfw / src / wl_window.c
1 //========================================================================
2 // GLFW 3.4 Wayland - www.glfw.org
3 //------------------------------------------------------------------------
4 // Copyright (c) 2014 Jonas Ådahl <jadahl@gmail.com>
5 //
6 // This software is provided 'as-is', without any express or implied
7 // warranty. In no event will the authors be held liable for any damages
8 // arising from the use of this software.
9 //
10 // Permission is granted to anyone to use this software for any purpose,
11 // including commercial applications, and to alter it and redistribute it
12 // freely, subject to the following restrictions:
13 //
14 // 1. The origin of this software must not be misrepresented; you must not
15 //    claim that you wrote the original software. If you use this software
16 //    in a product, an acknowledgment in the product documentation would
17 //    be appreciated but is not required.
18 //
19 // 2. Altered source versions must be plainly marked as such, and must not
20 //    be misrepresented as being the original software.
21 //
22 // 3. This notice may not be removed or altered from any source
23 //    distribution.
24 //
25 //========================================================================
26 // It is fine to use C99 in this file because it will not be built with VS
27 //========================================================================
28
29 #define _GNU_SOURCE
30
31 #include "internal.h"
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <errno.h>
36 #include <unistd.h>
37 #include <string.h>
38 #include <fcntl.h>
39 #include <sys/mman.h>
40 #include <sys/timerfd.h>
41 #include <poll.h>
42
43
44 static int createTmpfileCloexec(char* tmpname)
45 {
46     int fd;
47
48     fd = mkostemp(tmpname, O_CLOEXEC);
49     if (fd >= 0)
50         unlink(tmpname);
51
52     return fd;
53 }
54
55 /*
56  * Create a new, unique, anonymous file of the given size, and
57  * return the file descriptor for it. The file descriptor is set
58  * CLOEXEC. The file is immediately suitable for mmap()'ing
59  * the given size at offset zero.
60  *
61  * The file should not have a permanent backing store like a disk,
62  * but may have if XDG_RUNTIME_DIR is not properly implemented in OS.
63  *
64  * The file name is deleted from the file system.
65  *
66  * The file is suitable for buffer sharing between processes by
67  * transmitting the file descriptor over Unix sockets using the
68  * SCM_RIGHTS methods.
69  *
70  * posix_fallocate() is used to guarantee that disk space is available
71  * for the file at the given size. If disk space is insufficient, errno
72  * is set to ENOSPC. If posix_fallocate() is not supported, program may
73  * receive SIGBUS on accessing mmap()'ed file contents instead.
74  */
75 static int createAnonymousFile(off_t size)
76 {
77     static const char template[] = "/glfw-shared-XXXXXX";
78     const char* path;
79     char* name;
80     int fd;
81     int ret;
82
83 #ifdef HAVE_MEMFD_CREATE
84     fd = memfd_create("glfw-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING);
85     if (fd >= 0)
86     {
87         // We can add this seal before calling posix_fallocate(), as the file
88         // is currently zero-sized anyway.
89         //
90         // There is also no need to check for the return value, we couldn’t do
91         // anything with it anyway.
92         fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_SEAL);
93     }
94     else
95 #elif defined(SHM_ANON)
96     fd = shm_open(SHM_ANON, O_RDWR | O_CLOEXEC, 0600);
97     if (fd < 0)
98 #endif
99     {
100         path = getenv("XDG_RUNTIME_DIR");
101         if (!path)
102         {
103             errno = ENOENT;
104             return -1;
105         }
106
107         name = calloc(strlen(path) + sizeof(template), 1);
108         strcpy(name, path);
109         strcat(name, template);
110
111         fd = createTmpfileCloexec(name);
112         free(name);
113         if (fd < 0)
114             return -1;
115     }
116
117 #if defined(SHM_ANON)
118     // posix_fallocate does not work on SHM descriptors
119     ret = ftruncate(fd, size);
120 #else
121     ret = posix_fallocate(fd, 0, size);
122 #endif
123     if (ret != 0)
124     {
125         close(fd);
126         errno = ret;
127         return -1;
128     }
129     return fd;
130 }
131
132 static struct wl_buffer* createShmBuffer(const GLFWimage* image)
133 {
134     struct wl_shm_pool* pool;
135     struct wl_buffer* buffer;
136     int stride = image->width * 4;
137     int length = image->width * image->height * 4;
138     void* data;
139     int fd, i;
140
141     fd = createAnonymousFile(length);
142     if (fd < 0)
143     {
144         _glfwInputError(GLFW_PLATFORM_ERROR,
145                         "Wayland: Creating a buffer file for %d B failed: %s",
146                         length, strerror(errno));
147         return NULL;
148     }
149
150     data = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
151     if (data == MAP_FAILED)
152     {
153         _glfwInputError(GLFW_PLATFORM_ERROR,
154                         "Wayland: mmap failed: %s", strerror(errno));
155         close(fd);
156         return NULL;
157     }
158
159     pool = wl_shm_create_pool(_glfw.wl.shm, fd, length);
160
161     close(fd);
162     unsigned char* source = (unsigned char*) image->pixels;
163     unsigned char* target = data;
164     for (i = 0;  i < image->width * image->height;  i++, source += 4)
165     {
166         unsigned int alpha = source[3];
167
168         *target++ = (unsigned char) ((source[2] * alpha) / 255);
169         *target++ = (unsigned char) ((source[1] * alpha) / 255);
170         *target++ = (unsigned char) ((source[0] * alpha) / 255);
171         *target++ = (unsigned char) alpha;
172     }
173
174     buffer =
175         wl_shm_pool_create_buffer(pool, 0,
176                                   image->width,
177                                   image->height,
178                                   stride, WL_SHM_FORMAT_ARGB8888);
179     munmap(data, length);
180     wl_shm_pool_destroy(pool);
181
182     return buffer;
183 }
184
185 static void createDecoration(_GLFWdecorationWayland* decoration,
186                              struct wl_surface* parent,
187                              struct wl_buffer* buffer, GLFWbool opaque,
188                              int x, int y,
189                              int width, int height)
190 {
191     struct wl_region* region;
192
193     decoration->surface = wl_compositor_create_surface(_glfw.wl.compositor);
194     decoration->subsurface =
195         wl_subcompositor_get_subsurface(_glfw.wl.subcompositor,
196                                         decoration->surface, parent);
197     wl_subsurface_set_position(decoration->subsurface, x, y);
198     decoration->viewport = wp_viewporter_get_viewport(_glfw.wl.viewporter,
199                                                       decoration->surface);
200     wp_viewport_set_destination(decoration->viewport, width, height);
201     wl_surface_attach(decoration->surface, buffer, 0, 0);
202
203     if (opaque)
204     {
205         region = wl_compositor_create_region(_glfw.wl.compositor);
206         wl_region_add(region, 0, 0, width, height);
207         wl_surface_set_opaque_region(decoration->surface, region);
208         wl_surface_commit(decoration->surface);
209         wl_region_destroy(region);
210     }
211     else
212         wl_surface_commit(decoration->surface);
213 }
214
215 static void createDecorations(_GLFWwindow* window)
216 {
217     unsigned char data[] = { 224, 224, 224, 255 };
218     const GLFWimage image = { 1, 1, data };
219     GLFWbool opaque = (data[3] == 255);
220
221     if (!_glfw.wl.viewporter || !window->decorated || window->wl.decorations.serverSide)
222         return;
223
224     if (!window->wl.decorations.buffer)
225         window->wl.decorations.buffer = createShmBuffer(&image);
226     if (!window->wl.decorations.buffer)
227         return;
228
229     createDecoration(&window->wl.decorations.top, window->wl.surface,
230                      window->wl.decorations.buffer, opaque,
231                      0, -_GLFW_DECORATION_TOP,
232                      window->wl.width, _GLFW_DECORATION_TOP);
233     createDecoration(&window->wl.decorations.left, window->wl.surface,
234                      window->wl.decorations.buffer, opaque,
235                      -_GLFW_DECORATION_WIDTH, -_GLFW_DECORATION_TOP,
236                      _GLFW_DECORATION_WIDTH, window->wl.height + _GLFW_DECORATION_TOP);
237     createDecoration(&window->wl.decorations.right, window->wl.surface,
238                      window->wl.decorations.buffer, opaque,
239                      window->wl.width, -_GLFW_DECORATION_TOP,
240                      _GLFW_DECORATION_WIDTH, window->wl.height + _GLFW_DECORATION_TOP);
241     createDecoration(&window->wl.decorations.bottom, window->wl.surface,
242                      window->wl.decorations.buffer, opaque,
243                      -_GLFW_DECORATION_WIDTH, window->wl.height,
244                      window->wl.width + _GLFW_DECORATION_HORIZONTAL, _GLFW_DECORATION_WIDTH);
245 }
246
247 static void destroyDecoration(_GLFWdecorationWayland* decoration)
248 {
249     if (decoration->surface)
250         wl_surface_destroy(decoration->surface);
251     if (decoration->subsurface)
252         wl_subsurface_destroy(decoration->subsurface);
253     if (decoration->viewport)
254         wp_viewport_destroy(decoration->viewport);
255     decoration->surface = NULL;
256     decoration->subsurface = NULL;
257     decoration->viewport = NULL;
258 }
259
260 static void destroyDecorations(_GLFWwindow* window)
261 {
262     destroyDecoration(&window->wl.decorations.top);
263     destroyDecoration(&window->wl.decorations.left);
264     destroyDecoration(&window->wl.decorations.right);
265     destroyDecoration(&window->wl.decorations.bottom);
266 }
267
268 static void xdgDecorationHandleConfigure(void* data,
269                                          struct zxdg_toplevel_decoration_v1* decoration,
270                                          uint32_t mode)
271 {
272     _GLFWwindow* window = data;
273
274     window->wl.decorations.serverSide = (mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
275
276     if (!window->wl.decorations.serverSide)
277         createDecorations(window);
278 }
279
280 static const struct zxdg_toplevel_decoration_v1_listener xdgDecorationListener = {
281     xdgDecorationHandleConfigure,
282 };
283
284 // Makes the surface considered as XRGB instead of ARGB.
285 static void setOpaqueRegion(_GLFWwindow* window)
286 {
287     struct wl_region* region;
288
289     region = wl_compositor_create_region(_glfw.wl.compositor);
290     if (!region)
291         return;
292
293     wl_region_add(region, 0, 0, window->wl.width, window->wl.height);
294     wl_surface_set_opaque_region(window->wl.surface, region);
295     wl_surface_commit(window->wl.surface);
296     wl_region_destroy(region);
297 }
298
299
300 static void resizeWindow(_GLFWwindow* window)
301 {
302     int scale = window->wl.scale;
303     int scaledWidth = window->wl.width * scale;
304     int scaledHeight = window->wl.height * scale;
305     wl_egl_window_resize(window->wl.native, scaledWidth, scaledHeight, 0, 0);
306     if (!window->wl.transparent)
307         setOpaqueRegion(window);
308     _glfwInputFramebufferSize(window, scaledWidth, scaledHeight);
309     _glfwInputWindowContentScale(window, scale, scale);
310
311     if (!window->wl.decorations.top.surface)
312         return;
313
314     // Top decoration.
315     wp_viewport_set_destination(window->wl.decorations.top.viewport,
316                                 window->wl.width, _GLFW_DECORATION_TOP);
317     wl_surface_commit(window->wl.decorations.top.surface);
318
319     // Left decoration.
320     wp_viewport_set_destination(window->wl.decorations.left.viewport,
321                                 _GLFW_DECORATION_WIDTH, window->wl.height + _GLFW_DECORATION_TOP);
322     wl_surface_commit(window->wl.decorations.left.surface);
323
324     // Right decoration.
325     wl_subsurface_set_position(window->wl.decorations.right.subsurface,
326                                window->wl.width, -_GLFW_DECORATION_TOP);
327     wp_viewport_set_destination(window->wl.decorations.right.viewport,
328                                 _GLFW_DECORATION_WIDTH, window->wl.height + _GLFW_DECORATION_TOP);
329     wl_surface_commit(window->wl.decorations.right.surface);
330
331     // Bottom decoration.
332     wl_subsurface_set_position(window->wl.decorations.bottom.subsurface,
333                                -_GLFW_DECORATION_WIDTH, window->wl.height);
334     wp_viewport_set_destination(window->wl.decorations.bottom.viewport,
335                                 window->wl.width + _GLFW_DECORATION_HORIZONTAL, _GLFW_DECORATION_WIDTH);
336     wl_surface_commit(window->wl.decorations.bottom.surface);
337 }
338
339 static void checkScaleChange(_GLFWwindow* window)
340 {
341     int scale = 1;
342     int i;
343     int monitorScale;
344
345     // Check if we will be able to set the buffer scale or not.
346     if (_glfw.wl.compositorVersion < 3)
347         return;
348
349     // Get the scale factor from the highest scale monitor.
350     for (i = 0; i < window->wl.monitorsCount; ++i)
351     {
352         monitorScale = window->wl.monitors[i]->wl.scale;
353         if (scale < monitorScale)
354             scale = monitorScale;
355     }
356
357     // Only change the framebuffer size if the scale changed.
358     if (scale != window->wl.scale)
359     {
360         window->wl.scale = scale;
361         wl_surface_set_buffer_scale(window->wl.surface, scale);
362         resizeWindow(window);
363     }
364 }
365
366 static void surfaceHandleEnter(void *data,
367                                struct wl_surface *surface,
368                                struct wl_output *output)
369 {
370     _GLFWwindow* window = data;
371     _GLFWmonitor* monitor = wl_output_get_user_data(output);
372
373     if (window->wl.monitorsCount + 1 > window->wl.monitorsSize)
374     {
375         ++window->wl.monitorsSize;
376         window->wl.monitors =
377             realloc(window->wl.monitors,
378                     window->wl.monitorsSize * sizeof(_GLFWmonitor*));
379     }
380
381     window->wl.monitors[window->wl.monitorsCount++] = monitor;
382
383     checkScaleChange(window);
384 }
385
386 static void surfaceHandleLeave(void *data,
387                                struct wl_surface *surface,
388                                struct wl_output *output)
389 {
390     _GLFWwindow* window = data;
391     _GLFWmonitor* monitor = wl_output_get_user_data(output);
392     GLFWbool found;
393     int i;
394
395     for (i = 0, found = GLFW_FALSE; i < window->wl.monitorsCount - 1; ++i)
396     {
397         if (monitor == window->wl.monitors[i])
398             found = GLFW_TRUE;
399         if (found)
400             window->wl.monitors[i] = window->wl.monitors[i + 1];
401     }
402     window->wl.monitors[--window->wl.monitorsCount] = NULL;
403
404     checkScaleChange(window);
405 }
406
407 static const struct wl_surface_listener surfaceListener = {
408     surfaceHandleEnter,
409     surfaceHandleLeave
410 };
411
412 static void setIdleInhibitor(_GLFWwindow* window, GLFWbool enable)
413 {
414     if (enable && !window->wl.idleInhibitor && _glfw.wl.idleInhibitManager)
415     {
416         window->wl.idleInhibitor =
417             zwp_idle_inhibit_manager_v1_create_inhibitor(
418                 _glfw.wl.idleInhibitManager, window->wl.surface);
419         if (!window->wl.idleInhibitor)
420             _glfwInputError(GLFW_PLATFORM_ERROR,
421                             "Wayland: Idle inhibitor creation failed");
422     }
423     else if (!enable && window->wl.idleInhibitor)
424     {
425         zwp_idle_inhibitor_v1_destroy(window->wl.idleInhibitor);
426         window->wl.idleInhibitor = NULL;
427     }
428 }
429
430 static GLFWbool createSurface(_GLFWwindow* window,
431                               const _GLFWwndconfig* wndconfig)
432 {
433     window->wl.surface = wl_compositor_create_surface(_glfw.wl.compositor);
434     if (!window->wl.surface)
435         return GLFW_FALSE;
436
437     wl_surface_add_listener(window->wl.surface,
438                             &surfaceListener,
439                             window);
440
441     wl_surface_set_user_data(window->wl.surface, window);
442
443     window->wl.native = wl_egl_window_create(window->wl.surface,
444                                              wndconfig->width,
445                                              wndconfig->height);
446     if (!window->wl.native)
447         return GLFW_FALSE;
448
449     window->wl.width = wndconfig->width;
450     window->wl.height = wndconfig->height;
451     window->wl.scale = 1;
452
453     if (!window->wl.transparent)
454         setOpaqueRegion(window);
455
456     return GLFW_TRUE;
457 }
458
459 static void setFullscreen(_GLFWwindow* window, _GLFWmonitor* monitor,
460                           int refreshRate)
461 {
462     if (window->wl.xdg.toplevel)
463     {
464         xdg_toplevel_set_fullscreen(
465             window->wl.xdg.toplevel,
466             monitor->wl.output);
467     }
468     setIdleInhibitor(window, GLFW_TRUE);
469     if (!window->wl.decorations.serverSide)
470         destroyDecorations(window);
471 }
472
473 static void xdgToplevelHandleConfigure(void* data,
474                                        struct xdg_toplevel* toplevel,
475                                        int32_t width,
476                                        int32_t height,
477                                        struct wl_array* states)
478 {
479     _GLFWwindow* window = data;
480     float aspectRatio;
481     float targetRatio;
482     uint32_t* state;
483     GLFWbool maximized = GLFW_FALSE;
484     GLFWbool fullscreen = GLFW_FALSE;
485     GLFWbool activated = GLFW_FALSE;
486
487     wl_array_for_each(state, states)
488     {
489         switch (*state)
490         {
491             case XDG_TOPLEVEL_STATE_MAXIMIZED:
492                 maximized = GLFW_TRUE;
493                 break;
494             case XDG_TOPLEVEL_STATE_FULLSCREEN:
495                 fullscreen = GLFW_TRUE;
496                 break;
497             case XDG_TOPLEVEL_STATE_RESIZING:
498                 break;
499             case XDG_TOPLEVEL_STATE_ACTIVATED:
500                 activated = GLFW_TRUE;
501                 break;
502         }
503     }
504
505     if (width != 0 && height != 0)
506     {
507         if (!maximized && !fullscreen)
508         {
509             if (window->numer != GLFW_DONT_CARE && window->denom != GLFW_DONT_CARE)
510             {
511                 aspectRatio = (float)width / (float)height;
512                 targetRatio = (float)window->numer / (float)window->denom;
513                 if (aspectRatio < targetRatio)
514                     height = width / targetRatio;
515                 else if (aspectRatio > targetRatio)
516                     width = height * targetRatio;
517             }
518         }
519
520         _glfwInputWindowSize(window, width, height);
521         _glfwPlatformSetWindowSize(window, width, height);
522         _glfwInputWindowDamage(window);
523     }
524
525     if (window->wl.wasFullscreen && window->autoIconify)
526     {
527         if (!activated || !fullscreen)
528         {
529             _glfwPlatformIconifyWindow(window);
530             window->wl.wasFullscreen = GLFW_FALSE;
531         }
532     }
533     if (fullscreen && activated)
534         window->wl.wasFullscreen = GLFW_TRUE;
535     _glfwInputWindowFocus(window, activated);
536 }
537
538 static void xdgToplevelHandleClose(void* data,
539                                    struct xdg_toplevel* toplevel)
540 {
541     _GLFWwindow* window = data;
542     _glfwInputWindowCloseRequest(window);
543 }
544
545 static const struct xdg_toplevel_listener xdgToplevelListener = {
546     xdgToplevelHandleConfigure,
547     xdgToplevelHandleClose
548 };
549
550 static void xdgSurfaceHandleConfigure(void* data,
551                                       struct xdg_surface* surface,
552                                       uint32_t serial)
553 {
554     xdg_surface_ack_configure(surface, serial);
555 }
556
557 static const struct xdg_surface_listener xdgSurfaceListener = {
558     xdgSurfaceHandleConfigure
559 };
560
561 static void setXdgDecorations(_GLFWwindow* window)
562 {
563     if (_glfw.wl.decorationManager)
564     {
565         window->wl.xdg.decoration =
566             zxdg_decoration_manager_v1_get_toplevel_decoration(
567                 _glfw.wl.decorationManager, window->wl.xdg.toplevel);
568         zxdg_toplevel_decoration_v1_add_listener(window->wl.xdg.decoration,
569                                                  &xdgDecorationListener,
570                                                  window);
571         zxdg_toplevel_decoration_v1_set_mode(
572             window->wl.xdg.decoration,
573             ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
574     }
575     else
576     {
577         window->wl.decorations.serverSide = GLFW_FALSE;
578         createDecorations(window);
579     }
580 }
581
582 static GLFWbool createXdgSurface(_GLFWwindow* window)
583 {
584     window->wl.xdg.surface = xdg_wm_base_get_xdg_surface(_glfw.wl.wmBase,
585                                                          window->wl.surface);
586     if (!window->wl.xdg.surface)
587     {
588         _glfwInputError(GLFW_PLATFORM_ERROR,
589                         "Wayland: xdg-surface creation failed");
590         return GLFW_FALSE;
591     }
592
593     xdg_surface_add_listener(window->wl.xdg.surface,
594                              &xdgSurfaceListener,
595                              window);
596
597     window->wl.xdg.toplevel = xdg_surface_get_toplevel(window->wl.xdg.surface);
598     if (!window->wl.xdg.toplevel)
599     {
600         _glfwInputError(GLFW_PLATFORM_ERROR,
601                         "Wayland: xdg-toplevel creation failed");
602         return GLFW_FALSE;
603     }
604
605     xdg_toplevel_add_listener(window->wl.xdg.toplevel,
606                               &xdgToplevelListener,
607                               window);
608
609     if (window->wl.title)
610         xdg_toplevel_set_title(window->wl.xdg.toplevel, window->wl.title);
611
612     if (window->minwidth != GLFW_DONT_CARE && window->minheight != GLFW_DONT_CARE)
613         xdg_toplevel_set_min_size(window->wl.xdg.toplevel,
614                                   window->minwidth, window->minheight);
615     if (window->maxwidth != GLFW_DONT_CARE && window->maxheight != GLFW_DONT_CARE)
616         xdg_toplevel_set_max_size(window->wl.xdg.toplevel,
617                                   window->maxwidth, window->maxheight);
618
619     if (window->monitor)
620     {
621         xdg_toplevel_set_fullscreen(window->wl.xdg.toplevel,
622                                     window->monitor->wl.output);
623         setIdleInhibitor(window, GLFW_TRUE);
624     }
625     else if (window->wl.maximized)
626     {
627         xdg_toplevel_set_maximized(window->wl.xdg.toplevel);
628         setIdleInhibitor(window, GLFW_FALSE);
629         setXdgDecorations(window);
630     }
631     else
632     {
633         setIdleInhibitor(window, GLFW_FALSE);
634         setXdgDecorations(window);
635     }
636
637     wl_surface_commit(window->wl.surface);
638     wl_display_roundtrip(_glfw.wl.display);
639
640     return GLFW_TRUE;
641 }
642
643 static void setCursorImage(_GLFWwindow* window,
644                            _GLFWcursorWayland* cursorWayland)
645 {
646     struct itimerspec timer = {};
647     struct wl_cursor* wlCursor = cursorWayland->cursor;
648     struct wl_cursor_image* image;
649     struct wl_buffer* buffer;
650     struct wl_surface* surface = _glfw.wl.cursorSurface;
651     int scale = 1;
652
653     if (!wlCursor)
654         buffer = cursorWayland->buffer;
655     else
656     {
657         if (window->wl.scale > 1 && cursorWayland->cursorHiDPI)
658         {
659             wlCursor = cursorWayland->cursorHiDPI;
660             scale = 2;
661         }
662
663         image = wlCursor->images[cursorWayland->currentImage];
664         buffer = wl_cursor_image_get_buffer(image);
665         if (!buffer)
666             return;
667
668         timer.it_value.tv_sec = image->delay / 1000;
669         timer.it_value.tv_nsec = (image->delay % 1000) * 1000000;
670         timerfd_settime(_glfw.wl.cursorTimerfd, 0, &timer, NULL);
671
672         cursorWayland->width = image->width;
673         cursorWayland->height = image->height;
674         cursorWayland->xhot = image->hotspot_x;
675         cursorWayland->yhot = image->hotspot_y;
676     }
677
678     wl_pointer_set_cursor(_glfw.wl.pointer, _glfw.wl.serial,
679                           surface,
680                           cursorWayland->xhot / scale,
681                           cursorWayland->yhot / scale);
682     wl_surface_set_buffer_scale(surface, scale);
683     wl_surface_attach(surface, buffer, 0, 0);
684     wl_surface_damage(surface, 0, 0,
685                       cursorWayland->width, cursorWayland->height);
686     wl_surface_commit(surface);
687 }
688
689 static void incrementCursorImage(_GLFWwindow* window)
690 {
691     _GLFWcursor* cursor;
692
693     if (!window || window->wl.decorations.focus != mainWindow)
694         return;
695
696     cursor = window->wl.currentCursor;
697     if (cursor && cursor->wl.cursor)
698     {
699         cursor->wl.currentImage += 1;
700         cursor->wl.currentImage %= cursor->wl.cursor->image_count;
701         setCursorImage(window, &cursor->wl);
702     }
703 }
704
705 static void handleEvents(int timeout)
706 {
707     struct wl_display* display = _glfw.wl.display;
708     struct pollfd fds[] = {
709         { wl_display_get_fd(display), POLLIN },
710         { _glfw.wl.timerfd, POLLIN },
711         { _glfw.wl.cursorTimerfd, POLLIN },
712     };
713     ssize_t read_ret;
714     uint64_t repeats, i;
715
716     while (wl_display_prepare_read(display) != 0)
717         wl_display_dispatch_pending(display);
718
719     // If an error different from EAGAIN happens, we have likely been
720     // disconnected from the Wayland session, try to handle that the best we
721     // can.
722     if (wl_display_flush(display) < 0 && errno != EAGAIN)
723     {
724         _GLFWwindow* window = _glfw.windowListHead;
725         while (window)
726         {
727             _glfwInputWindowCloseRequest(window);
728             window = window->next;
729         }
730         wl_display_cancel_read(display);
731         return;
732     }
733
734     if (poll(fds, 3, timeout) > 0)
735     {
736         if (fds[0].revents & POLLIN)
737         {
738             wl_display_read_events(display);
739             wl_display_dispatch_pending(display);
740         }
741         else
742         {
743             wl_display_cancel_read(display);
744         }
745
746         if (fds[1].revents & POLLIN)
747         {
748             read_ret = read(_glfw.wl.timerfd, &repeats, sizeof(repeats));
749             if (read_ret != 8)
750                 return;
751
752             if (_glfw.wl.keyboardFocus)
753             {
754                 for (i = 0; i < repeats; ++i)
755                 {
756                     _glfwInputKey(_glfw.wl.keyboardFocus,
757                                   _glfw.wl.keyboardLastKey,
758                                   _glfw.wl.keyboardLastScancode,
759                                   GLFW_REPEAT,
760                                   _glfw.wl.xkb.modifiers);
761                 }
762             }
763         }
764
765         if (fds[2].revents & POLLIN)
766         {
767             read_ret = read(_glfw.wl.cursorTimerfd, &repeats, sizeof(repeats));
768             if (read_ret != 8)
769                 return;
770
771             incrementCursorImage(_glfw.wl.pointerFocus);
772         }
773     }
774     else
775     {
776         wl_display_cancel_read(display);
777     }
778 }
779
780 //////////////////////////////////////////////////////////////////////////
781 //////                       GLFW platform API                      //////
782 //////////////////////////////////////////////////////////////////////////
783
784 int _glfwPlatformCreateWindow(_GLFWwindow* window,
785                               const _GLFWwndconfig* wndconfig,
786                               const _GLFWctxconfig* ctxconfig,
787                               const _GLFWfbconfig* fbconfig)
788 {
789     window->wl.transparent = fbconfig->transparent;
790
791     if (!createSurface(window, wndconfig))
792         return GLFW_FALSE;
793
794     if (ctxconfig->client != GLFW_NO_API)
795     {
796         if (ctxconfig->source == GLFW_EGL_CONTEXT_API ||
797             ctxconfig->source == GLFW_NATIVE_CONTEXT_API)
798         {
799             if (!_glfwInitEGL())
800                 return GLFW_FALSE;
801             if (!_glfwCreateContextEGL(window, ctxconfig, fbconfig))
802                 return GLFW_FALSE;
803         }
804         else if (ctxconfig->source == GLFW_OSMESA_CONTEXT_API)
805         {
806             if (!_glfwInitOSMesa())
807                 return GLFW_FALSE;
808             if (!_glfwCreateContextOSMesa(window, ctxconfig, fbconfig))
809                 return GLFW_FALSE;
810         }
811     }
812
813     if (wndconfig->title)
814         window->wl.title = _glfw_strdup(wndconfig->title);
815
816     if (wndconfig->visible)
817     {
818         if (!createXdgSurface(window))
819             return GLFW_FALSE;
820
821         window->wl.visible = GLFW_TRUE;
822     }
823     else
824     {
825         window->wl.xdg.surface = NULL;
826         window->wl.xdg.toplevel = NULL;
827         window->wl.visible = GLFW_FALSE;
828     }
829
830     window->wl.currentCursor = NULL;
831
832     window->wl.monitors = calloc(1, sizeof(_GLFWmonitor*));
833     window->wl.monitorsCount = 0;
834     window->wl.monitorsSize = 1;
835
836     return GLFW_TRUE;
837 }
838
839 void _glfwPlatformDestroyWindow(_GLFWwindow* window)
840 {
841     if (window == _glfw.wl.pointerFocus)
842     {
843         _glfw.wl.pointerFocus = NULL;
844         _glfwInputCursorEnter(window, GLFW_FALSE);
845     }
846     if (window == _glfw.wl.keyboardFocus)
847     {
848         _glfw.wl.keyboardFocus = NULL;
849         _glfwInputWindowFocus(window, GLFW_FALSE);
850     }
851
852     if (window->wl.idleInhibitor)
853         zwp_idle_inhibitor_v1_destroy(window->wl.idleInhibitor);
854
855     if (window->context.destroy)
856         window->context.destroy(window);
857
858     destroyDecorations(window);
859     if (window->wl.xdg.decoration)
860         zxdg_toplevel_decoration_v1_destroy(window->wl.xdg.decoration);
861
862     if (window->wl.decorations.buffer)
863         wl_buffer_destroy(window->wl.decorations.buffer);
864
865     if (window->wl.native)
866         wl_egl_window_destroy(window->wl.native);
867
868     if (window->wl.xdg.toplevel)
869         xdg_toplevel_destroy(window->wl.xdg.toplevel);
870
871     if (window->wl.xdg.surface)
872         xdg_surface_destroy(window->wl.xdg.surface);
873
874     if (window->wl.surface)
875         wl_surface_destroy(window->wl.surface);
876
877     free(window->wl.title);
878     free(window->wl.monitors);
879 }
880
881 void _glfwPlatformSetWindowTitle(_GLFWwindow* window, const char* title)
882 {
883     if (window->wl.title)
884         free(window->wl.title);
885     window->wl.title = _glfw_strdup(title);
886     if (window->wl.xdg.toplevel)
887         xdg_toplevel_set_title(window->wl.xdg.toplevel, title);
888 }
889
890 void _glfwPlatformSetWindowIcon(_GLFWwindow* window,
891                                 int count, const GLFWimage* images)
892 {
893     _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
894                     "Wayland: The platform does not support setting the window icon");
895 }
896
897 void _glfwPlatformGetWindowPos(_GLFWwindow* window, int* xpos, int* ypos)
898 {
899     // A Wayland client is not aware of its position, so just warn and leave it
900     // as (0, 0)
901
902     _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
903                     "Wayland: The platform does not provide the window position");
904 }
905
906 void _glfwPlatformSetWindowPos(_GLFWwindow* window, int xpos, int ypos)
907 {
908     // A Wayland client can not set its position, so just warn
909
910     _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
911                     "Wayland: The platform does not support setting the window position");
912 }
913
914 void _glfwPlatformGetWindowSize(_GLFWwindow* window, int* width, int* height)
915 {
916     if (width)
917         *width = window->wl.width;
918     if (height)
919         *height = window->wl.height;
920 }
921
922 void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
923 {
924     window->wl.width = width;
925     window->wl.height = height;
926     resizeWindow(window);
927 }
928
929 void _glfwPlatformSetWindowSizeLimits(_GLFWwindow* window,
930                                       int minwidth, int minheight,
931                                       int maxwidth, int maxheight)
932 {
933     if (window->wl.xdg.toplevel)
934     {
935         if (minwidth == GLFW_DONT_CARE || minheight == GLFW_DONT_CARE)
936             minwidth = minheight = 0;
937         if (maxwidth == GLFW_DONT_CARE || maxheight == GLFW_DONT_CARE)
938             maxwidth = maxheight = 0;
939         xdg_toplevel_set_min_size(window->wl.xdg.toplevel, minwidth, minheight);
940         xdg_toplevel_set_max_size(window->wl.xdg.toplevel, maxwidth, maxheight);
941         wl_surface_commit(window->wl.surface);
942     }
943 }
944
945 void _glfwPlatformSetWindowAspectRatio(_GLFWwindow* window,
946                                        int numer, int denom)
947 {
948     // TODO: find out how to trigger a resize.
949     // The actual limits are checked in the xdg_toplevel::configure handler.
950     _glfwInputError(GLFW_FEATURE_UNIMPLEMENTED,
951                     "Wayland: Window aspect ratio not yet implemented");
952 }
953
954 void _glfwPlatformGetFramebufferSize(_GLFWwindow* window,
955                                      int* width, int* height)
956 {
957     _glfwPlatformGetWindowSize(window, width, height);
958     if (width)
959         *width *= window->wl.scale;
960     if (height)
961         *height *= window->wl.scale;
962 }
963
964 void _glfwPlatformGetWindowFrameSize(_GLFWwindow* window,
965                                      int* left, int* top,
966                                      int* right, int* bottom)
967 {
968     if (window->decorated && !window->monitor && !window->wl.decorations.serverSide)
969     {
970         if (top)
971             *top = _GLFW_DECORATION_TOP;
972         if (left)
973             *left = _GLFW_DECORATION_WIDTH;
974         if (right)
975             *right = _GLFW_DECORATION_WIDTH;
976         if (bottom)
977             *bottom = _GLFW_DECORATION_WIDTH;
978     }
979 }
980
981 void _glfwPlatformGetWindowContentScale(_GLFWwindow* window,
982                                         float* xscale, float* yscale)
983 {
984     if (xscale)
985         *xscale = (float) window->wl.scale;
986     if (yscale)
987         *yscale = (float) window->wl.scale;
988 }
989
990 void _glfwPlatformIconifyWindow(_GLFWwindow* window)
991 {
992     if (window->wl.xdg.toplevel)
993         xdg_toplevel_set_minimized(window->wl.xdg.toplevel);
994 }
995
996 void _glfwPlatformRestoreWindow(_GLFWwindow* window)
997 {
998     if (window->wl.xdg.toplevel)
999     {
1000         if (window->monitor)
1001             xdg_toplevel_unset_fullscreen(window->wl.xdg.toplevel);
1002         if (window->wl.maximized)
1003             xdg_toplevel_unset_maximized(window->wl.xdg.toplevel);
1004         // There is no way to unset minimized, or even to know if we are
1005         // minimized, so there is nothing to do in this case.
1006     }
1007     _glfwInputWindowMonitor(window, NULL);
1008     window->wl.maximized = GLFW_FALSE;
1009 }
1010
1011 void _glfwPlatformMaximizeWindow(_GLFWwindow* window)
1012 {
1013     if (window->wl.xdg.toplevel)
1014     {
1015         xdg_toplevel_set_maximized(window->wl.xdg.toplevel);
1016     }
1017     window->wl.maximized = GLFW_TRUE;
1018 }
1019
1020 void _glfwPlatformShowWindow(_GLFWwindow* window)
1021 {
1022     if (!window->wl.visible)
1023     {
1024         createXdgSurface(window);
1025         window->wl.visible = GLFW_TRUE;
1026     }
1027 }
1028
1029 void _glfwPlatformHideWindow(_GLFWwindow* window)
1030 {
1031     if (window->wl.xdg.toplevel)
1032     {
1033         xdg_toplevel_destroy(window->wl.xdg.toplevel);
1034         xdg_surface_destroy(window->wl.xdg.surface);
1035         window->wl.xdg.toplevel = NULL;
1036         window->wl.xdg.surface = NULL;
1037     }
1038     window->wl.visible = GLFW_FALSE;
1039 }
1040
1041 void _glfwPlatformRequestWindowAttention(_GLFWwindow* window)
1042 {
1043     // TODO
1044     _glfwInputError(GLFW_FEATURE_UNIMPLEMENTED,
1045                     "Wayland: Window attention request not implemented yet");
1046 }
1047
1048 void _glfwPlatformFocusWindow(_GLFWwindow* window)
1049 {
1050     _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
1051                     "Wayland: The platform does not support setting the input focus");
1052 }
1053
1054 void _glfwPlatformSetWindowMonitor(_GLFWwindow* window,
1055                                    _GLFWmonitor* monitor,
1056                                    int xpos, int ypos,
1057                                    int width, int height,
1058                                    int refreshRate)
1059 {
1060     if (monitor)
1061     {
1062         setFullscreen(window, monitor, refreshRate);
1063     }
1064     else
1065     {
1066         if (window->wl.xdg.toplevel)
1067             xdg_toplevel_unset_fullscreen(window->wl.xdg.toplevel);
1068         setIdleInhibitor(window, GLFW_FALSE);
1069         if (!_glfw.wl.decorationManager)
1070             createDecorations(window);
1071     }
1072     _glfwInputWindowMonitor(window, monitor);
1073 }
1074
1075 int _glfwPlatformWindowFocused(_GLFWwindow* window)
1076 {
1077     return _glfw.wl.keyboardFocus == window;
1078 }
1079
1080 int _glfwPlatformWindowIconified(_GLFWwindow* window)
1081 {
1082     // xdg-shell doesn’t give any way to request whether a surface is
1083     // iconified.
1084     return GLFW_FALSE;
1085 }
1086
1087 int _glfwPlatformWindowVisible(_GLFWwindow* window)
1088 {
1089     return window->wl.visible;
1090 }
1091
1092 int _glfwPlatformWindowMaximized(_GLFWwindow* window)
1093 {
1094     return window->wl.maximized;
1095 }
1096
1097 int _glfwPlatformWindowHovered(_GLFWwindow* window)
1098 {
1099     return window->wl.hovered;
1100 }
1101
1102 int _glfwPlatformFramebufferTransparent(_GLFWwindow* window)
1103 {
1104     return window->wl.transparent;
1105 }
1106
1107 void _glfwPlatformSetWindowResizable(_GLFWwindow* window, GLFWbool enabled)
1108 {
1109     // TODO
1110     _glfwInputError(GLFW_FEATURE_UNIMPLEMENTED,
1111                     "Wayland: Window attribute setting not implemented yet");
1112 }
1113
1114 void _glfwPlatformSetWindowDecorated(_GLFWwindow* window, GLFWbool enabled)
1115 {
1116     if (!window->monitor)
1117     {
1118         if (enabled)
1119             createDecorations(window);
1120         else
1121             destroyDecorations(window);
1122     }
1123 }
1124
1125 void _glfwPlatformSetWindowFloating(_GLFWwindow* window, GLFWbool enabled)
1126 {
1127     // TODO
1128     _glfwInputError(GLFW_FEATURE_UNIMPLEMENTED,
1129                     "Wayland: Window attribute setting not implemented yet");
1130 }
1131
1132 void _glfwPlatformSetWindowMousePassthrough(_GLFWwindow* window, GLFWbool enabled)
1133 {
1134     if (enabled)
1135     {
1136         struct wl_region* region = wl_compositor_create_region(_glfw.wl.compositor);
1137         wl_surface_set_input_region(window->wl.surface, region);
1138         wl_region_destroy(region);
1139     }
1140     else
1141         wl_surface_set_input_region(window->wl.surface, 0);
1142     wl_surface_commit(window->wl.surface);
1143 }
1144
1145 float _glfwPlatformGetWindowOpacity(_GLFWwindow* window)
1146 {
1147     return 1.f;
1148 }
1149
1150 void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity)
1151 {
1152     _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
1153                     "Wayland: The platform does not support setting the window opacity");
1154 }
1155
1156 void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window, GLFWbool enabled)
1157 {
1158     // This is handled in relativePointerHandleRelativeMotion
1159 }
1160
1161 GLFWbool _glfwPlatformRawMouseMotionSupported(void)
1162 {
1163     return GLFW_TRUE;
1164 }
1165
1166 void _glfwPlatformPollEvents(void)
1167 {
1168     handleEvents(0);
1169 }
1170
1171 void _glfwPlatformWaitEvents(void)
1172 {
1173     handleEvents(-1);
1174 }
1175
1176 void _glfwPlatformWaitEventsTimeout(double timeout)
1177 {
1178     handleEvents((int) (timeout * 1e3));
1179 }
1180
1181 void _glfwPlatformPostEmptyEvent(void)
1182 {
1183     wl_display_sync(_glfw.wl.display);
1184 }
1185
1186 void _glfwPlatformGetCursorPos(_GLFWwindow* window, double* xpos, double* ypos)
1187 {
1188     if (xpos)
1189         *xpos = window->wl.cursorPosX;
1190     if (ypos)
1191         *ypos = window->wl.cursorPosY;
1192 }
1193
1194 static GLFWbool isPointerLocked(_GLFWwindow* window);
1195
1196 void _glfwPlatformSetCursorPos(_GLFWwindow* window, double x, double y)
1197 {
1198     if (isPointerLocked(window))
1199     {
1200         zwp_locked_pointer_v1_set_cursor_position_hint(
1201             window->wl.pointerLock.lockedPointer,
1202             wl_fixed_from_double(x), wl_fixed_from_double(y));
1203         wl_surface_commit(window->wl.surface);
1204     }
1205 }
1206
1207 void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode)
1208 {
1209     _glfwPlatformSetCursor(window, window->wl.currentCursor);
1210 }
1211
1212 const char* _glfwPlatformGetScancodeName(int scancode)
1213 {
1214     // TODO
1215     _glfwInputError(GLFW_FEATURE_UNIMPLEMENTED,
1216                     "Wayland: Key names not yet implemented");
1217     return NULL;
1218 }
1219
1220 int _glfwPlatformGetKeyScancode(int key)
1221 {
1222     return _glfw.wl.scancodes[key];
1223 }
1224
1225 int _glfwPlatformCreateCursor(_GLFWcursor* cursor,
1226                               const GLFWimage* image,
1227                               int xhot, int yhot)
1228 {
1229     cursor->wl.buffer = createShmBuffer(image);
1230     if (!cursor->wl.buffer)
1231         return GLFW_FALSE;
1232
1233     cursor->wl.width = image->width;
1234     cursor->wl.height = image->height;
1235     cursor->wl.xhot = xhot;
1236     cursor->wl.yhot = yhot;
1237     return GLFW_TRUE;
1238 }
1239
1240 int _glfwPlatformCreateStandardCursor(_GLFWcursor* cursor, int shape)
1241 {
1242     const char* name = NULL;
1243
1244     // Try the XDG names first
1245     if (shape == GLFW_ARROW_CURSOR)
1246         name = "default";
1247     else if (shape == GLFW_IBEAM_CURSOR)
1248         name = "text";
1249     else if (shape == GLFW_CROSSHAIR_CURSOR)
1250         name = "crosshair";
1251     else if (shape == GLFW_POINTING_HAND_CURSOR)
1252         name = "pointer";
1253     else if (shape == GLFW_RESIZE_EW_CURSOR)
1254         name = "ew-resize";
1255     else if (shape == GLFW_RESIZE_NS_CURSOR)
1256         name = "ns-resize";
1257     else if (shape == GLFW_RESIZE_NWSE_CURSOR)
1258         name = "nwse-resize";
1259     else if (shape == GLFW_RESIZE_NESW_CURSOR)
1260         name = "nesw-resize";
1261     else if (shape == GLFW_RESIZE_ALL_CURSOR)
1262         name = "all-scroll";
1263     else if (shape == GLFW_NOT_ALLOWED_CURSOR)
1264         name = "not-allowed";
1265
1266     cursor->wl.cursor = wl_cursor_theme_get_cursor(_glfw.wl.cursorTheme, name);
1267
1268     if (_glfw.wl.cursorThemeHiDPI)
1269     {
1270         cursor->wl.cursorHiDPI =
1271             wl_cursor_theme_get_cursor(_glfw.wl.cursorThemeHiDPI, name);
1272     }
1273
1274     if (!cursor->wl.cursor)
1275     {
1276         // Fall back to the core X11 names
1277         if (shape == GLFW_ARROW_CURSOR)
1278             name = "left_ptr";
1279         else if (shape == GLFW_IBEAM_CURSOR)
1280             name = "xterm";
1281         else if (shape == GLFW_CROSSHAIR_CURSOR)
1282             name = "crosshair";
1283         else if (shape == GLFW_POINTING_HAND_CURSOR)
1284             name = "hand2";
1285         else if (shape == GLFW_RESIZE_EW_CURSOR)
1286             name = "sb_h_double_arrow";
1287         else if (shape == GLFW_RESIZE_NS_CURSOR)
1288             name = "sb_v_double_arrow";
1289         else if (shape == GLFW_RESIZE_ALL_CURSOR)
1290             name = "fleur";
1291         else
1292         {
1293             _glfwInputError(GLFW_CURSOR_UNAVAILABLE,
1294                             "Wayland: Standard cursor shape unavailable");
1295             return GLFW_FALSE;
1296         }
1297
1298         cursor->wl.cursor = wl_cursor_theme_get_cursor(_glfw.wl.cursorTheme, name);
1299         if (!cursor->wl.cursor)
1300         {
1301             _glfwInputError(GLFW_PLATFORM_ERROR,
1302                             "Wayland: Failed to create standard cursor \"%s\"",
1303                             name);
1304             return GLFW_FALSE;
1305         }
1306
1307         if (_glfw.wl.cursorThemeHiDPI)
1308         {
1309             if (!cursor->wl.cursorHiDPI)
1310             {
1311                 cursor->wl.cursorHiDPI =
1312                     wl_cursor_theme_get_cursor(_glfw.wl.cursorThemeHiDPI, name);
1313             }
1314         }
1315     }
1316
1317     return GLFW_TRUE;
1318 }
1319
1320 void _glfwPlatformDestroyCursor(_GLFWcursor* cursor)
1321 {
1322     // If it's a standard cursor we don't need to do anything here
1323     if (cursor->wl.cursor)
1324         return;
1325
1326     if (cursor->wl.buffer)
1327         wl_buffer_destroy(cursor->wl.buffer);
1328 }
1329
1330 static void relativePointerHandleRelativeMotion(void* data,
1331                                                 struct zwp_relative_pointer_v1* pointer,
1332                                                 uint32_t timeHi,
1333                                                 uint32_t timeLo,
1334                                                 wl_fixed_t dx,
1335                                                 wl_fixed_t dy,
1336                                                 wl_fixed_t dxUnaccel,
1337                                                 wl_fixed_t dyUnaccel)
1338 {
1339     _GLFWwindow* window = data;
1340     double xpos = window->virtualCursorPosX;
1341     double ypos = window->virtualCursorPosY;
1342
1343     if (window->cursorMode != GLFW_CURSOR_DISABLED)
1344         return;
1345
1346     if (window->rawMouseMotion)
1347     {
1348         xpos += wl_fixed_to_double(dxUnaccel);
1349         ypos += wl_fixed_to_double(dyUnaccel);
1350     }
1351     else
1352     {
1353         xpos += wl_fixed_to_double(dx);
1354         ypos += wl_fixed_to_double(dy);
1355     }
1356
1357     _glfwInputCursorPos(window, xpos, ypos);
1358 }
1359
1360 static const struct zwp_relative_pointer_v1_listener relativePointerListener = {
1361     relativePointerHandleRelativeMotion
1362 };
1363
1364 static void lockedPointerHandleLocked(void* data,
1365                                       struct zwp_locked_pointer_v1* lockedPointer)
1366 {
1367 }
1368
1369 static void unlockPointer(_GLFWwindow* window)
1370 {
1371     struct zwp_relative_pointer_v1* relativePointer =
1372         window->wl.pointerLock.relativePointer;
1373     struct zwp_locked_pointer_v1* lockedPointer =
1374         window->wl.pointerLock.lockedPointer;
1375
1376     zwp_relative_pointer_v1_destroy(relativePointer);
1377     zwp_locked_pointer_v1_destroy(lockedPointer);
1378
1379     window->wl.pointerLock.relativePointer = NULL;
1380     window->wl.pointerLock.lockedPointer = NULL;
1381 }
1382
1383 static void lockPointer(_GLFWwindow* window);
1384
1385 static void lockedPointerHandleUnlocked(void* data,
1386                                         struct zwp_locked_pointer_v1* lockedPointer)
1387 {
1388 }
1389
1390 static const struct zwp_locked_pointer_v1_listener lockedPointerListener = {
1391     lockedPointerHandleLocked,
1392     lockedPointerHandleUnlocked
1393 };
1394
1395 static void lockPointer(_GLFWwindow* window)
1396 {
1397     struct zwp_relative_pointer_v1* relativePointer;
1398     struct zwp_locked_pointer_v1* lockedPointer;
1399
1400     if (!_glfw.wl.relativePointerManager)
1401     {
1402         _glfwInputError(GLFW_PLATFORM_ERROR,
1403                         "Wayland: no relative pointer manager");
1404         return;
1405     }
1406
1407     relativePointer =
1408         zwp_relative_pointer_manager_v1_get_relative_pointer(
1409             _glfw.wl.relativePointerManager,
1410             _glfw.wl.pointer);
1411     zwp_relative_pointer_v1_add_listener(relativePointer,
1412                                          &relativePointerListener,
1413                                          window);
1414
1415     lockedPointer =
1416         zwp_pointer_constraints_v1_lock_pointer(
1417             _glfw.wl.pointerConstraints,
1418             window->wl.surface,
1419             _glfw.wl.pointer,
1420             NULL,
1421             ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);
1422     zwp_locked_pointer_v1_add_listener(lockedPointer,
1423                                        &lockedPointerListener,
1424                                        window);
1425
1426     window->wl.pointerLock.relativePointer = relativePointer;
1427     window->wl.pointerLock.lockedPointer = lockedPointer;
1428
1429     wl_pointer_set_cursor(_glfw.wl.pointer, _glfw.wl.serial,
1430                           NULL, 0, 0);
1431 }
1432
1433 static GLFWbool isPointerLocked(_GLFWwindow* window)
1434 {
1435     return window->wl.pointerLock.lockedPointer != NULL;
1436 }
1437
1438 void _glfwPlatformSetCursor(_GLFWwindow* window, _GLFWcursor* cursor)
1439 {
1440     struct wl_cursor* defaultCursor;
1441     struct wl_cursor* defaultCursorHiDPI = NULL;
1442
1443     if (!_glfw.wl.pointer)
1444         return;
1445
1446     window->wl.currentCursor = cursor;
1447
1448     // If we're not in the correct window just save the cursor
1449     // the next time the pointer enters the window the cursor will change
1450     if (window != _glfw.wl.pointerFocus || window->wl.decorations.focus != mainWindow)
1451         return;
1452
1453     // Unlock possible pointer lock if no longer disabled.
1454     if (window->cursorMode != GLFW_CURSOR_DISABLED && isPointerLocked(window))
1455         unlockPointer(window);
1456
1457     if (window->cursorMode == GLFW_CURSOR_NORMAL)
1458     {
1459         if (cursor)
1460             setCursorImage(window, &cursor->wl);
1461         else
1462         {
1463             defaultCursor = wl_cursor_theme_get_cursor(_glfw.wl.cursorTheme,
1464                                                        "left_ptr");
1465             if (!defaultCursor)
1466             {
1467                 _glfwInputError(GLFW_PLATFORM_ERROR,
1468                                 "Wayland: Standard cursor not found");
1469                 return;
1470             }
1471             if (_glfw.wl.cursorThemeHiDPI)
1472                 defaultCursorHiDPI =
1473                     wl_cursor_theme_get_cursor(_glfw.wl.cursorThemeHiDPI,
1474                                                "left_ptr");
1475             _GLFWcursorWayland cursorWayland = {
1476                 defaultCursor,
1477                 defaultCursorHiDPI,
1478                 NULL,
1479                 0, 0,
1480                 0, 0,
1481                 0
1482             };
1483             setCursorImage(window, &cursorWayland);
1484         }
1485     }
1486     else if (window->cursorMode == GLFW_CURSOR_DISABLED)
1487     {
1488         if (!isPointerLocked(window))
1489             lockPointer(window);
1490     }
1491     else if (window->cursorMode == GLFW_CURSOR_HIDDEN)
1492     {
1493         wl_pointer_set_cursor(_glfw.wl.pointer, _glfw.wl.serial, NULL, 0, 0);
1494     }
1495 }
1496
1497 static void dataSourceHandleTarget(void* data,
1498                                    struct wl_data_source* dataSource,
1499                                    const char* mimeType)
1500 {
1501     if (_glfw.wl.dataSource != dataSource)
1502     {
1503         _glfwInputError(GLFW_PLATFORM_ERROR,
1504                         "Wayland: Unknown clipboard data source");
1505         return;
1506     }
1507 }
1508
1509 static void dataSourceHandleSend(void* data,
1510                                  struct wl_data_source* dataSource,
1511                                  const char* mimeType,
1512                                  int fd)
1513 {
1514     const char* string = _glfw.wl.clipboardSendString;
1515     size_t len = _glfw.wl.clipboardSendSize;
1516     int ret;
1517
1518     if (_glfw.wl.dataSource != dataSource)
1519     {
1520         _glfwInputError(GLFW_PLATFORM_ERROR,
1521                         "Wayland: Unknown clipboard data source");
1522         return;
1523     }
1524
1525     if (!string)
1526     {
1527         _glfwInputError(GLFW_PLATFORM_ERROR,
1528                         "Wayland: Copy requested from an invalid string");
1529         return;
1530     }
1531
1532     if (strcmp(mimeType, "text/plain;charset=utf-8") != 0)
1533     {
1534         _glfwInputError(GLFW_PLATFORM_ERROR,
1535                         "Wayland: Wrong MIME type asked from clipboard");
1536         close(fd);
1537         return;
1538     }
1539
1540     while (len > 0)
1541     {
1542         ret = write(fd, string, len);
1543         if (ret == -1 && errno == EINTR)
1544             continue;
1545         if (ret == -1)
1546         {
1547             // TODO: also report errno maybe.
1548             _glfwInputError(GLFW_PLATFORM_ERROR,
1549                             "Wayland: Error while writing the clipboard");
1550             close(fd);
1551             return;
1552         }
1553         len -= ret;
1554     }
1555     close(fd);
1556 }
1557
1558 static void dataSourceHandleCancelled(void* data,
1559                                       struct wl_data_source* dataSource)
1560 {
1561     wl_data_source_destroy(dataSource);
1562
1563     if (_glfw.wl.dataSource != dataSource)
1564     {
1565         _glfwInputError(GLFW_PLATFORM_ERROR,
1566                         "Wayland: Unknown clipboard data source");
1567         return;
1568     }
1569
1570     _glfw.wl.dataSource = NULL;
1571 }
1572
1573 static const struct wl_data_source_listener dataSourceListener = {
1574     dataSourceHandleTarget,
1575     dataSourceHandleSend,
1576     dataSourceHandleCancelled,
1577 };
1578
1579 void _glfwPlatformSetClipboardString(const char* string)
1580 {
1581     if (_glfw.wl.dataSource)
1582     {
1583         wl_data_source_destroy(_glfw.wl.dataSource);
1584         _glfw.wl.dataSource = NULL;
1585     }
1586
1587     if (_glfw.wl.clipboardSendString)
1588     {
1589         free(_glfw.wl.clipboardSendString);
1590         _glfw.wl.clipboardSendString = NULL;
1591     }
1592
1593     _glfw.wl.clipboardSendString = strdup(string);
1594     if (!_glfw.wl.clipboardSendString)
1595     {
1596         _glfwInputError(GLFW_PLATFORM_ERROR,
1597                         "Wayland: Impossible to allocate clipboard string");
1598         return;
1599     }
1600     _glfw.wl.clipboardSendSize = strlen(string);
1601     _glfw.wl.dataSource =
1602         wl_data_device_manager_create_data_source(_glfw.wl.dataDeviceManager);
1603     if (!_glfw.wl.dataSource)
1604     {
1605         _glfwInputError(GLFW_PLATFORM_ERROR,
1606                         "Wayland: Impossible to create clipboard source");
1607         free(_glfw.wl.clipboardSendString);
1608         return;
1609     }
1610     wl_data_source_add_listener(_glfw.wl.dataSource,
1611                                 &dataSourceListener,
1612                                 NULL);
1613     wl_data_source_offer(_glfw.wl.dataSource, "text/plain;charset=utf-8");
1614     wl_data_device_set_selection(_glfw.wl.dataDevice,
1615                                  _glfw.wl.dataSource,
1616                                  _glfw.wl.serial);
1617 }
1618
1619 static GLFWbool growClipboardString(void)
1620 {
1621     char* clipboard = _glfw.wl.clipboardString;
1622
1623     clipboard = realloc(clipboard, _glfw.wl.clipboardSize * 2);
1624     if (!clipboard)
1625     {
1626         _glfwInputError(GLFW_PLATFORM_ERROR,
1627                         "Wayland: Impossible to grow clipboard string");
1628         return GLFW_FALSE;
1629     }
1630     _glfw.wl.clipboardString = clipboard;
1631     _glfw.wl.clipboardSize = _glfw.wl.clipboardSize * 2;
1632     return GLFW_TRUE;
1633 }
1634
1635 const char* _glfwPlatformGetClipboardString(void)
1636 {
1637     int fds[2];
1638     int ret;
1639     size_t len = 0;
1640
1641     if (!_glfw.wl.dataOffer)
1642     {
1643         _glfwInputError(GLFW_FORMAT_UNAVAILABLE,
1644                         "No clipboard data has been sent yet");
1645         return NULL;
1646     }
1647
1648     ret = pipe2(fds, O_CLOEXEC);
1649     if (ret < 0)
1650     {
1651         // TODO: also report errno maybe?
1652         _glfwInputError(GLFW_PLATFORM_ERROR,
1653                         "Wayland: Impossible to create clipboard pipe fds");
1654         return NULL;
1655     }
1656
1657     wl_data_offer_receive(_glfw.wl.dataOffer, "text/plain;charset=utf-8", fds[1]);
1658     close(fds[1]);
1659
1660     // XXX: this is a huge hack, this function shouldn’t be synchronous!
1661     handleEvents(-1);
1662
1663     while (1)
1664     {
1665         // Grow the clipboard if we need to paste something bigger, there is no
1666         // shrink operation yet.
1667         if (len + 4096 > _glfw.wl.clipboardSize)
1668         {
1669             if (!growClipboardString())
1670             {
1671                 close(fds[0]);
1672                 return NULL;
1673             }
1674         }
1675
1676         // Then read from the fd to the clipboard, handling all known errors.
1677         ret = read(fds[0], _glfw.wl.clipboardString + len, 4096);
1678         if (ret == 0)
1679             break;
1680         if (ret == -1 && errno == EINTR)
1681             continue;
1682         if (ret == -1)
1683         {
1684             // TODO: also report errno maybe.
1685             _glfwInputError(GLFW_PLATFORM_ERROR,
1686                             "Wayland: Impossible to read from clipboard fd");
1687             close(fds[0]);
1688             return NULL;
1689         }
1690         len += ret;
1691     }
1692     close(fds[0]);
1693     if (len + 1 > _glfw.wl.clipboardSize)
1694     {
1695         if (!growClipboardString())
1696             return NULL;
1697     }
1698     _glfw.wl.clipboardString[len] = '\0';
1699     return _glfw.wl.clipboardString;
1700 }
1701
1702 EGLenum _glfwPlatformGetEGLPlatform(EGLint** attribs)
1703 {
1704     if (_glfw.egl.EXT_platform_base && _glfw.egl.EXT_platform_wayland)
1705         return EGL_PLATFORM_WAYLAND_EXT;
1706     else
1707         return 0;
1708 }
1709
1710 EGLNativeDisplayType _glfwPlatformGetEGLNativeDisplay(void)
1711 {
1712     return _glfw.wl.display;
1713 }
1714
1715 EGLNativeWindowType _glfwPlatformGetEGLNativeWindow(_GLFWwindow* window)
1716 {
1717     return window->wl.native;
1718 }
1719
1720 void _glfwPlatformGetRequiredInstanceExtensions(char** extensions)
1721 {
1722     if (!_glfw.vk.KHR_surface || !_glfw.vk.KHR_wayland_surface)
1723         return;
1724
1725     extensions[0] = "VK_KHR_surface";
1726     extensions[1] = "VK_KHR_wayland_surface";
1727 }
1728
1729 int _glfwPlatformGetPhysicalDevicePresentationSupport(VkInstance instance,
1730                                                       VkPhysicalDevice device,
1731                                                       uint32_t queuefamily)
1732 {
1733     PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR
1734         vkGetPhysicalDeviceWaylandPresentationSupportKHR =
1735         (PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR)
1736         vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceWaylandPresentationSupportKHR");
1737     if (!vkGetPhysicalDeviceWaylandPresentationSupportKHR)
1738     {
1739         _glfwInputError(GLFW_API_UNAVAILABLE,
1740                         "Wayland: Vulkan instance missing VK_KHR_wayland_surface extension");
1741         return VK_NULL_HANDLE;
1742     }
1743
1744     return vkGetPhysicalDeviceWaylandPresentationSupportKHR(device,
1745                                                             queuefamily,
1746                                                             _glfw.wl.display);
1747 }
1748
1749 VkResult _glfwPlatformCreateWindowSurface(VkInstance instance,
1750                                           _GLFWwindow* window,
1751                                           const VkAllocationCallbacks* allocator,
1752                                           VkSurfaceKHR* surface)
1753 {
1754     VkResult err;
1755     VkWaylandSurfaceCreateInfoKHR sci;
1756     PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR;
1757
1758     vkCreateWaylandSurfaceKHR = (PFN_vkCreateWaylandSurfaceKHR)
1759         vkGetInstanceProcAddr(instance, "vkCreateWaylandSurfaceKHR");
1760     if (!vkCreateWaylandSurfaceKHR)
1761     {
1762         _glfwInputError(GLFW_API_UNAVAILABLE,
1763                         "Wayland: Vulkan instance missing VK_KHR_wayland_surface extension");
1764         return VK_ERROR_EXTENSION_NOT_PRESENT;
1765     }
1766
1767     memset(&sci, 0, sizeof(sci));
1768     sci.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
1769     sci.display = _glfw.wl.display;
1770     sci.surface = window->wl.surface;
1771
1772     err = vkCreateWaylandSurfaceKHR(instance, &sci, allocator, surface);
1773     if (err)
1774     {
1775         _glfwInputError(GLFW_PLATFORM_ERROR,
1776                         "Wayland: Failed to create Vulkan surface: %s",
1777                         _glfwGetVulkanResultString(err));
1778     }
1779
1780     return err;
1781 }
1782
1783
1784 //////////////////////////////////////////////////////////////////////////
1785 //////                        GLFW native API                       //////
1786 //////////////////////////////////////////////////////////////////////////
1787
1788 GLFWAPI struct wl_display* glfwGetWaylandDisplay(void)
1789 {
1790     _GLFW_REQUIRE_INIT_OR_RETURN(NULL);
1791     return _glfw.wl.display;
1792 }
1793
1794 GLFWAPI struct wl_surface* glfwGetWaylandWindow(GLFWwindow* handle)
1795 {
1796     _GLFWwindow* window = (_GLFWwindow*) handle;
1797     _GLFW_REQUIRE_INIT_OR_RETURN(NULL);
1798     return window->wl.surface;
1799 }
1800