DSCF

.co.uk

PC32

A ColorForth compiler and editor for x86-64
git clone https://dscf.co.uk/clone/PC32.git
Log | Files | Refs | README

wl_window.c (86107B)


      1 //========================================================================
      2 // GLFW 3.3 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 <assert.h>
     37 #include <unistd.h>
     38 #include <string.h>
     39 #include <fcntl.h>
     40 #include <sys/mman.h>
     41 #include <sys/timerfd.h>
     42 #include <poll.h>
     43 #include <signal.h>
     44 #include <time.h>
     45 
     46 #define GLFW_BORDER_SIZE    4
     47 #define GLFW_CAPTION_HEIGHT 24
     48 
     49 static int createTmpfileCloexec(char* tmpname)
     50 {
     51     int fd;
     52 
     53     fd = mkostemp(tmpname, O_CLOEXEC);
     54     if (fd >= 0)
     55         unlink(tmpname);
     56 
     57     return fd;
     58 }
     59 
     60 /*
     61  * Create a new, unique, anonymous file of the given size, and
     62  * return the file descriptor for it. The file descriptor is set
     63  * CLOEXEC. The file is immediately suitable for mmap()'ing
     64  * the given size at offset zero.
     65  *
     66  * The file should not have a permanent backing store like a disk,
     67  * but may have if XDG_RUNTIME_DIR is not properly implemented in OS.
     68  *
     69  * The file name is deleted from the file system.
     70  *
     71  * The file is suitable for buffer sharing between processes by
     72  * transmitting the file descriptor over Unix sockets using the
     73  * SCM_RIGHTS methods.
     74  *
     75  * posix_fallocate() is used to guarantee that disk space is available
     76  * for the file at the given size. If disk space is insufficient, errno
     77  * is set to ENOSPC. If posix_fallocate() is not supported, program may
     78  * receive SIGBUS on accessing mmap()'ed file contents instead.
     79  */
     80 static int createAnonymousFile(off_t size)
     81 {
     82     static const char template[] = "/glfw-shared-XXXXXX";
     83     const char* path;
     84     char* name;
     85     int fd;
     86     int ret;
     87 
     88 #ifdef HAVE_MEMFD_CREATE
     89     fd = memfd_create("glfw-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING);
     90     if (fd >= 0)
     91     {
     92         // We can add this seal before calling posix_fallocate(), as the file
     93         // is currently zero-sized anyway.
     94         //
     95         // There is also no need to check for the return value, we couldn’t do
     96         // anything with it anyway.
     97         fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_SEAL);
     98     }
     99     else
    100 #elif defined(SHM_ANON)
    101     fd = shm_open(SHM_ANON, O_RDWR | O_CLOEXEC, 0600);
    102     if (fd < 0)
    103 #endif
    104     {
    105         path = getenv("XDG_RUNTIME_DIR");
    106         if (!path)
    107         {
    108             errno = ENOENT;
    109             return -1;
    110         }
    111 
    112         name = calloc(strlen(path) + sizeof(template), 1);
    113         strcpy(name, path);
    114         strcat(name, template);
    115 
    116         fd = createTmpfileCloexec(name);
    117         free(name);
    118         if (fd < 0)
    119             return -1;
    120     }
    121 
    122 #if defined(SHM_ANON)
    123     // posix_fallocate does not work on SHM descriptors
    124     ret = ftruncate(fd, size);
    125 #else
    126     ret = posix_fallocate(fd, 0, size);
    127 #endif
    128     if (ret != 0)
    129     {
    130         close(fd);
    131         errno = ret;
    132         return -1;
    133     }
    134     return fd;
    135 }
    136 
    137 static struct wl_buffer* createShmBuffer(const GLFWimage* image)
    138 {
    139     struct wl_shm_pool* pool;
    140     struct wl_buffer* buffer;
    141     int stride = image->width * 4;
    142     int length = image->width * image->height * 4;
    143     void* data;
    144     int fd, i;
    145 
    146     fd = createAnonymousFile(length);
    147     if (fd < 0)
    148     {
    149         _glfwInputError(GLFW_PLATFORM_ERROR,
    150                         "Wayland: Failed to create buffer file of size %d: %s",
    151                         length, strerror(errno));
    152         return NULL;
    153     }
    154 
    155     data = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    156     if (data == MAP_FAILED)
    157     {
    158         _glfwInputError(GLFW_PLATFORM_ERROR,
    159                         "Wayland: Failed to map file: %s", strerror(errno));
    160         close(fd);
    161         return NULL;
    162     }
    163 
    164     pool = wl_shm_create_pool(_glfw.wl.shm, fd, length);
    165 
    166     close(fd);
    167     unsigned char* source = (unsigned char*) image->pixels;
    168     unsigned char* target = data;
    169     for (i = 0;  i < image->width * image->height;  i++, source += 4)
    170     {
    171         unsigned int alpha = source[3];
    172 
    173         *target++ = (unsigned char) ((source[2] * alpha) / 255);
    174         *target++ = (unsigned char) ((source[1] * alpha) / 255);
    175         *target++ = (unsigned char) ((source[0] * alpha) / 255);
    176         *target++ = (unsigned char) alpha;
    177     }
    178 
    179     buffer =
    180         wl_shm_pool_create_buffer(pool, 0,
    181                                   image->width,
    182                                   image->height,
    183                                   stride, WL_SHM_FORMAT_ARGB8888);
    184     munmap(data, length);
    185     wl_shm_pool_destroy(pool);
    186 
    187     return buffer;
    188 }
    189 
    190 // Wait for data to arrive on any of the specified file descriptors
    191 //
    192 static GLFWbool waitForData(struct pollfd* fds, nfds_t count, double* timeout)
    193 {
    194     for (;;)
    195     {
    196         if (timeout)
    197         {
    198             const uint64_t base = _glfwPlatformGetTimerValue();
    199 
    200 #if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__CYGWIN__)
    201             const time_t seconds = (time_t) *timeout;
    202             const long nanoseconds = (long) ((*timeout - seconds) * 1e9);
    203             const struct timespec ts = { seconds, nanoseconds };
    204             const int result = ppoll(fds, count, &ts, NULL);
    205 #elif defined(__NetBSD__)
    206             const time_t seconds = (time_t) *timeout;
    207             const long nanoseconds = (long) ((*timeout - seconds) * 1e9);
    208             const struct timespec ts = { seconds, nanoseconds };
    209             const int result = pollts(fds, count, &ts, NULL);
    210 #else
    211             const int milliseconds = (int) (*timeout * 1e3);
    212             const int result = poll(fds, count, milliseconds);
    213 #endif
    214             const int error = errno; // clock_gettime may overwrite our error
    215 
    216             *timeout -= (_glfwPlatformGetTimerValue() - base) /
    217                 (double) _glfwPlatformGetTimerFrequency();
    218 
    219             if (result > 0)
    220                 return GLFW_TRUE;
    221             else if (result == -1 && error != EINTR && error != EAGAIN)
    222                 return GLFW_FALSE;
    223             else if (*timeout <= 0.0)
    224                 return GLFW_FALSE;
    225         }
    226         else
    227         {
    228             const int result = poll(fds, count, -1);
    229             if (result > 0)
    230                 return GLFW_TRUE;
    231             else if (result == -1 && errno != EINTR && errno != EAGAIN)
    232                 return GLFW_FALSE;
    233         }
    234     }
    235 }
    236 
    237 static void createFallbackDecoration(_GLFWdecorationWayland* decoration,
    238                                      struct wl_surface* parent,
    239                                      struct wl_buffer* buffer,
    240                                      int x, int y,
    241                                      int width, int height)
    242 {
    243     decoration->surface = wl_compositor_create_surface(_glfw.wl.compositor);
    244     decoration->subsurface =
    245         wl_subcompositor_get_subsurface(_glfw.wl.subcompositor,
    246                                         decoration->surface, parent);
    247     wl_subsurface_set_position(decoration->subsurface, x, y);
    248     decoration->viewport = wp_viewporter_get_viewport(_glfw.wl.viewporter,
    249                                                       decoration->surface);
    250     wp_viewport_set_destination(decoration->viewport, width, height);
    251     wl_surface_attach(decoration->surface, buffer, 0, 0);
    252 
    253     struct wl_region* region = wl_compositor_create_region(_glfw.wl.compositor);
    254     wl_region_add(region, 0, 0, width, height);
    255     wl_surface_set_opaque_region(decoration->surface, region);
    256     wl_surface_commit(decoration->surface);
    257     wl_region_destroy(region);
    258 }
    259 
    260 static void createFallbackDecorations(_GLFWwindow* window)
    261 {
    262     unsigned char data[] = { 224, 224, 224, 255 };
    263     const GLFWimage image = { 1, 1, data };
    264 
    265     if (!_glfw.wl.viewporter)
    266         return;
    267 
    268     if (!window->wl.decorations.buffer)
    269         window->wl.decorations.buffer = createShmBuffer(&image);
    270     if (!window->wl.decorations.buffer)
    271         return;
    272 
    273     createFallbackDecoration(&window->wl.decorations.top, window->wl.surface,
    274                              window->wl.decorations.buffer,
    275                              0, -GLFW_CAPTION_HEIGHT,
    276                              window->wl.width, GLFW_CAPTION_HEIGHT);
    277     createFallbackDecoration(&window->wl.decorations.left, window->wl.surface,
    278                              window->wl.decorations.buffer,
    279                              -GLFW_BORDER_SIZE, -GLFW_CAPTION_HEIGHT,
    280                              GLFW_BORDER_SIZE, window->wl.height + GLFW_CAPTION_HEIGHT);
    281     createFallbackDecoration(&window->wl.decorations.right, window->wl.surface,
    282                              window->wl.decorations.buffer,
    283                              window->wl.width, -GLFW_CAPTION_HEIGHT,
    284                              GLFW_BORDER_SIZE, window->wl.height + GLFW_CAPTION_HEIGHT);
    285     createFallbackDecoration(&window->wl.decorations.bottom, window->wl.surface,
    286                              window->wl.decorations.buffer,
    287                              -GLFW_BORDER_SIZE, window->wl.height,
    288                              window->wl.width + GLFW_BORDER_SIZE * 2, GLFW_BORDER_SIZE);
    289 }
    290 
    291 static void destroyFallbackDecoration(_GLFWdecorationWayland* decoration)
    292 {
    293     if (decoration->subsurface)
    294         wl_subsurface_destroy(decoration->subsurface);
    295     if (decoration->surface)
    296         wl_surface_destroy(decoration->surface);
    297     if (decoration->viewport)
    298         wp_viewport_destroy(decoration->viewport);
    299     decoration->surface = NULL;
    300     decoration->subsurface = NULL;
    301     decoration->viewport = NULL;
    302 }
    303 
    304 static void destroyFallbackDecorations(_GLFWwindow* window)
    305 {
    306     destroyFallbackDecoration(&window->wl.decorations.top);
    307     destroyFallbackDecoration(&window->wl.decorations.left);
    308     destroyFallbackDecoration(&window->wl.decorations.right);
    309     destroyFallbackDecoration(&window->wl.decorations.bottom);
    310 }
    311 
    312 static void xdgDecorationHandleConfigure(void* userData,
    313                                          struct zxdg_toplevel_decoration_v1* decoration,
    314                                          uint32_t mode)
    315 {
    316     _GLFWwindow* window = userData;
    317 
    318     window->wl.xdg.decorationMode = mode;
    319 
    320     if (mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE)
    321     {
    322         if (window->decorated && !window->monitor)
    323             createFallbackDecorations(window);
    324     }
    325     else
    326         destroyFallbackDecorations(window);
    327 }
    328 
    329 static const struct zxdg_toplevel_decoration_v1_listener xdgDecorationListener =
    330 {
    331     xdgDecorationHandleConfigure,
    332 };
    333 
    334 // Makes the surface considered as XRGB instead of ARGB.
    335 static void setContentAreaOpaque(_GLFWwindow* window)
    336 {
    337     struct wl_region* region;
    338 
    339     region = wl_compositor_create_region(_glfw.wl.compositor);
    340     if (!region)
    341         return;
    342 
    343     wl_region_add(region, 0, 0, window->wl.width, window->wl.height);
    344     wl_surface_set_opaque_region(window->wl.surface, region);
    345     wl_region_destroy(region);
    346 }
    347 
    348 
    349 static void resizeWindow(_GLFWwindow* window)
    350 {
    351     int scale = window->wl.scale;
    352     int scaledWidth = window->wl.width * scale;
    353     int scaledHeight = window->wl.height * scale;
    354 
    355     if (window->wl.egl.window)
    356         wl_egl_window_resize(window->wl.egl.window, scaledWidth, scaledHeight, 0, 0);
    357     if (!window->wl.transparent)
    358         setContentAreaOpaque(window);
    359     _glfwInputFramebufferSize(window, scaledWidth, scaledHeight);
    360 
    361     if (!window->wl.decorations.top.surface)
    362         return;
    363 
    364     wp_viewport_set_destination(window->wl.decorations.top.viewport,
    365                                 window->wl.width, GLFW_CAPTION_HEIGHT);
    366     wl_surface_commit(window->wl.decorations.top.surface);
    367 
    368     wp_viewport_set_destination(window->wl.decorations.left.viewport,
    369                                 GLFW_BORDER_SIZE, window->wl.height + GLFW_CAPTION_HEIGHT);
    370     wl_surface_commit(window->wl.decorations.left.surface);
    371 
    372     wl_subsurface_set_position(window->wl.decorations.right.subsurface,
    373                                window->wl.width, -GLFW_CAPTION_HEIGHT);
    374     wp_viewport_set_destination(window->wl.decorations.right.viewport,
    375                                 GLFW_BORDER_SIZE, window->wl.height + GLFW_CAPTION_HEIGHT);
    376     wl_surface_commit(window->wl.decorations.right.surface);
    377 
    378     wl_subsurface_set_position(window->wl.decorations.bottom.subsurface,
    379                                -GLFW_BORDER_SIZE, window->wl.height);
    380     wp_viewport_set_destination(window->wl.decorations.bottom.viewport,
    381                                 window->wl.width + GLFW_BORDER_SIZE * 2, GLFW_BORDER_SIZE);
    382     wl_surface_commit(window->wl.decorations.bottom.surface);
    383 }
    384 
    385 void _glfwUpdateContentScaleWayland(_GLFWwindow* window)
    386 {
    387     if (_glfw.wl.compositorVersion < WL_SURFACE_SET_BUFFER_SCALE_SINCE_VERSION)
    388         return;
    389 
    390     // Get the scale factor from the highest scale monitor.
    391     int maxScale = 1;
    392 
    393     for (int i = 0; i < window->wl.monitorsCount; i++)
    394         maxScale = _glfw_max(window->wl.monitors[i]->wl.scale, maxScale);
    395 
    396     // Only change the framebuffer size if the scale changed.
    397     if (window->wl.scale != maxScale)
    398     {
    399         window->wl.scale = maxScale;
    400         wl_surface_set_buffer_scale(window->wl.surface, maxScale);
    401         _glfwInputWindowContentScale(window, maxScale, maxScale);
    402         resizeWindow(window);
    403     }
    404 }
    405 
    406 static void surfaceHandleEnter(void* userData,
    407                                struct wl_surface* surface,
    408                                struct wl_output* output)
    409 {
    410     _GLFWwindow* window = userData;
    411     _GLFWmonitor* monitor = wl_output_get_user_data(output);
    412 
    413     if (window->wl.monitorsCount + 1 > window->wl.monitorsSize)
    414     {
    415         ++window->wl.monitorsSize;
    416         window->wl.monitors =
    417             realloc(window->wl.monitors,
    418                     window->wl.monitorsSize * sizeof(_GLFWmonitor*));
    419     }
    420 
    421     window->wl.monitors[window->wl.monitorsCount++] = monitor;
    422 
    423     _glfwUpdateContentScaleWayland(window);
    424 }
    425 
    426 static void surfaceHandleLeave(void* userData,
    427                                struct wl_surface* surface,
    428                                struct wl_output* output)
    429 {
    430     _GLFWwindow* window = userData;
    431     _GLFWmonitor* monitor = wl_output_get_user_data(output);
    432     GLFWbool found;
    433     int i;
    434 
    435     for (i = 0, found = GLFW_FALSE; i < window->wl.monitorsCount - 1; ++i)
    436     {
    437         if (monitor == window->wl.monitors[i])
    438             found = GLFW_TRUE;
    439         if (found)
    440             window->wl.monitors[i] = window->wl.monitors[i + 1];
    441     }
    442     window->wl.monitors[--window->wl.monitorsCount] = NULL;
    443 
    444     _glfwUpdateContentScaleWayland(window);
    445 }
    446 
    447 static const struct wl_surface_listener surfaceListener =
    448 {
    449     surfaceHandleEnter,
    450     surfaceHandleLeave
    451 };
    452 
    453 static void setIdleInhibitor(_GLFWwindow* window, GLFWbool enable)
    454 {
    455     if (enable && !window->wl.idleInhibitor && _glfw.wl.idleInhibitManager)
    456     {
    457         window->wl.idleInhibitor =
    458             zwp_idle_inhibit_manager_v1_create_inhibitor(
    459                 _glfw.wl.idleInhibitManager, window->wl.surface);
    460         if (!window->wl.idleInhibitor)
    461             _glfwInputError(GLFW_PLATFORM_ERROR,
    462                             "Wayland: Failed to create idle inhibitor");
    463     }
    464     else if (!enable && window->wl.idleInhibitor)
    465     {
    466         zwp_idle_inhibitor_v1_destroy(window->wl.idleInhibitor);
    467         window->wl.idleInhibitor = NULL;
    468     }
    469 }
    470 
    471 // Make the specified window and its video mode active on its monitor
    472 //
    473 static void acquireMonitor(_GLFWwindow* window)
    474 {
    475     if (window->wl.xdg.toplevel)
    476     {
    477         xdg_toplevel_set_fullscreen(window->wl.xdg.toplevel,
    478                                     window->monitor->wl.output);
    479     }
    480 
    481     setIdleInhibitor(window, GLFW_TRUE);
    482 
    483     if (window->wl.decorations.top.surface)
    484         destroyFallbackDecorations(window);
    485 }
    486 
    487 // Remove the window and restore the original video mode
    488 //
    489 static void releaseMonitor(_GLFWwindow* window)
    490 {
    491     if (window->wl.xdg.toplevel)
    492         xdg_toplevel_unset_fullscreen(window->wl.xdg.toplevel);
    493 
    494     setIdleInhibitor(window, GLFW_FALSE);
    495 
    496     if (window->wl.xdg.decorationMode != ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE)
    497     {
    498         if (window->decorated)
    499             createFallbackDecorations(window);
    500     }
    501 }
    502 
    503 static void xdgToplevelHandleConfigure(void* userData,
    504                                        struct xdg_toplevel* toplevel,
    505                                        int32_t width,
    506                                        int32_t height,
    507                                        struct wl_array* states)
    508 {
    509     _GLFWwindow* window = userData;
    510     uint32_t* state;
    511 
    512     window->wl.pending.activated  = GLFW_FALSE;
    513     window->wl.pending.maximized  = GLFW_FALSE;
    514     window->wl.pending.fullscreen = GLFW_FALSE;
    515 
    516     wl_array_for_each(state, states)
    517     {
    518         switch (*state)
    519         {
    520             case XDG_TOPLEVEL_STATE_MAXIMIZED:
    521                 window->wl.pending.maximized = GLFW_TRUE;
    522                 break;
    523             case XDG_TOPLEVEL_STATE_FULLSCREEN:
    524                 window->wl.pending.fullscreen = GLFW_TRUE;
    525                 break;
    526             case XDG_TOPLEVEL_STATE_RESIZING:
    527                 break;
    528             case XDG_TOPLEVEL_STATE_ACTIVATED:
    529                 window->wl.pending.activated = GLFW_TRUE;
    530                 break;
    531         }
    532     }
    533 
    534     if (width && height)
    535     {
    536         if (window->wl.decorations.top.surface)
    537         {
    538             window->wl.pending.width  = _glfw_max(0, width - GLFW_BORDER_SIZE * 2);
    539             window->wl.pending.height =
    540                 _glfw_max(0, height - GLFW_BORDER_SIZE - GLFW_CAPTION_HEIGHT);
    541         }
    542         else
    543         {
    544             window->wl.pending.width  = width;
    545             window->wl.pending.height = height;
    546         }
    547     }
    548     else
    549     {
    550         window->wl.pending.width  = window->wl.width;
    551         window->wl.pending.height = window->wl.height;
    552     }
    553 }
    554 
    555 static void xdgToplevelHandleClose(void* userData,
    556                                    struct xdg_toplevel* toplevel)
    557 {
    558     _GLFWwindow* window = userData;
    559     _glfwInputWindowCloseRequest(window);
    560 }
    561 
    562 static const struct xdg_toplevel_listener xdgToplevelListener =
    563 {
    564     xdgToplevelHandleConfigure,
    565     xdgToplevelHandleClose
    566 };
    567 
    568 static void xdgSurfaceHandleConfigure(void* userData,
    569                                       struct xdg_surface* surface,
    570                                       uint32_t serial)
    571 {
    572     _GLFWwindow* window = userData;
    573 
    574     xdg_surface_ack_configure(surface, serial);
    575 
    576     if (window->wl.activated != window->wl.pending.activated)
    577     {
    578         window->wl.activated = window->wl.pending.activated;
    579         if (!window->wl.activated)
    580         {
    581             if (window->monitor && window->autoIconify)
    582                 xdg_toplevel_set_minimized(window->wl.xdg.toplevel);
    583         }
    584     }
    585 
    586     if (window->wl.maximized != window->wl.pending.maximized)
    587     {
    588         window->wl.maximized = window->wl.pending.maximized;
    589         _glfwInputWindowMaximize(window, window->wl.maximized);
    590     }
    591 
    592     window->wl.fullscreen = window->wl.pending.fullscreen;
    593 
    594     int width  = window->wl.pending.width;
    595     int height = window->wl.pending.height;
    596 
    597     if (!window->wl.maximized && !window->wl.fullscreen)
    598     {
    599         if (window->numer != GLFW_DONT_CARE && window->denom != GLFW_DONT_CARE)
    600         {
    601             const float aspectRatio = (float) width / (float) height;
    602             const float targetRatio = (float) window->numer / (float) window->denom;
    603             if (aspectRatio < targetRatio)
    604                 height = width / targetRatio;
    605             else if (aspectRatio > targetRatio)
    606                 width = height * targetRatio;
    607         }
    608     }
    609 
    610     if (width != window->wl.width || height != window->wl.height)
    611     {
    612         window->wl.width = width;
    613         window->wl.height = height;
    614         resizeWindow(window);
    615 
    616         _glfwInputWindowSize(window, width, height);
    617 
    618         if (window->wl.visible)
    619             _glfwInputWindowDamage(window);
    620     }
    621 
    622     if (!window->wl.visible)
    623     {
    624         // Allow the window to be mapped only if it either has no XDG
    625         // decorations or they have already received a configure event
    626         if (!window->wl.xdg.decoration || window->wl.xdg.decorationMode)
    627         {
    628             window->wl.visible = GLFW_TRUE;
    629             _glfwInputWindowDamage(window);
    630         }
    631     }
    632 }
    633 
    634 static const struct xdg_surface_listener xdgSurfaceListener =
    635 {
    636     xdgSurfaceHandleConfigure
    637 };
    638 
    639 static GLFWbool createShellObjects(_GLFWwindow* window)
    640 {
    641     window->wl.xdg.surface = xdg_wm_base_get_xdg_surface(_glfw.wl.wmBase,
    642                                                          window->wl.surface);
    643     if (!window->wl.xdg.surface)
    644     {
    645         _glfwInputError(GLFW_PLATFORM_ERROR,
    646                         "Wayland: Failed to create xdg-surface for window");
    647         return GLFW_FALSE;
    648     }
    649 
    650     xdg_surface_add_listener(window->wl.xdg.surface, &xdgSurfaceListener, window);
    651 
    652     window->wl.xdg.toplevel = xdg_surface_get_toplevel(window->wl.xdg.surface);
    653     if (!window->wl.xdg.toplevel)
    654     {
    655         _glfwInputError(GLFW_PLATFORM_ERROR,
    656                         "Wayland: Failed to create xdg-toplevel for window");
    657         return GLFW_FALSE;
    658     }
    659 
    660     xdg_toplevel_add_listener(window->wl.xdg.toplevel, &xdgToplevelListener, window);
    661 
    662     if (window->wl.title)
    663         xdg_toplevel_set_title(window->wl.xdg.toplevel, window->wl.title);
    664 
    665     if (window->monitor)
    666     {
    667         xdg_toplevel_set_fullscreen(window->wl.xdg.toplevel, window->monitor->wl.output);
    668         setIdleInhibitor(window, GLFW_TRUE);
    669     }
    670     else
    671     {
    672         if (window->wl.maximized)
    673             xdg_toplevel_set_maximized(window->wl.xdg.toplevel);
    674 
    675         setIdleInhibitor(window, GLFW_FALSE);
    676 
    677         if (_glfw.wl.decorationManager)
    678         {
    679             window->wl.xdg.decoration =
    680                 zxdg_decoration_manager_v1_get_toplevel_decoration(
    681                     _glfw.wl.decorationManager, window->wl.xdg.toplevel);
    682             zxdg_toplevel_decoration_v1_add_listener(window->wl.xdg.decoration,
    683                                                      &xdgDecorationListener,
    684                                                      window);
    685 
    686             uint32_t mode;
    687 
    688             if (window->decorated)
    689                 mode = ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE;
    690             else
    691                 mode = ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE;
    692 
    693             zxdg_toplevel_decoration_v1_set_mode(window->wl.xdg.decoration, mode);
    694         }
    695         else
    696         {
    697             if (window->decorated)
    698                 createFallbackDecorations(window);
    699         }
    700     }
    701 
    702     if (window->minwidth != GLFW_DONT_CARE && window->minheight != GLFW_DONT_CARE)
    703     {
    704         int minwidth  = window->minwidth;
    705         int minheight = window->minheight;
    706 
    707         if (window->wl.decorations.top.surface)
    708         {
    709             minwidth  += GLFW_BORDER_SIZE * 2;
    710             minheight += GLFW_CAPTION_HEIGHT + GLFW_BORDER_SIZE;
    711         }
    712 
    713         xdg_toplevel_set_min_size(window->wl.xdg.toplevel, minwidth, minheight);
    714     }
    715 
    716     if (window->maxwidth != GLFW_DONT_CARE && window->maxheight != GLFW_DONT_CARE)
    717     {
    718         int maxwidth  = window->maxwidth;
    719         int maxheight = window->maxheight;
    720 
    721         if (window->wl.decorations.top.surface)
    722         {
    723             maxwidth  += GLFW_BORDER_SIZE * 2;
    724             maxheight += GLFW_CAPTION_HEIGHT + GLFW_BORDER_SIZE;
    725         }
    726 
    727         xdg_toplevel_set_max_size(window->wl.xdg.toplevel, maxwidth, maxheight);
    728     }
    729 
    730     wl_surface_commit(window->wl.surface);
    731     wl_display_roundtrip(_glfw.wl.display);
    732 
    733     return GLFW_TRUE;
    734 }
    735 
    736 static void destroyShellObjects(_GLFWwindow* window)
    737 {
    738     destroyFallbackDecorations(window);
    739 
    740     if (window->wl.xdg.decoration)
    741         zxdg_toplevel_decoration_v1_destroy(window->wl.xdg.decoration);
    742 
    743     if (window->wl.xdg.toplevel)
    744         xdg_toplevel_destroy(window->wl.xdg.toplevel);
    745 
    746     if (window->wl.xdg.surface)
    747         xdg_surface_destroy(window->wl.xdg.surface);
    748 
    749     window->wl.xdg.decoration = NULL;
    750     window->wl.xdg.decorationMode = 0;
    751     window->wl.xdg.toplevel = NULL;
    752     window->wl.xdg.surface = NULL;
    753 }
    754 
    755 static GLFWbool createNativeSurface(_GLFWwindow* window,
    756                                     const _GLFWwndconfig* wndconfig,
    757                                     const _GLFWfbconfig* fbconfig)
    758 {
    759     window->wl.surface = wl_compositor_create_surface(_glfw.wl.compositor);
    760     if (!window->wl.surface)
    761     {
    762         _glfwInputError(GLFW_PLATFORM_ERROR, "Wayland: Failed to create window surface");
    763         return GLFW_FALSE;
    764     }
    765 
    766     wl_surface_add_listener(window->wl.surface,
    767                             &surfaceListener,
    768                             window);
    769 
    770     wl_surface_set_user_data(window->wl.surface, window);
    771 
    772     window->wl.width = wndconfig->width;
    773     window->wl.height = wndconfig->height;
    774     window->wl.scale = 1;
    775     window->wl.title = _glfw_strdup(wndconfig->title);
    776 
    777     window->wl.maximized = wndconfig->maximized;
    778 
    779     window->wl.transparent = fbconfig->transparent;
    780     if (!window->wl.transparent)
    781         setContentAreaOpaque(window);
    782 
    783     return GLFW_TRUE;
    784 }
    785 
    786 static void setCursorImage(_GLFWwindow* window,
    787                            _GLFWcursorWayland* cursorWayland)
    788 {
    789     struct itimerspec timer = {};
    790     struct wl_cursor* wlCursor = cursorWayland->cursor;
    791     struct wl_cursor_image* image;
    792     struct wl_buffer* buffer;
    793     struct wl_surface* surface = _glfw.wl.cursorSurface;
    794     int scale = 1;
    795 
    796     if (!wlCursor)
    797         buffer = cursorWayland->buffer;
    798     else
    799     {
    800         if (window->wl.scale > 1 && cursorWayland->cursorHiDPI)
    801         {
    802             wlCursor = cursorWayland->cursorHiDPI;
    803             scale = 2;
    804         }
    805 
    806         image = wlCursor->images[cursorWayland->currentImage];
    807         buffer = wl_cursor_image_get_buffer(image);
    808         if (!buffer)
    809             return;
    810 
    811         timer.it_value.tv_sec = image->delay / 1000;
    812         timer.it_value.tv_nsec = (image->delay % 1000) * 1000000;
    813         timerfd_settime(_glfw.wl.cursorTimerfd, 0, &timer, NULL);
    814 
    815         cursorWayland->width = image->width;
    816         cursorWayland->height = image->height;
    817         cursorWayland->xhot = image->hotspot_x;
    818         cursorWayland->yhot = image->hotspot_y;
    819     }
    820 
    821     wl_pointer_set_cursor(_glfw.wl.pointer, _glfw.wl.pointerEnterSerial,
    822                           surface,
    823                           cursorWayland->xhot / scale,
    824                           cursorWayland->yhot / scale);
    825     wl_surface_set_buffer_scale(surface, scale);
    826     wl_surface_attach(surface, buffer, 0, 0);
    827     wl_surface_damage(surface, 0, 0,
    828                       cursorWayland->width, cursorWayland->height);
    829     wl_surface_commit(surface);
    830 }
    831 
    832 static void incrementCursorImage(_GLFWwindow* window)
    833 {
    834     _GLFWcursor* cursor;
    835 
    836     if (!window || window->wl.decorations.focus != mainWindow)
    837         return;
    838 
    839     cursor = window->wl.currentCursor;
    840     if (cursor && cursor->wl.cursor)
    841     {
    842         cursor->wl.currentImage += 1;
    843         cursor->wl.currentImage %= cursor->wl.cursor->image_count;
    844         setCursorImage(window, &cursor->wl);
    845     }
    846 }
    847 
    848 static GLFWbool flushDisplay(void)
    849 {
    850     while (wl_display_flush(_glfw.wl.display) == -1)
    851     {
    852         if (errno != EAGAIN)
    853             return GLFW_FALSE;
    854 
    855         struct pollfd fd = { wl_display_get_fd(_glfw.wl.display), POLLOUT };
    856 
    857         while (poll(&fd, 1, -1) == -1)
    858         {
    859             if (errno != EINTR && errno != EAGAIN)
    860                 return GLFW_FALSE;
    861         }
    862     }
    863 
    864     return GLFW_TRUE;
    865 }
    866 
    867 static void handleEvents(double* timeout)
    868 {
    869     GLFWbool event = GLFW_FALSE;
    870     struct pollfd fds[] =
    871     {
    872         { wl_display_get_fd(_glfw.wl.display), POLLIN },
    873         { _glfw.wl.timerfd, POLLIN },
    874         { _glfw.wl.cursorTimerfd, POLLIN },
    875     };
    876 
    877     while (!event)
    878     {
    879         while (wl_display_prepare_read(_glfw.wl.display) != 0)
    880             wl_display_dispatch_pending(_glfw.wl.display);
    881 
    882         // If an error other than EAGAIN happens, we have likely been disconnected
    883         // from the Wayland session; try to handle that the best we can.
    884         if (!flushDisplay())
    885         {
    886             wl_display_cancel_read(_glfw.wl.display);
    887 
    888             _GLFWwindow* window = _glfw.windowListHead;
    889             while (window)
    890             {
    891                 _glfwInputWindowCloseRequest(window);
    892                 window = window->next;
    893             }
    894 
    895             return;
    896         }
    897 
    898         if (!waitForData(fds, 3, timeout))
    899         {
    900             wl_display_cancel_read(_glfw.wl.display);
    901             return;
    902         }
    903 
    904         if (fds[0].revents & POLLIN)
    905         {
    906             wl_display_read_events(_glfw.wl.display);
    907             if (wl_display_dispatch_pending(_glfw.wl.display) > 0)
    908                 event = GLFW_TRUE;
    909         }
    910         else
    911             wl_display_cancel_read(_glfw.wl.display);
    912 
    913         if (fds[1].revents & POLLIN)
    914         {
    915             uint64_t repeats;
    916 
    917             if (read(_glfw.wl.timerfd, &repeats, sizeof(repeats)) == 8)
    918             {
    919                 for (uint64_t i = 0; i < repeats; i++)
    920                 {
    921                     _glfwInputKey(_glfw.wl.keyboardFocus,
    922                                   _glfw.wl.keyboardLastKey,
    923                                   _glfw.wl.keyboardLastScancode,
    924                                   GLFW_PRESS,
    925                                   _glfw.wl.xkb.modifiers);
    926                     _glfwInputTextWayland(_glfw.wl.keyboardFocus,
    927                                           _glfw.wl.keyboardLastScancode);
    928                 }
    929 
    930                 event = GLFW_TRUE;
    931             }
    932         }
    933 
    934         if (fds[2].revents & POLLIN)
    935         {
    936             uint64_t repeats;
    937 
    938             if (read(_glfw.wl.cursorTimerfd, &repeats, sizeof(repeats)) == 8)
    939             {
    940                 incrementCursorImage(_glfw.wl.pointerFocus);
    941                 event = GLFW_TRUE;
    942             }
    943         }
    944     }
    945 }
    946 
    947 // Reads the specified data offer as the specified MIME type
    948 //
    949 static char* readDataOfferAsString(struct wl_data_offer* offer, const char* mimeType)
    950 {
    951     int fds[2];
    952 
    953     if (pipe2(fds, O_CLOEXEC) == -1)
    954     {
    955         _glfwInputError(GLFW_PLATFORM_ERROR,
    956                         "Wayland: Failed to create pipe for data offer: %s",
    957                         strerror(errno));
    958         return NULL;
    959     }
    960 
    961     wl_data_offer_receive(offer, mimeType, fds[1]);
    962     flushDisplay();
    963     close(fds[1]);
    964 
    965     char* string = NULL;
    966     size_t size = 0;
    967     size_t length = 0;
    968 
    969     for (;;)
    970     {
    971         const size_t readSize = 4096;
    972         const size_t requiredSize = length + readSize + 1;
    973         if (requiredSize > size)
    974         {
    975             char* longer = realloc(string, requiredSize);
    976             if (!longer)
    977             {
    978                 _glfwInputError(GLFW_OUT_OF_MEMORY, NULL);
    979                 close(fds[0]);
    980                 return NULL;
    981             }
    982 
    983             string = longer;
    984             size = requiredSize;
    985         }
    986 
    987         const ssize_t result = read(fds[0], string + length, readSize);
    988         if (result == 0)
    989             break;
    990         else if (result == -1)
    991         {
    992             if (errno == EINTR)
    993                 continue;
    994 
    995             _glfwInputError(GLFW_PLATFORM_ERROR,
    996                             "Wayland: Failed to read from data offer pipe: %s",
    997                             strerror(errno));
    998             close(fds[0]);
    999             return NULL;
   1000         }
   1001 
   1002         length += result;
   1003     }
   1004 
   1005     close(fds[0]);
   1006 
   1007     string[length] = '\0';
   1008     return string;
   1009 }
   1010 
   1011 static _GLFWwindow* findWindowFromDecorationSurface(struct wl_surface* surface,
   1012                                                     _GLFWdecorationSideWayland* which)
   1013 {
   1014     _GLFWdecorationSideWayland focus;
   1015     _GLFWwindow* window = _glfw.windowListHead;
   1016     if (!which)
   1017         which = &focus;
   1018     while (window)
   1019     {
   1020         if (surface == window->wl.decorations.top.surface)
   1021         {
   1022             *which = topDecoration;
   1023             break;
   1024         }
   1025         if (surface == window->wl.decorations.left.surface)
   1026         {
   1027             *which = leftDecoration;
   1028             break;
   1029         }
   1030         if (surface == window->wl.decorations.right.surface)
   1031         {
   1032             *which = rightDecoration;
   1033             break;
   1034         }
   1035         if (surface == window->wl.decorations.bottom.surface)
   1036         {
   1037             *which = bottomDecoration;
   1038             break;
   1039         }
   1040         window = window->next;
   1041     }
   1042     return window;
   1043 }
   1044 
   1045 static void pointerHandleEnter(void* userData,
   1046                                struct wl_pointer* pointer,
   1047                                uint32_t serial,
   1048                                struct wl_surface* surface,
   1049                                wl_fixed_t sx,
   1050                                wl_fixed_t sy)
   1051 {
   1052     // Happens in the case we just destroyed the surface.
   1053     if (!surface)
   1054         return;
   1055 
   1056     _GLFWdecorationSideWayland focus = mainWindow;
   1057     _GLFWwindow* window = wl_surface_get_user_data(surface);
   1058     if (!window)
   1059     {
   1060         window = findWindowFromDecorationSurface(surface, &focus);
   1061         if (!window)
   1062             return;
   1063     }
   1064 
   1065     window->wl.decorations.focus = focus;
   1066     _glfw.wl.serial = serial;
   1067     _glfw.wl.pointerEnterSerial = serial;
   1068     _glfw.wl.pointerFocus = window;
   1069 
   1070     window->wl.hovered = GLFW_TRUE;
   1071 
   1072     _glfwPlatformSetCursor(window, window->wl.currentCursor);
   1073     _glfwInputCursorEnter(window, GLFW_TRUE);
   1074 }
   1075 
   1076 static void pointerHandleLeave(void* userData,
   1077                                struct wl_pointer* pointer,
   1078                                uint32_t serial,
   1079                                struct wl_surface* surface)
   1080 {
   1081     _GLFWwindow* window = _glfw.wl.pointerFocus;
   1082 
   1083     if (!window)
   1084         return;
   1085 
   1086     window->wl.hovered = GLFW_FALSE;
   1087 
   1088     _glfw.wl.serial = serial;
   1089     _glfw.wl.pointerFocus = NULL;
   1090     _glfwInputCursorEnter(window, GLFW_FALSE);
   1091     _glfw.wl.cursorPreviousName = NULL;
   1092 }
   1093 
   1094 static void setCursor(_GLFWwindow* window, const char* name)
   1095 {
   1096     struct wl_buffer* buffer;
   1097     struct wl_cursor* cursor;
   1098     struct wl_cursor_image* image;
   1099     struct wl_surface* surface = _glfw.wl.cursorSurface;
   1100     struct wl_cursor_theme* theme = _glfw.wl.cursorTheme;
   1101     int scale = 1;
   1102 
   1103     if (window->wl.scale > 1 && _glfw.wl.cursorThemeHiDPI)
   1104     {
   1105         // We only support up to scale=2 for now, since libwayland-cursor
   1106         // requires us to load a different theme for each size.
   1107         scale = 2;
   1108         theme = _glfw.wl.cursorThemeHiDPI;
   1109     }
   1110 
   1111     cursor = wl_cursor_theme_get_cursor(theme, name);
   1112     if (!cursor)
   1113     {
   1114         _glfwInputError(GLFW_PLATFORM_ERROR,
   1115                         "Wayland: Standard cursor shape unavailable");
   1116         return;
   1117     }
   1118     // TODO: handle animated cursors too.
   1119     image = cursor->images[0];
   1120 
   1121     if (!image)
   1122         return;
   1123 
   1124     buffer = wl_cursor_image_get_buffer(image);
   1125     if (!buffer)
   1126         return;
   1127     wl_pointer_set_cursor(_glfw.wl.pointer, _glfw.wl.pointerEnterSerial,
   1128                           surface,
   1129                           image->hotspot_x / scale,
   1130                           image->hotspot_y / scale);
   1131     wl_surface_set_buffer_scale(surface, scale);
   1132     wl_surface_attach(surface, buffer, 0, 0);
   1133     wl_surface_damage(surface, 0, 0,
   1134                       image->width, image->height);
   1135     wl_surface_commit(surface);
   1136     _glfw.wl.cursorPreviousName = name;
   1137 }
   1138 
   1139 static void pointerHandleMotion(void* userData,
   1140                                 struct wl_pointer* pointer,
   1141                                 uint32_t time,
   1142                                 wl_fixed_t sx,
   1143                                 wl_fixed_t sy)
   1144 {
   1145     _GLFWwindow* window = _glfw.wl.pointerFocus;
   1146     const char* cursorName = NULL;
   1147     double x, y;
   1148 
   1149     if (!window)
   1150         return;
   1151 
   1152     if (window->cursorMode == GLFW_CURSOR_DISABLED)
   1153         return;
   1154     x = wl_fixed_to_double(sx);
   1155     y = wl_fixed_to_double(sy);
   1156     window->wl.cursorPosX = x;
   1157     window->wl.cursorPosY = y;
   1158 
   1159     switch (window->wl.decorations.focus)
   1160     {
   1161         case mainWindow:
   1162             _glfwInputCursorPos(window, x, y);
   1163             _glfw.wl.cursorPreviousName = NULL;
   1164             return;
   1165         case topDecoration:
   1166             if (y < GLFW_BORDER_SIZE)
   1167                 cursorName = "n-resize";
   1168             else
   1169                 cursorName = "left_ptr";
   1170             break;
   1171         case leftDecoration:
   1172             if (y < GLFW_BORDER_SIZE)
   1173                 cursorName = "nw-resize";
   1174             else
   1175                 cursorName = "w-resize";
   1176             break;
   1177         case rightDecoration:
   1178             if (y < GLFW_BORDER_SIZE)
   1179                 cursorName = "ne-resize";
   1180             else
   1181                 cursorName = "e-resize";
   1182             break;
   1183         case bottomDecoration:
   1184             if (x < GLFW_BORDER_SIZE)
   1185                 cursorName = "sw-resize";
   1186             else if (x > window->wl.width + GLFW_BORDER_SIZE)
   1187                 cursorName = "se-resize";
   1188             else
   1189                 cursorName = "s-resize";
   1190             break;
   1191         default:
   1192             assert(0);
   1193     }
   1194     if (_glfw.wl.cursorPreviousName != cursorName)
   1195         setCursor(window, cursorName);
   1196 }
   1197 
   1198 static void pointerHandleButton(void* userData,
   1199                                 struct wl_pointer* pointer,
   1200                                 uint32_t serial,
   1201                                 uint32_t time,
   1202                                 uint32_t button,
   1203                                 uint32_t state)
   1204 {
   1205     _GLFWwindow* window = _glfw.wl.pointerFocus;
   1206     int glfwButton;
   1207 
   1208     uint32_t edges = XDG_TOPLEVEL_RESIZE_EDGE_NONE;
   1209 
   1210     if (!window)
   1211         return;
   1212     if (button == BTN_LEFT)
   1213     {
   1214         switch (window->wl.decorations.focus)
   1215         {
   1216             case mainWindow:
   1217                 break;
   1218             case topDecoration:
   1219                 if (window->wl.cursorPosY < GLFW_BORDER_SIZE)
   1220                     edges = XDG_TOPLEVEL_RESIZE_EDGE_TOP;
   1221                 else
   1222                 {
   1223                     xdg_toplevel_move(window->wl.xdg.toplevel, _glfw.wl.seat, serial);
   1224                 }
   1225                 break;
   1226             case leftDecoration:
   1227                 if (window->wl.cursorPosY < GLFW_BORDER_SIZE)
   1228                     edges = XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT;
   1229                 else
   1230                     edges = XDG_TOPLEVEL_RESIZE_EDGE_LEFT;
   1231                 break;
   1232             case rightDecoration:
   1233                 if (window->wl.cursorPosY < GLFW_BORDER_SIZE)
   1234                     edges = XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT;
   1235                 else
   1236                     edges = XDG_TOPLEVEL_RESIZE_EDGE_RIGHT;
   1237                 break;
   1238             case bottomDecoration:
   1239                 if (window->wl.cursorPosX < GLFW_BORDER_SIZE)
   1240                     edges = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT;
   1241                 else if (window->wl.cursorPosX > window->wl.width + GLFW_BORDER_SIZE)
   1242                     edges = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT;
   1243                 else
   1244                     edges = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM;
   1245                 break;
   1246             default:
   1247                 assert(0);
   1248         }
   1249         if (edges != XDG_TOPLEVEL_RESIZE_EDGE_NONE)
   1250         {
   1251             xdg_toplevel_resize(window->wl.xdg.toplevel, _glfw.wl.seat,
   1252                                 serial, edges);
   1253             return;
   1254         }
   1255     }
   1256     else if (button == BTN_RIGHT)
   1257     {
   1258         if (window->wl.decorations.focus != mainWindow && window->wl.xdg.toplevel)
   1259         {
   1260             xdg_toplevel_show_window_menu(window->wl.xdg.toplevel,
   1261                                           _glfw.wl.seat, serial,
   1262                                           window->wl.cursorPosX,
   1263                                           window->wl.cursorPosY);
   1264             return;
   1265         }
   1266     }
   1267 
   1268     // Don’t pass the button to the user if it was related to a decoration.
   1269     if (window->wl.decorations.focus != mainWindow)
   1270         return;
   1271 
   1272     _glfw.wl.serial = serial;
   1273 
   1274     /* Makes left, right and middle 0, 1 and 2. Overall order follows evdev
   1275      * codes. */
   1276     glfwButton = button - BTN_LEFT;
   1277 
   1278     _glfwInputMouseClick(window,
   1279                          glfwButton,
   1280                          state == WL_POINTER_BUTTON_STATE_PRESSED
   1281                                 ? GLFW_PRESS
   1282                                 : GLFW_RELEASE,
   1283                          _glfw.wl.xkb.modifiers);
   1284 }
   1285 
   1286 static void pointerHandleAxis(void* userData,
   1287                               struct wl_pointer* pointer,
   1288                               uint32_t time,
   1289                               uint32_t axis,
   1290                               wl_fixed_t value)
   1291 {
   1292     _GLFWwindow* window = _glfw.wl.pointerFocus;
   1293     double x = 0.0, y = 0.0;
   1294     // Wayland scroll events are in pointer motion coordinate space (think two
   1295     // finger scroll).  The factor 10 is commonly used to convert to "scroll
   1296     // step means 1.0.
   1297     const double scrollFactor = 1.0 / 10.0;
   1298 
   1299     if (!window)
   1300         return;
   1301 
   1302     assert(axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL ||
   1303            axis == WL_POINTER_AXIS_VERTICAL_SCROLL);
   1304 
   1305     if (axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL)
   1306         x = -wl_fixed_to_double(value) * scrollFactor;
   1307     else if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL)
   1308         y = -wl_fixed_to_double(value) * scrollFactor;
   1309 
   1310     _glfwInputScroll(window, x, y);
   1311 }
   1312 
   1313 static const struct wl_pointer_listener pointerListener =
   1314 {
   1315     pointerHandleEnter,
   1316     pointerHandleLeave,
   1317     pointerHandleMotion,
   1318     pointerHandleButton,
   1319     pointerHandleAxis,
   1320 };
   1321 
   1322 static void keyboardHandleKeymap(void* userData,
   1323                                  struct wl_keyboard* keyboard,
   1324                                  uint32_t format,
   1325                                  int fd,
   1326                                  uint32_t size)
   1327 {
   1328     struct xkb_keymap* keymap;
   1329     struct xkb_state* state;
   1330     struct xkb_compose_table* composeTable;
   1331     struct xkb_compose_state* composeState;
   1332     char* mapStr;
   1333     const char* locale;
   1334 
   1335     if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1)
   1336     {
   1337         close(fd);
   1338         return;
   1339     }
   1340 
   1341     mapStr = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
   1342     if (mapStr == MAP_FAILED) {
   1343         close(fd);
   1344         return;
   1345     }
   1346 
   1347     keymap = xkb_keymap_new_from_string(_glfw.wl.xkb.context,
   1348                                         mapStr,
   1349                                         XKB_KEYMAP_FORMAT_TEXT_V1,
   1350                                         0);
   1351     munmap(mapStr, size);
   1352     close(fd);
   1353 
   1354     if (!keymap)
   1355     {
   1356         _glfwInputError(GLFW_PLATFORM_ERROR,
   1357                         "Wayland: Failed to compile keymap");
   1358         return;
   1359     }
   1360 
   1361     state = xkb_state_new(keymap);
   1362     if (!state)
   1363     {
   1364         _glfwInputError(GLFW_PLATFORM_ERROR,
   1365                         "Wayland: Failed to create XKB state");
   1366         xkb_keymap_unref(keymap);
   1367         return;
   1368     }
   1369 
   1370     // Look up the preferred locale, falling back to "C" as default.
   1371     locale = getenv("LC_ALL");
   1372     if (!locale)
   1373         locale = getenv("LC_CTYPE");
   1374     if (!locale)
   1375         locale = getenv("LANG");
   1376     if (!locale)
   1377         locale = "C";
   1378 
   1379     composeTable =
   1380         xkb_compose_table_new_from_locale(_glfw.wl.xkb.context, locale,
   1381                                           XKB_COMPOSE_COMPILE_NO_FLAGS);
   1382     if (composeTable)
   1383     {
   1384         composeState =
   1385             xkb_compose_state_new(composeTable, XKB_COMPOSE_STATE_NO_FLAGS);
   1386         xkb_compose_table_unref(composeTable);
   1387         if (composeState)
   1388             _glfw.wl.xkb.composeState = composeState;
   1389         else
   1390             _glfwInputError(GLFW_PLATFORM_ERROR,
   1391                             "Wayland: Failed to create XKB compose state");
   1392     }
   1393     else
   1394     {
   1395         _glfwInputError(GLFW_PLATFORM_ERROR,
   1396                         "Wayland: Failed to create XKB compose table");
   1397     }
   1398 
   1399     xkb_keymap_unref(_glfw.wl.xkb.keymap);
   1400     xkb_state_unref(_glfw.wl.xkb.state);
   1401     _glfw.wl.xkb.keymap = keymap;
   1402     _glfw.wl.xkb.state = state;
   1403 
   1404     _glfw.wl.xkb.controlIndex  = xkb_keymap_mod_get_index(_glfw.wl.xkb.keymap, "Control");
   1405     _glfw.wl.xkb.altIndex      = xkb_keymap_mod_get_index(_glfw.wl.xkb.keymap, "Mod1");
   1406     _glfw.wl.xkb.shiftIndex    = xkb_keymap_mod_get_index(_glfw.wl.xkb.keymap, "Shift");
   1407     _glfw.wl.xkb.superIndex    = xkb_keymap_mod_get_index(_glfw.wl.xkb.keymap, "Mod4");
   1408     _glfw.wl.xkb.capsLockIndex = xkb_keymap_mod_get_index(_glfw.wl.xkb.keymap, "Lock");
   1409     _glfw.wl.xkb.numLockIndex  = xkb_keymap_mod_get_index(_glfw.wl.xkb.keymap, "Mod2");
   1410 }
   1411 
   1412 static void keyboardHandleEnter(void* userData,
   1413                                 struct wl_keyboard* keyboard,
   1414                                 uint32_t serial,
   1415                                 struct wl_surface* surface,
   1416                                 struct wl_array* keys)
   1417 {
   1418     // Happens in the case we just destroyed the surface.
   1419     if (!surface)
   1420         return;
   1421 
   1422     _GLFWwindow* window = wl_surface_get_user_data(surface);
   1423     if (!window)
   1424     {
   1425         window = findWindowFromDecorationSurface(surface, NULL);
   1426         if (!window)
   1427             return;
   1428     }
   1429 
   1430     _glfw.wl.serial = serial;
   1431     _glfw.wl.keyboardFocus = window;
   1432     _glfwInputWindowFocus(window, GLFW_TRUE);
   1433 }
   1434 
   1435 static void keyboardHandleLeave(void* userData,
   1436                                 struct wl_keyboard* keyboard,
   1437                                 uint32_t serial,
   1438                                 struct wl_surface* surface)
   1439 {
   1440     _GLFWwindow* window = _glfw.wl.keyboardFocus;
   1441 
   1442     if (!window)
   1443         return;
   1444 
   1445     struct itimerspec timer = {};
   1446     timerfd_settime(_glfw.wl.timerfd, 0, &timer, NULL);
   1447 
   1448     _glfw.wl.serial = serial;
   1449     _glfw.wl.keyboardFocus = NULL;
   1450     _glfwInputWindowFocus(window, GLFW_FALSE);
   1451 }
   1452 
   1453 static int translateKey(uint32_t scancode)
   1454 {
   1455     if (scancode < sizeof(_glfw.wl.keycodes) / sizeof(_glfw.wl.keycodes[0]))
   1456         return _glfw.wl.keycodes[scancode];
   1457 
   1458     return GLFW_KEY_UNKNOWN;
   1459 }
   1460 
   1461 static xkb_keysym_t composeSymbol(xkb_keysym_t sym)
   1462 {
   1463     if (sym == XKB_KEY_NoSymbol || !_glfw.wl.xkb.composeState)
   1464         return sym;
   1465     if (xkb_compose_state_feed(_glfw.wl.xkb.composeState, sym)
   1466             != XKB_COMPOSE_FEED_ACCEPTED)
   1467         return sym;
   1468     switch (xkb_compose_state_get_status(_glfw.wl.xkb.composeState))
   1469     {
   1470         case XKB_COMPOSE_COMPOSED:
   1471             return xkb_compose_state_get_one_sym(_glfw.wl.xkb.composeState);
   1472         case XKB_COMPOSE_COMPOSING:
   1473         case XKB_COMPOSE_CANCELLED:
   1474             return XKB_KEY_NoSymbol;
   1475         case XKB_COMPOSE_NOTHING:
   1476         default:
   1477             return sym;
   1478     }
   1479 }
   1480 
   1481 GLFWbool _glfwInputTextWayland(_GLFWwindow* window, uint32_t scancode)
   1482 {
   1483     const xkb_keysym_t* keysyms;
   1484     const xkb_keycode_t keycode = scancode + 8;
   1485 
   1486     if (xkb_state_key_get_syms(_glfw.wl.xkb.state, keycode, &keysyms) == 1)
   1487     {
   1488         const xkb_keysym_t keysym = composeSymbol(keysyms[0]);
   1489         const uint32_t codepoint = _glfwKeySym2Unicode(keysym);
   1490         if (codepoint != GLFW_INVALID_CODEPOINT)
   1491         {
   1492             const int mods = _glfw.wl.xkb.modifiers;
   1493             const int plain = !(mods & (GLFW_MOD_CONTROL | GLFW_MOD_ALT));
   1494             _glfwInputChar(window, codepoint, mods, plain);
   1495         }
   1496     }
   1497 
   1498     return xkb_keymap_key_repeats(_glfw.wl.xkb.keymap, keycode);
   1499 }
   1500 
   1501 static void keyboardHandleKey(void* userData,
   1502                               struct wl_keyboard* keyboard,
   1503                               uint32_t serial,
   1504                               uint32_t time,
   1505                               uint32_t scancode,
   1506                               uint32_t state)
   1507 {
   1508     _GLFWwindow* window = _glfw.wl.keyboardFocus;
   1509     if (!window)
   1510         return;
   1511 
   1512     const int key = translateKey(scancode);
   1513     const int action =
   1514         state == WL_KEYBOARD_KEY_STATE_PRESSED ? GLFW_PRESS : GLFW_RELEASE;
   1515 
   1516     _glfw.wl.serial = serial;
   1517     _glfwInputKey(window, key, scancode, action, _glfw.wl.xkb.modifiers);
   1518 
   1519     struct itimerspec timer = {};
   1520 
   1521     if (action == GLFW_PRESS)
   1522     {
   1523         const GLFWbool shouldRepeat = _glfwInputTextWayland(window, scancode);
   1524 
   1525         if (shouldRepeat && _glfw.wl.keyboardRepeatRate > 0)
   1526         {
   1527             _glfw.wl.keyboardLastKey = key;
   1528             _glfw.wl.keyboardLastScancode = scancode;
   1529             if (_glfw.wl.keyboardRepeatRate > 1)
   1530                 timer.it_interval.tv_nsec = 1000000000 / _glfw.wl.keyboardRepeatRate;
   1531             else
   1532                 timer.it_interval.tv_sec = 1;
   1533 
   1534             timer.it_value.tv_sec = _glfw.wl.keyboardRepeatDelay / 1000;
   1535             timer.it_value.tv_nsec = (_glfw.wl.keyboardRepeatDelay % 1000) * 1000000;
   1536         }
   1537     }
   1538 
   1539     timerfd_settime(_glfw.wl.timerfd, 0, &timer, NULL);
   1540 }
   1541 
   1542 static void keyboardHandleModifiers(void* userData,
   1543                                     struct wl_keyboard* keyboard,
   1544                                     uint32_t serial,
   1545                                     uint32_t modsDepressed,
   1546                                     uint32_t modsLatched,
   1547                                     uint32_t modsLocked,
   1548                                     uint32_t group)
   1549 {
   1550     _glfw.wl.serial = serial;
   1551 
   1552     if (!_glfw.wl.xkb.keymap)
   1553         return;
   1554 
   1555     xkb_state_update_mask(_glfw.wl.xkb.state,
   1556                           modsDepressed,
   1557                           modsLatched,
   1558                           modsLocked,
   1559                           0,
   1560                           0,
   1561                           group);
   1562 
   1563     _glfw.wl.xkb.modifiers = 0;
   1564 
   1565     struct
   1566     {
   1567         xkb_mod_index_t index;
   1568         unsigned int bit;
   1569     } modifiers[] =
   1570     {
   1571         { _glfw.wl.xkb.controlIndex,  GLFW_MOD_CONTROL },
   1572         { _glfw.wl.xkb.altIndex,      GLFW_MOD_ALT },
   1573         { _glfw.wl.xkb.shiftIndex,    GLFW_MOD_SHIFT },
   1574         { _glfw.wl.xkb.superIndex,    GLFW_MOD_SUPER },
   1575         { _glfw.wl.xkb.capsLockIndex, GLFW_MOD_CAPS_LOCK },
   1576         { _glfw.wl.xkb.numLockIndex,  GLFW_MOD_NUM_LOCK }
   1577     };
   1578 
   1579     for (size_t i = 0; i < sizeof(modifiers) / sizeof(modifiers[0]); i++)
   1580     {
   1581         if (xkb_state_mod_index_is_active(_glfw.wl.xkb.state,
   1582                                           modifiers[i].index,
   1583                                           XKB_STATE_MODS_EFFECTIVE) == 1)
   1584         {
   1585             _glfw.wl.xkb.modifiers |= modifiers[i].bit;
   1586         }
   1587     }
   1588 }
   1589 
   1590 #ifdef WL_KEYBOARD_REPEAT_INFO_SINCE_VERSION
   1591 static void keyboardHandleRepeatInfo(void* userData,
   1592                                      struct wl_keyboard* keyboard,
   1593                                      int32_t rate,
   1594                                      int32_t delay)
   1595 {
   1596     if (keyboard != _glfw.wl.keyboard)
   1597         return;
   1598 
   1599     _glfw.wl.keyboardRepeatRate = rate;
   1600     _glfw.wl.keyboardRepeatDelay = delay;
   1601 }
   1602 #endif
   1603 
   1604 static const struct wl_keyboard_listener keyboardListener =
   1605 {
   1606     keyboardHandleKeymap,
   1607     keyboardHandleEnter,
   1608     keyboardHandleLeave,
   1609     keyboardHandleKey,
   1610     keyboardHandleModifiers,
   1611 #ifdef WL_KEYBOARD_REPEAT_INFO_SINCE_VERSION
   1612     keyboardHandleRepeatInfo,
   1613 #endif
   1614 };
   1615 
   1616 static void seatHandleCapabilities(void* userData,
   1617                                    struct wl_seat* seat,
   1618                                    enum wl_seat_capability caps)
   1619 {
   1620     if ((caps & WL_SEAT_CAPABILITY_POINTER) && !_glfw.wl.pointer)
   1621     {
   1622         _glfw.wl.pointer = wl_seat_get_pointer(seat);
   1623         wl_pointer_add_listener(_glfw.wl.pointer, &pointerListener, NULL);
   1624     }
   1625     else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && _glfw.wl.pointer)
   1626     {
   1627         wl_pointer_destroy(_glfw.wl.pointer);
   1628         _glfw.wl.pointer = NULL;
   1629     }
   1630 
   1631     if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !_glfw.wl.keyboard)
   1632     {
   1633         _glfw.wl.keyboard = wl_seat_get_keyboard(seat);
   1634         wl_keyboard_add_listener(_glfw.wl.keyboard, &keyboardListener, NULL);
   1635     }
   1636     else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && _glfw.wl.keyboard)
   1637     {
   1638         wl_keyboard_destroy(_glfw.wl.keyboard);
   1639         _glfw.wl.keyboard = NULL;
   1640     }
   1641 }
   1642 
   1643 static void seatHandleName(void* userData,
   1644                            struct wl_seat* seat,
   1645                            const char* name)
   1646 {
   1647 }
   1648 
   1649 static const struct wl_seat_listener seatListener =
   1650 {
   1651     seatHandleCapabilities,
   1652     seatHandleName,
   1653 };
   1654 
   1655 static void dataOfferHandleOffer(void* userData,
   1656                                  struct wl_data_offer* offer,
   1657                                  const char* mimeType)
   1658 {
   1659     for (unsigned int i = 0; i < _glfw.wl.offerCount; i++)
   1660     {
   1661         if (_glfw.wl.offers[i].offer == offer)
   1662         {
   1663             if (strcmp(mimeType, "text/plain;charset=utf-8") == 0)
   1664                 _glfw.wl.offers[i].text_plain_utf8 = GLFW_TRUE;
   1665             else if (strcmp(mimeType, "text/uri-list") == 0)
   1666                 _glfw.wl.offers[i].text_uri_list = GLFW_TRUE;
   1667 
   1668             break;
   1669         }
   1670     }
   1671 }
   1672 
   1673 static const struct wl_data_offer_listener dataOfferListener =
   1674 {
   1675     dataOfferHandleOffer
   1676 };
   1677 
   1678 static void dataDeviceHandleDataOffer(void* userData,
   1679                                       struct wl_data_device* device,
   1680                                       struct wl_data_offer* offer)
   1681 {
   1682     _GLFWofferWayland* offers =
   1683         realloc(_glfw.wl.offers, _glfw.wl.offerCount + 1);
   1684     if (!offers)
   1685     {
   1686         _glfwInputError(GLFW_OUT_OF_MEMORY, NULL);
   1687         return;
   1688     }
   1689 
   1690     _glfw.wl.offers = offers;
   1691     _glfw.wl.offerCount++;
   1692 
   1693     _glfw.wl.offers[_glfw.wl.offerCount - 1] = (_GLFWofferWayland) { offer };
   1694     wl_data_offer_add_listener(offer, &dataOfferListener, NULL);
   1695 }
   1696 
   1697 static void dataDeviceHandleEnter(void* userData,
   1698                                   struct wl_data_device* device,
   1699                                   uint32_t serial,
   1700                                   struct wl_surface* surface,
   1701                                   wl_fixed_t x,
   1702                                   wl_fixed_t y,
   1703                                   struct wl_data_offer* offer)
   1704 {
   1705     if (_glfw.wl.dragOffer)
   1706     {
   1707         wl_data_offer_destroy(_glfw.wl.dragOffer);
   1708         _glfw.wl.dragOffer = NULL;
   1709         _glfw.wl.dragFocus = NULL;
   1710     }
   1711 
   1712     for (unsigned int i = 0; i < _glfw.wl.offerCount; i++)
   1713     {
   1714         if (_glfw.wl.offers[i].offer == offer)
   1715         {
   1716             _GLFWwindow* window = NULL;
   1717 
   1718             if (surface)
   1719                 window = wl_surface_get_user_data(surface);
   1720 
   1721             if (window && _glfw.wl.offers[i].text_uri_list)
   1722             {
   1723                 _glfw.wl.dragOffer = offer;
   1724                 _glfw.wl.dragFocus = window;
   1725                 _glfw.wl.dragSerial = serial;
   1726             }
   1727 
   1728             _glfw.wl.offers[i] = _glfw.wl.offers[_glfw.wl.offerCount - 1];
   1729             _glfw.wl.offerCount--;
   1730             break;
   1731         }
   1732     }
   1733 
   1734     if (_glfw.wl.dragOffer)
   1735         wl_data_offer_accept(offer, serial, "text/uri-list");
   1736     else
   1737     {
   1738         wl_data_offer_accept(offer, serial, NULL);
   1739         wl_data_offer_destroy(offer);
   1740     }
   1741 }
   1742 
   1743 static void dataDeviceHandleLeave(void* userData,
   1744                                   struct wl_data_device* device)
   1745 {
   1746     if (_glfw.wl.dragOffer)
   1747     {
   1748         wl_data_offer_destroy(_glfw.wl.dragOffer);
   1749         _glfw.wl.dragOffer = NULL;
   1750         _glfw.wl.dragFocus = NULL;
   1751     }
   1752 }
   1753 
   1754 static void dataDeviceHandleMotion(void* userData,
   1755                                    struct wl_data_device* device,
   1756                                    uint32_t time,
   1757                                    wl_fixed_t x,
   1758                                    wl_fixed_t y)
   1759 {
   1760 }
   1761 
   1762 static void dataDeviceHandleDrop(void* userData,
   1763                                  struct wl_data_device* device)
   1764 {
   1765     if (!_glfw.wl.dragOffer)
   1766         return;
   1767 
   1768     char* string = readDataOfferAsString(_glfw.wl.dragOffer, "text/uri-list");
   1769     if (string)
   1770     {
   1771         int count;
   1772         char** paths = _glfwParseUriList(string, &count);
   1773         if (paths)
   1774             _glfwInputDrop(_glfw.wl.dragFocus, count, (const char**) paths);
   1775 
   1776         for (int i = 0; i < count; i++)
   1777             free(paths[i]);
   1778 
   1779         free(paths);
   1780     }
   1781 
   1782     free(string);
   1783 }
   1784 
   1785 static void dataDeviceHandleSelection(void* userData,
   1786                                       struct wl_data_device* device,
   1787                                       struct wl_data_offer* offer)
   1788 {
   1789     if (_glfw.wl.selectionOffer)
   1790     {
   1791         wl_data_offer_destroy(_glfw.wl.selectionOffer);
   1792         _glfw.wl.selectionOffer = NULL;
   1793     }
   1794 
   1795     for (unsigned int i = 0; i < _glfw.wl.offerCount; i++)
   1796     {
   1797         if (_glfw.wl.offers[i].offer == offer)
   1798         {
   1799             if (_glfw.wl.offers[i].text_plain_utf8)
   1800                 _glfw.wl.selectionOffer = offer;
   1801             else
   1802                 wl_data_offer_destroy(offer);
   1803 
   1804             _glfw.wl.offers[i] = _glfw.wl.offers[_glfw.wl.offerCount - 1];
   1805             _glfw.wl.offerCount--;
   1806             break;
   1807         }
   1808     }
   1809 }
   1810 
   1811 const struct wl_data_device_listener dataDeviceListener =
   1812 {
   1813     dataDeviceHandleDataOffer,
   1814     dataDeviceHandleEnter,
   1815     dataDeviceHandleLeave,
   1816     dataDeviceHandleMotion,
   1817     dataDeviceHandleDrop,
   1818     dataDeviceHandleSelection,
   1819 };
   1820 
   1821 // Translates a GLFW standard cursor to a theme cursor name
   1822 //
   1823 static char *translateCursorShape(int shape)
   1824 {
   1825     switch (shape)
   1826     {
   1827         case GLFW_ARROW_CURSOR:
   1828             return "left_ptr";
   1829         case GLFW_IBEAM_CURSOR:
   1830             return "xterm";
   1831         case GLFW_CROSSHAIR_CURSOR:
   1832             return "crosshair";
   1833         case GLFW_HAND_CURSOR:
   1834             return "hand2";
   1835         case GLFW_HRESIZE_CURSOR:
   1836             return "sb_h_double_arrow";
   1837         case GLFW_VRESIZE_CURSOR:
   1838             return "sb_v_double_arrow";
   1839     }
   1840     return NULL;
   1841 }
   1842 
   1843 void _glfwAddSeatListenerWayland(struct wl_seat* seat)
   1844 {
   1845     wl_seat_add_listener(seat, &seatListener, NULL);
   1846 }
   1847 
   1848 void _glfwAddDataDeviceListenerWayland(struct wl_data_device* device)
   1849 {
   1850     wl_data_device_add_listener(device, &dataDeviceListener, NULL);
   1851 }
   1852 
   1853 
   1854 //////////////////////////////////////////////////////////////////////////
   1855 //////                       GLFW platform API                      //////
   1856 //////////////////////////////////////////////////////////////////////////
   1857 
   1858 int _glfwPlatformCreateWindow(_GLFWwindow* window,
   1859                               const _GLFWwndconfig* wndconfig,
   1860                               const _GLFWctxconfig* ctxconfig,
   1861                               const _GLFWfbconfig* fbconfig)
   1862 {
   1863     if (!createNativeSurface(window, wndconfig, fbconfig))
   1864         return GLFW_FALSE;
   1865 
   1866     if (ctxconfig->client != GLFW_NO_API)
   1867     {
   1868         if (ctxconfig->source == GLFW_EGL_CONTEXT_API ||
   1869             ctxconfig->source == GLFW_NATIVE_CONTEXT_API)
   1870         {
   1871             window->wl.egl.window = wl_egl_window_create(window->wl.surface,
   1872                                                          wndconfig->width,
   1873                                                          wndconfig->height);
   1874             if (!window->wl.egl.window)
   1875             {
   1876                 _glfwInputError(GLFW_PLATFORM_ERROR,
   1877                                 "Wayland: Failed to create EGL window");
   1878                 return GLFW_FALSE;
   1879             }
   1880 
   1881             if (!_glfwInitEGL())
   1882                 return GLFW_FALSE;
   1883             if (!_glfwCreateContextEGL(window, ctxconfig, fbconfig))
   1884                 return GLFW_FALSE;
   1885         }
   1886         else if (ctxconfig->source == GLFW_OSMESA_CONTEXT_API)
   1887         {
   1888             if (!_glfwInitOSMesa())
   1889                 return GLFW_FALSE;
   1890             if (!_glfwCreateContextOSMesa(window, ctxconfig, fbconfig))
   1891                 return GLFW_FALSE;
   1892         }
   1893 
   1894         if (!_glfwRefreshContextAttribs(window, ctxconfig))
   1895             return GLFW_FALSE;
   1896     }
   1897 
   1898     if (window->monitor || wndconfig->visible)
   1899     {
   1900         if (!createShellObjects(window))
   1901             return GLFW_FALSE;
   1902     }
   1903 
   1904     return GLFW_TRUE;
   1905 }
   1906 
   1907 void _glfwPlatformDestroyWindow(_GLFWwindow* window)
   1908 {
   1909     if (window == _glfw.wl.pointerFocus)
   1910     {
   1911         _glfw.wl.pointerFocus = NULL;
   1912         _glfwInputCursorEnter(window, GLFW_FALSE);
   1913     }
   1914     if (window == _glfw.wl.keyboardFocus)
   1915     {
   1916         _glfw.wl.keyboardFocus = NULL;
   1917         _glfwInputWindowFocus(window, GLFW_FALSE);
   1918     }
   1919 
   1920     if (window->wl.idleInhibitor)
   1921         zwp_idle_inhibitor_v1_destroy(window->wl.idleInhibitor);
   1922 
   1923     if (window->context.destroy)
   1924         window->context.destroy(window);
   1925 
   1926     destroyShellObjects(window);
   1927 
   1928     if (window->wl.decorations.buffer)
   1929         wl_buffer_destroy(window->wl.decorations.buffer);
   1930 
   1931     if (window->wl.egl.window)
   1932         wl_egl_window_destroy(window->wl.egl.window);
   1933 
   1934     if (window->wl.surface)
   1935         wl_surface_destroy(window->wl.surface);
   1936 
   1937     free(window->wl.title);
   1938     free(window->wl.monitors);
   1939 }
   1940 
   1941 void _glfwPlatformSetWindowTitle(_GLFWwindow* window, const char* title)
   1942 {
   1943     if (window->wl.title)
   1944         free(window->wl.title);
   1945     window->wl.title = _glfw_strdup(title);
   1946     if (window->wl.xdg.toplevel)
   1947         xdg_toplevel_set_title(window->wl.xdg.toplevel, title);
   1948 }
   1949 
   1950 void _glfwPlatformSetWindowIcon(_GLFWwindow* window,
   1951                                 int count, const GLFWimage* images)
   1952 {
   1953     _glfwInputError(GLFW_PLATFORM_ERROR,
   1954                     "Wayland: Setting window icon not supported");
   1955 }
   1956 
   1957 void _glfwPlatformGetWindowPos(_GLFWwindow* window, int* xpos, int* ypos)
   1958 {
   1959     // A Wayland client is not aware of its position, so just warn and leave it
   1960     // as (0, 0)
   1961 
   1962     _glfwInputError(GLFW_PLATFORM_ERROR,
   1963                     "Wayland: Window position retrieval not supported");
   1964 }
   1965 
   1966 void _glfwPlatformSetWindowPos(_GLFWwindow* window, int xpos, int ypos)
   1967 {
   1968     // A Wayland client can not set its position, so just warn
   1969 
   1970     _glfwInputError(GLFW_PLATFORM_ERROR,
   1971                     "Wayland: Window position setting not supported");
   1972 }
   1973 
   1974 void _glfwPlatformGetWindowSize(_GLFWwindow* window, int* width, int* height)
   1975 {
   1976     if (width)
   1977         *width = window->wl.width;
   1978     if (height)
   1979         *height = window->wl.height;
   1980 }
   1981 
   1982 void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
   1983 {
   1984     if (window->monitor)
   1985     {
   1986         // Video mode setting is not available on Wayland
   1987     }
   1988     else
   1989     {
   1990         window->wl.width = width;
   1991         window->wl.height = height;
   1992         resizeWindow(window);
   1993     }
   1994 }
   1995 
   1996 void _glfwPlatformSetWindowSizeLimits(_GLFWwindow* window,
   1997                                       int minwidth, int minheight,
   1998                                       int maxwidth, int maxheight)
   1999 {
   2000     if (window->wl.xdg.toplevel)
   2001     {
   2002         if (minwidth == GLFW_DONT_CARE || minheight == GLFW_DONT_CARE)
   2003             minwidth = minheight = 0;
   2004         else
   2005         {
   2006             if (window->wl.decorations.top.surface)
   2007             {
   2008                 minwidth  += GLFW_BORDER_SIZE * 2;
   2009                 minheight += GLFW_CAPTION_HEIGHT + GLFW_BORDER_SIZE;
   2010             }
   2011         }
   2012 
   2013         if (maxwidth == GLFW_DONT_CARE || maxheight == GLFW_DONT_CARE)
   2014             maxwidth = maxheight = 0;
   2015         else
   2016         {
   2017             if (window->wl.decorations.top.surface)
   2018             {
   2019                 maxwidth  += GLFW_BORDER_SIZE * 2;
   2020                 maxheight += GLFW_CAPTION_HEIGHT + GLFW_BORDER_SIZE;
   2021             }
   2022         }
   2023 
   2024         xdg_toplevel_set_min_size(window->wl.xdg.toplevel, minwidth, minheight);
   2025         xdg_toplevel_set_max_size(window->wl.xdg.toplevel, maxwidth, maxheight);
   2026         wl_surface_commit(window->wl.surface);
   2027     }
   2028 }
   2029 
   2030 void _glfwPlatformSetWindowAspectRatio(_GLFWwindow* window,
   2031                                        int numer, int denom)
   2032 {
   2033     if (window->wl.maximized || window->wl.fullscreen)
   2034         return;
   2035 
   2036     if (numer != GLFW_DONT_CARE && denom != GLFW_DONT_CARE)
   2037     {
   2038         const float aspectRatio = (float) window->wl.width / (float) window->wl.height;
   2039         const float targetRatio = (float) numer / (float) denom;
   2040         if (aspectRatio < targetRatio)
   2041             window->wl.height = window->wl.width / targetRatio;
   2042         else if (aspectRatio > targetRatio)
   2043             window->wl.width = window->wl.height * targetRatio;
   2044 
   2045         resizeWindow(window);
   2046     }
   2047 }
   2048 
   2049 void _glfwPlatformGetFramebufferSize(_GLFWwindow* window,
   2050                                      int* width, int* height)
   2051 {
   2052     _glfwPlatformGetWindowSize(window, width, height);
   2053     if (width)
   2054         *width *= window->wl.scale;
   2055     if (height)
   2056         *height *= window->wl.scale;
   2057 }
   2058 
   2059 void _glfwPlatformGetWindowFrameSize(_GLFWwindow* window,
   2060                                      int* left, int* top,
   2061                                      int* right, int* bottom)
   2062 {
   2063     if (window->decorated && !window->monitor && window->wl.decorations.top.surface)
   2064     {
   2065         if (top)
   2066             *top = GLFW_CAPTION_HEIGHT;
   2067         if (left)
   2068             *left = GLFW_BORDER_SIZE;
   2069         if (right)
   2070             *right = GLFW_BORDER_SIZE;
   2071         if (bottom)
   2072             *bottom = GLFW_BORDER_SIZE;
   2073     }
   2074 }
   2075 
   2076 void _glfwPlatformGetWindowContentScale(_GLFWwindow* window,
   2077                                         float* xscale, float* yscale)
   2078 {
   2079     if (xscale)
   2080         *xscale = (float) window->wl.scale;
   2081     if (yscale)
   2082         *yscale = (float) window->wl.scale;
   2083 }
   2084 
   2085 void _glfwPlatformIconifyWindow(_GLFWwindow* window)
   2086 {
   2087     if (window->wl.xdg.toplevel)
   2088         xdg_toplevel_set_minimized(window->wl.xdg.toplevel);
   2089 }
   2090 
   2091 void _glfwPlatformRestoreWindow(_GLFWwindow* window)
   2092 {
   2093     if (window->monitor)
   2094     {
   2095         // There is no way to unset minimized, or even to know if we are
   2096         // minimized, so there is nothing to do here.
   2097     }
   2098     else
   2099     {
   2100         // We assume we are not minimized and act only on maximization
   2101 
   2102         if (window->wl.maximized)
   2103         {
   2104             if (window->wl.xdg.toplevel)
   2105                 xdg_toplevel_unset_maximized(window->wl.xdg.toplevel);
   2106             else
   2107                 window->wl.maximized = GLFW_FALSE;
   2108         }
   2109     }
   2110 }
   2111 
   2112 void _glfwPlatformMaximizeWindow(_GLFWwindow* window)
   2113 {
   2114     if (window->wl.xdg.toplevel)
   2115         xdg_toplevel_set_maximized(window->wl.xdg.toplevel);
   2116     else
   2117         window->wl.maximized = GLFW_TRUE;
   2118 }
   2119 
   2120 void _glfwPlatformShowWindow(_GLFWwindow* window)
   2121 {
   2122     if (!window->wl.xdg.toplevel)
   2123     {
   2124         // NOTE: The XDG/shell surface is created here so command-line applications
   2125         //       with off-screen windows do not appear in for example the Unity dock
   2126         createShellObjects(window);
   2127     }
   2128 }
   2129 
   2130 void _glfwPlatformHideWindow(_GLFWwindow* window)
   2131 {
   2132     if (window->wl.visible)
   2133     {
   2134         window->wl.visible = GLFW_FALSE;
   2135         destroyShellObjects(window);
   2136 
   2137         wl_surface_attach(window->wl.surface, NULL, 0, 0);
   2138         wl_surface_commit(window->wl.surface);
   2139     }
   2140 }
   2141 
   2142 void _glfwPlatformRequestWindowAttention(_GLFWwindow* window)
   2143 {
   2144     // TODO
   2145     _glfwInputError(GLFW_PLATFORM_ERROR,
   2146                     "Wayland: Window attention request not implemented yet");
   2147 }
   2148 
   2149 void _glfwPlatformFocusWindow(_GLFWwindow* window)
   2150 {
   2151     _glfwInputError(GLFW_PLATFORM_ERROR,
   2152                     "Wayland: Focusing a window requires user interaction");
   2153 }
   2154 
   2155 void _glfwPlatformSetWindowMonitor(_GLFWwindow* window,
   2156                                    _GLFWmonitor* monitor,
   2157                                    int xpos, int ypos,
   2158                                    int width, int height,
   2159                                    int refreshRate)
   2160 {
   2161     if (window->monitor == monitor)
   2162     {
   2163         if (!monitor)
   2164             _glfwPlatformSetWindowSize(window, width, height);
   2165 
   2166         return;
   2167     }
   2168 
   2169     if (window->monitor)
   2170         releaseMonitor(window);
   2171 
   2172     _glfwInputWindowMonitor(window, monitor);
   2173 
   2174     if (window->monitor)
   2175         acquireMonitor(window);
   2176     else
   2177         _glfwPlatformSetWindowSize(window, width, height);
   2178 }
   2179 
   2180 int _glfwPlatformWindowFocused(_GLFWwindow* window)
   2181 {
   2182     return _glfw.wl.keyboardFocus == window;
   2183 }
   2184 
   2185 int _glfwPlatformWindowIconified(_GLFWwindow* window)
   2186 {
   2187     // xdg-shell doesn’t give any way to request whether a surface is iconified
   2188     return GLFW_FALSE;
   2189 }
   2190 
   2191 int _glfwPlatformWindowVisible(_GLFWwindow* window)
   2192 {
   2193     return window->wl.visible;
   2194 }
   2195 
   2196 int _glfwPlatformWindowMaximized(_GLFWwindow* window)
   2197 {
   2198     return window->wl.maximized;
   2199 }
   2200 
   2201 int _glfwPlatformWindowHovered(_GLFWwindow* window)
   2202 {
   2203     return window->wl.hovered;
   2204 }
   2205 
   2206 int _glfwPlatformFramebufferTransparent(_GLFWwindow* window)
   2207 {
   2208     return window->wl.transparent;
   2209 }
   2210 
   2211 void _glfwPlatformSetWindowResizable(_GLFWwindow* window, GLFWbool enabled)
   2212 {
   2213     // TODO
   2214     _glfwInputError(GLFW_PLATFORM_ERROR,
   2215                     "Wayland: Window attribute setting not implemented yet");
   2216 }
   2217 
   2218 void _glfwPlatformSetWindowDecorated(_GLFWwindow* window, GLFWbool enabled)
   2219 {
   2220     if (window->wl.xdg.decoration)
   2221     {
   2222         uint32_t mode;
   2223 
   2224         if (enabled)
   2225             mode = ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE;
   2226         else
   2227             mode = ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE;
   2228 
   2229         zxdg_toplevel_decoration_v1_set_mode(window->wl.xdg.decoration, mode);
   2230     }
   2231     else
   2232     {
   2233         if (enabled)
   2234             createFallbackDecorations(window);
   2235         else
   2236             destroyFallbackDecorations(window);
   2237     }
   2238 }
   2239 
   2240 void _glfwPlatformSetWindowFloating(_GLFWwindow* window, GLFWbool enabled)
   2241 {
   2242     // TODO
   2243     _glfwInputError(GLFW_PLATFORM_ERROR,
   2244                     "Wayland: Window attribute setting not implemented yet");
   2245 }
   2246 
   2247 float _glfwPlatformGetWindowOpacity(_GLFWwindow* window)
   2248 {
   2249     return 1.f;
   2250 }
   2251 
   2252 void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity)
   2253 {
   2254 }
   2255 
   2256 void _glfwPlatformSetRawMouseMotion(_GLFWwindow* window, GLFWbool enabled)
   2257 {
   2258     // This is handled in relativePointerHandleRelativeMotion
   2259 }
   2260 
   2261 GLFWbool _glfwPlatformRawMouseMotionSupported(void)
   2262 {
   2263     return GLFW_TRUE;
   2264 }
   2265 
   2266 void _glfwPlatformPollEvents(void)
   2267 {
   2268     double timeout = 0.0;
   2269     handleEvents(&timeout);
   2270 }
   2271 
   2272 void _glfwPlatformWaitEvents(void)
   2273 {
   2274     handleEvents(NULL);
   2275 }
   2276 
   2277 void _glfwPlatformWaitEventsTimeout(double timeout)
   2278 {
   2279     handleEvents(&timeout);
   2280 }
   2281 
   2282 void _glfwPlatformPostEmptyEvent(void)
   2283 {
   2284     wl_display_sync(_glfw.wl.display);
   2285     flushDisplay();
   2286 }
   2287 
   2288 void _glfwPlatformGetCursorPos(_GLFWwindow* window, double* xpos, double* ypos)
   2289 {
   2290     if (xpos)
   2291         *xpos = window->wl.cursorPosX;
   2292     if (ypos)
   2293         *ypos = window->wl.cursorPosY;
   2294 }
   2295 
   2296 static GLFWbool isPointerLocked(_GLFWwindow* window);
   2297 
   2298 void _glfwPlatformSetCursorPos(_GLFWwindow* window, double x, double y)
   2299 {
   2300     if (isPointerLocked(window))
   2301     {
   2302         zwp_locked_pointer_v1_set_cursor_position_hint(
   2303             window->wl.pointerLock.lockedPointer,
   2304             wl_fixed_from_double(x), wl_fixed_from_double(y));
   2305     }
   2306 }
   2307 
   2308 void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode)
   2309 {
   2310     _glfwPlatformSetCursor(window, window->wl.currentCursor);
   2311 }
   2312 
   2313 const char* _glfwPlatformGetScancodeName(int scancode)
   2314 {
   2315     if (scancode < 0 || scancode > 255 ||
   2316         _glfw.wl.keycodes[scancode] == GLFW_KEY_UNKNOWN)
   2317     {
   2318         _glfwInputError(GLFW_INVALID_VALUE,
   2319                         "Wayland: Invalid scancode %i",
   2320                         scancode);
   2321         return NULL;
   2322     }
   2323 
   2324     const int key = _glfw.wl.keycodes[scancode];
   2325     const xkb_keycode_t keycode = scancode + 8;
   2326     const xkb_layout_index_t layout =
   2327         xkb_state_key_get_layout(_glfw.wl.xkb.state, keycode);
   2328     if (layout == XKB_LAYOUT_INVALID)
   2329     {
   2330         _glfwInputError(GLFW_PLATFORM_ERROR,
   2331                         "Wayland: Failed to retrieve layout for key name");
   2332         return NULL;
   2333     }
   2334 
   2335     const xkb_keysym_t* keysyms = NULL;
   2336     xkb_keymap_key_get_syms_by_level(_glfw.wl.xkb.keymap,
   2337                                      keycode,
   2338                                      layout,
   2339                                      0,
   2340                                      &keysyms);
   2341     if (keysyms == NULL)
   2342     {
   2343         _glfwInputError(GLFW_PLATFORM_ERROR,
   2344                         "Wayland: Failed to retrieve keysym for key name");
   2345         return NULL;
   2346     }
   2347 
   2348     const uint32_t codepoint = _glfwKeySym2Unicode(keysyms[0]);
   2349     if (codepoint == GLFW_INVALID_CODEPOINT)
   2350     {
   2351         _glfwInputError(GLFW_PLATFORM_ERROR,
   2352                         "Wayland: Failed to retrieve codepoint for key name");
   2353         return NULL;
   2354     }
   2355 
   2356     const size_t count = _glfwEncodeUTF8(_glfw.wl.keynames[key],  codepoint);
   2357     if (count == 0)
   2358     {
   2359         _glfwInputError(GLFW_PLATFORM_ERROR,
   2360                         "Wayland: Failed to encode codepoint for key name");
   2361         return NULL;
   2362     }
   2363 
   2364     _glfw.wl.keynames[key][count] = '\0';
   2365     return _glfw.wl.keynames[key];
   2366 }
   2367 
   2368 int _glfwPlatformGetKeyScancode(int key)
   2369 {
   2370     return _glfw.wl.scancodes[key];
   2371 }
   2372 
   2373 int _glfwPlatformCreateCursor(_GLFWcursor* cursor,
   2374                               const GLFWimage* image,
   2375                               int xhot, int yhot)
   2376 {
   2377     cursor->wl.buffer = createShmBuffer(image);
   2378     if (!cursor->wl.buffer)
   2379         return GLFW_FALSE;
   2380 
   2381     cursor->wl.width = image->width;
   2382     cursor->wl.height = image->height;
   2383     cursor->wl.xhot = xhot;
   2384     cursor->wl.yhot = yhot;
   2385     return GLFW_TRUE;
   2386 }
   2387 
   2388 int _glfwPlatformCreateStandardCursor(_GLFWcursor* cursor, int shape)
   2389 {
   2390     struct wl_cursor* standardCursor;
   2391 
   2392     standardCursor = wl_cursor_theme_get_cursor(_glfw.wl.cursorTheme,
   2393                                                 translateCursorShape(shape));
   2394     if (!standardCursor)
   2395     {
   2396         _glfwInputError(GLFW_PLATFORM_ERROR,
   2397                         "Wayland: Standard cursor \"%s\" not found",
   2398                         translateCursorShape(shape));
   2399         return GLFW_FALSE;
   2400     }
   2401 
   2402     cursor->wl.cursor = standardCursor;
   2403     cursor->wl.currentImage = 0;
   2404 
   2405     if (_glfw.wl.cursorThemeHiDPI)
   2406     {
   2407         standardCursor = wl_cursor_theme_get_cursor(_glfw.wl.cursorThemeHiDPI,
   2408                                                     translateCursorShape(shape));
   2409         cursor->wl.cursorHiDPI = standardCursor;
   2410     }
   2411 
   2412     return GLFW_TRUE;
   2413 }
   2414 
   2415 void _glfwPlatformDestroyCursor(_GLFWcursor* cursor)
   2416 {
   2417     // If it's a standard cursor we don't need to do anything here
   2418     if (cursor->wl.cursor)
   2419         return;
   2420 
   2421     if (cursor->wl.buffer)
   2422         wl_buffer_destroy(cursor->wl.buffer);
   2423 }
   2424 
   2425 static void relativePointerHandleRelativeMotion(void* userData,
   2426                                                 struct zwp_relative_pointer_v1* pointer,
   2427                                                 uint32_t timeHi,
   2428                                                 uint32_t timeLo,
   2429                                                 wl_fixed_t dx,
   2430                                                 wl_fixed_t dy,
   2431                                                 wl_fixed_t dxUnaccel,
   2432                                                 wl_fixed_t dyUnaccel)
   2433 {
   2434     _GLFWwindow* window = userData;
   2435     double xpos = window->virtualCursorPosX;
   2436     double ypos = window->virtualCursorPosY;
   2437 
   2438     if (window->cursorMode != GLFW_CURSOR_DISABLED)
   2439         return;
   2440 
   2441     if (window->rawMouseMotion)
   2442     {
   2443         xpos += wl_fixed_to_double(dxUnaccel);
   2444         ypos += wl_fixed_to_double(dyUnaccel);
   2445     }
   2446     else
   2447     {
   2448         xpos += wl_fixed_to_double(dx);
   2449         ypos += wl_fixed_to_double(dy);
   2450     }
   2451 
   2452     _glfwInputCursorPos(window, xpos, ypos);
   2453 }
   2454 
   2455 static const struct zwp_relative_pointer_v1_listener relativePointerListener =
   2456 {
   2457     relativePointerHandleRelativeMotion
   2458 };
   2459 
   2460 static void lockedPointerHandleLocked(void* userData,
   2461                                       struct zwp_locked_pointer_v1* lockedPointer)
   2462 {
   2463 }
   2464 
   2465 static void unlockPointer(_GLFWwindow* window)
   2466 {
   2467     struct zwp_relative_pointer_v1* relativePointer =
   2468         window->wl.pointerLock.relativePointer;
   2469     struct zwp_locked_pointer_v1* lockedPointer =
   2470         window->wl.pointerLock.lockedPointer;
   2471 
   2472     zwp_relative_pointer_v1_destroy(relativePointer);
   2473     zwp_locked_pointer_v1_destroy(lockedPointer);
   2474 
   2475     window->wl.pointerLock.relativePointer = NULL;
   2476     window->wl.pointerLock.lockedPointer = NULL;
   2477 }
   2478 
   2479 static void lockPointer(_GLFWwindow* window);
   2480 
   2481 static void lockedPointerHandleUnlocked(void* userData,
   2482                                         struct zwp_locked_pointer_v1* lockedPointer)
   2483 {
   2484 }
   2485 
   2486 static const struct zwp_locked_pointer_v1_listener lockedPointerListener =
   2487 {
   2488     lockedPointerHandleLocked,
   2489     lockedPointerHandleUnlocked
   2490 };
   2491 
   2492 static void lockPointer(_GLFWwindow* window)
   2493 {
   2494     struct zwp_relative_pointer_v1* relativePointer;
   2495     struct zwp_locked_pointer_v1* lockedPointer;
   2496 
   2497     if (!_glfw.wl.relativePointerManager)
   2498     {
   2499         _glfwInputError(GLFW_PLATFORM_ERROR,
   2500                         "Wayland: no relative pointer manager");
   2501         return;
   2502     }
   2503 
   2504     relativePointer =
   2505         zwp_relative_pointer_manager_v1_get_relative_pointer(
   2506             _glfw.wl.relativePointerManager,
   2507             _glfw.wl.pointer);
   2508     zwp_relative_pointer_v1_add_listener(relativePointer,
   2509                                          &relativePointerListener,
   2510                                          window);
   2511 
   2512     lockedPointer =
   2513         zwp_pointer_constraints_v1_lock_pointer(
   2514             _glfw.wl.pointerConstraints,
   2515             window->wl.surface,
   2516             _glfw.wl.pointer,
   2517             NULL,
   2518             ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);
   2519     zwp_locked_pointer_v1_add_listener(lockedPointer,
   2520                                        &lockedPointerListener,
   2521                                        window);
   2522 
   2523     window->wl.pointerLock.relativePointer = relativePointer;
   2524     window->wl.pointerLock.lockedPointer = lockedPointer;
   2525 
   2526     wl_pointer_set_cursor(_glfw.wl.pointer, _glfw.wl.pointerEnterSerial,
   2527                           NULL, 0, 0);
   2528 }
   2529 
   2530 static GLFWbool isPointerLocked(_GLFWwindow* window)
   2531 {
   2532     return window->wl.pointerLock.lockedPointer != NULL;
   2533 }
   2534 
   2535 void _glfwPlatformSetCursor(_GLFWwindow* window, _GLFWcursor* cursor)
   2536 {
   2537     struct wl_cursor* defaultCursor;
   2538     struct wl_cursor* defaultCursorHiDPI = NULL;
   2539 
   2540     if (!_glfw.wl.pointer)
   2541         return;
   2542 
   2543     window->wl.currentCursor = cursor;
   2544 
   2545     // If we're not in the correct window just save the cursor
   2546     // the next time the pointer enters the window the cursor will change
   2547     if (window != _glfw.wl.pointerFocus || window->wl.decorations.focus != mainWindow)
   2548         return;
   2549 
   2550     // Unlock possible pointer lock if no longer disabled.
   2551     if (window->cursorMode != GLFW_CURSOR_DISABLED && isPointerLocked(window))
   2552         unlockPointer(window);
   2553 
   2554     if (window->cursorMode == GLFW_CURSOR_NORMAL)
   2555     {
   2556         if (cursor)
   2557             setCursorImage(window, &cursor->wl);
   2558         else
   2559         {
   2560             defaultCursor = wl_cursor_theme_get_cursor(_glfw.wl.cursorTheme,
   2561                                                        "left_ptr");
   2562             if (!defaultCursor)
   2563             {
   2564                 _glfwInputError(GLFW_PLATFORM_ERROR,
   2565                                 "Wayland: Standard cursor not found");
   2566                 return;
   2567             }
   2568             if (_glfw.wl.cursorThemeHiDPI)
   2569                 defaultCursorHiDPI =
   2570                     wl_cursor_theme_get_cursor(_glfw.wl.cursorThemeHiDPI,
   2571                                                "left_ptr");
   2572             _GLFWcursorWayland cursorWayland = {
   2573                 defaultCursor,
   2574                 defaultCursorHiDPI,
   2575                 NULL,
   2576                 0, 0,
   2577                 0, 0,
   2578                 0
   2579             };
   2580             setCursorImage(window, &cursorWayland);
   2581         }
   2582     }
   2583     else if (window->cursorMode == GLFW_CURSOR_DISABLED)
   2584     {
   2585         if (!isPointerLocked(window))
   2586             lockPointer(window);
   2587     }
   2588     else if (window->cursorMode == GLFW_CURSOR_HIDDEN)
   2589     {
   2590         wl_pointer_set_cursor(_glfw.wl.pointer, _glfw.wl.pointerEnterSerial, NULL, 0, 0);
   2591     }
   2592 }
   2593 
   2594 static void dataSourceHandleTarget(void* userData,
   2595                                    struct wl_data_source* source,
   2596                                    const char* mimeType)
   2597 {
   2598     if (_glfw.wl.selectionSource != source)
   2599     {
   2600         _glfwInputError(GLFW_PLATFORM_ERROR,
   2601                         "Wayland: Unknown clipboard data source");
   2602         return;
   2603     }
   2604 }
   2605 
   2606 static void dataSourceHandleSend(void* userData,
   2607                                  struct wl_data_source* source,
   2608                                  const char* mimeType,
   2609                                  int fd)
   2610 {
   2611     // Ignore it if this is an outdated or invalid request
   2612     if (_glfw.wl.selectionSource != source ||
   2613         strcmp(mimeType, "text/plain;charset=utf-8") != 0)
   2614     {
   2615         close(fd);
   2616         return;
   2617     }
   2618 
   2619     char* string = _glfw.wl.clipboardString;
   2620     size_t length = strlen(string);
   2621 
   2622     while (length > 0)
   2623     {
   2624         const ssize_t result = write(fd, string, length);
   2625         if (result == -1)
   2626         {
   2627             if (errno == EINTR)
   2628                 continue;
   2629 
   2630             _glfwInputError(GLFW_PLATFORM_ERROR,
   2631                             "Wayland: Error while writing the clipboard: %s",
   2632                             strerror(errno));
   2633             break;
   2634         }
   2635 
   2636         length -= result;
   2637         string += result;
   2638     }
   2639 
   2640     close(fd);
   2641 }
   2642 
   2643 static void dataSourceHandleCancelled(void* userData,
   2644                                       struct wl_data_source* source)
   2645 {
   2646     wl_data_source_destroy(source);
   2647 
   2648     if (_glfw.wl.selectionSource != source)
   2649         return;
   2650 
   2651     _glfw.wl.selectionSource = NULL;
   2652 }
   2653 
   2654 static const struct wl_data_source_listener dataSourceListener =
   2655 {
   2656     dataSourceHandleTarget,
   2657     dataSourceHandleSend,
   2658     dataSourceHandleCancelled,
   2659 };
   2660 
   2661 void _glfwPlatformSetClipboardString(const char* string)
   2662 {
   2663     if (_glfw.wl.selectionSource)
   2664     {
   2665         wl_data_source_destroy(_glfw.wl.selectionSource);
   2666         _glfw.wl.selectionSource = NULL;
   2667     }
   2668 
   2669     char* copy = _glfw_strdup(string);
   2670     if (!copy)
   2671     {
   2672         _glfwInputError(GLFW_OUT_OF_MEMORY, NULL);
   2673         return;
   2674     }
   2675 
   2676     free(_glfw.wl.clipboardString);
   2677     _glfw.wl.clipboardString = copy;
   2678 
   2679     _glfw.wl.selectionSource =
   2680         wl_data_device_manager_create_data_source(_glfw.wl.dataDeviceManager);
   2681     if (!_glfw.wl.selectionSource)
   2682     {
   2683         _glfwInputError(GLFW_PLATFORM_ERROR,
   2684                         "Wayland: Failed to create clipboard data source");
   2685         return;
   2686     }
   2687     wl_data_source_add_listener(_glfw.wl.selectionSource,
   2688                                 &dataSourceListener,
   2689                                 NULL);
   2690     wl_data_source_offer(_glfw.wl.selectionSource, "text/plain;charset=utf-8");
   2691     wl_data_device_set_selection(_glfw.wl.dataDevice,
   2692                                  _glfw.wl.selectionSource,
   2693                                  _glfw.wl.serial);
   2694 }
   2695 
   2696 const char* _glfwPlatformGetClipboardString(void)
   2697 {
   2698     if (!_glfw.wl.selectionOffer)
   2699     {
   2700         _glfwInputError(GLFW_FORMAT_UNAVAILABLE,
   2701                         "Wayland: No clipboard data available");
   2702         return NULL;
   2703     }
   2704 
   2705     if (_glfw.wl.selectionSource)
   2706         return _glfw.wl.clipboardString;
   2707 
   2708     free(_glfw.wl.clipboardString);
   2709     _glfw.wl.clipboardString =
   2710         readDataOfferAsString(_glfw.wl.selectionOffer, "text/plain;charset=utf-8");
   2711     return _glfw.wl.clipboardString;
   2712 }
   2713 
   2714 void _glfwPlatformGetRequiredInstanceExtensions(char** extensions)
   2715 {
   2716     if (!_glfw.vk.KHR_surface || !_glfw.vk.KHR_wayland_surface)
   2717         return;
   2718 
   2719     extensions[0] = "VK_KHR_surface";
   2720     extensions[1] = "VK_KHR_wayland_surface";
   2721 }
   2722 
   2723 int _glfwPlatformGetPhysicalDevicePresentationSupport(VkInstance instance,
   2724                                                       VkPhysicalDevice device,
   2725                                                       uint32_t queuefamily)
   2726 {
   2727     PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR
   2728         vkGetPhysicalDeviceWaylandPresentationSupportKHR =
   2729         (PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR)
   2730         vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceWaylandPresentationSupportKHR");
   2731     if (!vkGetPhysicalDeviceWaylandPresentationSupportKHR)
   2732     {
   2733         _glfwInputError(GLFW_API_UNAVAILABLE,
   2734                         "Wayland: Vulkan instance missing VK_KHR_wayland_surface extension");
   2735         return VK_NULL_HANDLE;
   2736     }
   2737 
   2738     return vkGetPhysicalDeviceWaylandPresentationSupportKHR(device,
   2739                                                             queuefamily,
   2740                                                             _glfw.wl.display);
   2741 }
   2742 
   2743 VkResult _glfwPlatformCreateWindowSurface(VkInstance instance,
   2744                                           _GLFWwindow* window,
   2745                                           const VkAllocationCallbacks* allocator,
   2746                                           VkSurfaceKHR* surface)
   2747 {
   2748     VkResult err;
   2749     VkWaylandSurfaceCreateInfoKHR sci;
   2750     PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR;
   2751 
   2752     vkCreateWaylandSurfaceKHR = (PFN_vkCreateWaylandSurfaceKHR)
   2753         vkGetInstanceProcAddr(instance, "vkCreateWaylandSurfaceKHR");
   2754     if (!vkCreateWaylandSurfaceKHR)
   2755     {
   2756         _glfwInputError(GLFW_API_UNAVAILABLE,
   2757                         "Wayland: Vulkan instance missing VK_KHR_wayland_surface extension");
   2758         return VK_ERROR_EXTENSION_NOT_PRESENT;
   2759     }
   2760 
   2761     memset(&sci, 0, sizeof(sci));
   2762     sci.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
   2763     sci.display = _glfw.wl.display;
   2764     sci.surface = window->wl.surface;
   2765 
   2766     err = vkCreateWaylandSurfaceKHR(instance, &sci, allocator, surface);
   2767     if (err)
   2768     {
   2769         _glfwInputError(GLFW_PLATFORM_ERROR,
   2770                         "Wayland: Failed to create Vulkan surface: %s",
   2771                         _glfwGetVulkanResultString(err));
   2772     }
   2773 
   2774     return err;
   2775 }
   2776 
   2777 
   2778 //////////////////////////////////////////////////////////////////////////
   2779 //////                        GLFW native API                       //////
   2780 //////////////////////////////////////////////////////////////////////////
   2781 
   2782 GLFWAPI struct wl_display* glfwGetWaylandDisplay(void)
   2783 {
   2784     _GLFW_REQUIRE_INIT_OR_RETURN(NULL);
   2785     return _glfw.wl.display;
   2786 }
   2787 
   2788 GLFWAPI struct wl_surface* glfwGetWaylandWindow(GLFWwindow* handle)
   2789 {
   2790     _GLFWwindow* window = (_GLFWwindow*) handle;
   2791     _GLFW_REQUIRE_INIT_OR_RETURN(NULL);
   2792     return window->wl.surface;
   2793 }
   2794