chore: import official kitty sources from upstream

Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty,
vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
BlackAngelTV committed 2026-11-04 11:20:47 +01:00
commit 7e7d249099
1134 files changed
+433629

No files matched your search

+468
View File
@@ -0,0 +1,468 @@
/*
* backend_utils.c
* Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#define _GNU_SOURCE
#include "backend_utils.h"
#include "internal.h"
#include "memfd.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <stdio.h>
#include <sys/mman.h>
#ifdef __NetBSD__
#define ppoll pollts
#endif
void
update_fds(EventLoopData *eld) {
for (nfds_t i = 0; i < eld->watches_count; i++) {
Watch *w = eld->watches + i;
eld->fds[i].fd = w->fd;
eld->fds[i].events = w->enabled ? w->events : 0;
}
}
id_type
addWatch(EventLoopData *eld, const char *name, int fd, int events, int enabled, watch_callback_func cb, void *cb_data) {
if (eld->watches_count >= sizeof(eld->watches) / sizeof(eld->watches[0])) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Too many watches added");
return 0;
}
static id_type watch_counter = 0;
Watch *w = eld->watches + eld->watches_count++;
w->name = name;
w->fd = fd;
w->events = events;
w->enabled = enabled;
w->callback = cb;
w->callback_data = cb_data;
w->free = NULL;
w->id = ++watch_counter;
update_fds(eld);
return w->id;
}
#define removeX(which, item_id, update_func) \
{ \
for (nfds_t i = 0; i < eld->which##_count; i++) { \
if (eld->which[i].id == item_id) { \
eld->which##_count--; \
if (eld->which[i].callback_data && eld->which[i].free) { \
eld->which[i].free(eld->which[i].id, eld->which[i].callback_data); \
eld->which[i].callback_data = NULL; \
eld->which[i].free = NULL; \
} \
if (i < eld->which##_count) { memmove(eld->which + i, eld->which + i + 1, sizeof(eld->which[0]) * (eld->which##_count - i)); } \
update_func(eld); \
break; \
} \
} \
}
void
removeWatch(EventLoopData *eld, id_type watch_id) {
removeX(watches, watch_id, update_fds);
}
void
toggleWatch(EventLoopData *eld, id_type watch_id, int enabled) {
for (nfds_t i = 0; i < eld->watches_count; i++) {
if (eld->watches[i].id == watch_id) {
if (eld->watches[i].enabled != enabled) {
eld->watches[i].enabled = enabled;
update_fds(eld);
}
break;
}
}
}
static id_type timer_counter = 0;
static int
compare_timers(const void *a_, const void *b_) {
const Timer *a = (const Timer *)a_, *b = (const Timer *)b_;
return (a->trigger_at > b->trigger_at) ? 1 : (a->trigger_at < b->trigger_at) ? -1 : 0;
}
static void
update_timers(EventLoopData *eld) {
if (eld->timers_count > 1) qsort(eld->timers, eld->timers_count, sizeof(eld->timers[0]), compare_timers);
}
id_type
addTimer(
EventLoopData *eld, const char *name, monotonic_t interval, int enabled, bool repeats, timer_callback_func cb, void *cb_data, GLFWuserdatafreefun free) {
if (eld->timers_count >= sizeof(eld->timers) / sizeof(eld->timers[0])) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Too many timers added");
return 0;
}
Timer *t = eld->timers + eld->timers_count++;
t->interval = interval;
t->name = name;
t->trigger_at = enabled ? monotonic() + interval : MONOTONIC_T_MAX;
t->repeats = repeats;
t->callback = cb;
t->callback_data = cb_data;
t->free = free;
t->id = ++timer_counter;
update_timers(eld);
return timer_counter;
}
void
removeTimer(EventLoopData *eld, id_type timer_id) {
removeX(timers, timer_id, update_timers);
}
void
removeAllTimers(EventLoopData *eld) {
for (nfds_t i = 0; i < eld->timers_count; i++) {
if (eld->timers[i].free && eld->timers[i].callback_data) eld->timers[i].free(eld->timers[i].id, eld->timers[i].callback_data);
}
eld->timers_count = 0;
}
void
toggleTimer(EventLoopData *eld, id_type timer_id, int enabled) {
for (nfds_t i = 0; i < eld->timers_count; i++) {
if (eld->timers[i].id == timer_id) {
monotonic_t trigger_at = enabled ? (monotonic() + eld->timers[i].interval) : MONOTONIC_T_MAX;
if (trigger_at != eld->timers[i].trigger_at) {
eld->timers[i].trigger_at = trigger_at;
update_timers(eld);
}
break;
}
}
}
void
changeTimerInterval(EventLoopData *eld, id_type timer_id, monotonic_t interval) {
for (nfds_t i = 0; i < eld->timers_count; i++) {
if (eld->timers[i].id == timer_id) {
eld->timers[i].interval = interval;
break;
}
}
}
monotonic_t
prepareForPoll(EventLoopData *eld, monotonic_t timeout) {
for (nfds_t i = 0; i < eld->watches_count; i++) eld->fds[i].revents = 0;
if (!eld->timers_count || eld->timers[0].trigger_at == MONOTONIC_T_MAX) return timeout;
monotonic_t now = monotonic(), next_repeat_at = eld->timers[0].trigger_at;
if (timeout < 0 || now + timeout > next_repeat_at) { timeout = next_repeat_at <= now ? 0 : next_repeat_at - now; }
return timeout;
}
static struct timespec
calc_time(monotonic_t nsec) {
struct timespec result;
result.tv_sec = nsec / (1000LL * 1000LL * 1000LL);
result.tv_nsec = nsec % (1000LL * 1000LL * 1000LL);
return result;
}
int
pollWithTimeout(struct pollfd *fds, nfds_t nfds, monotonic_t timeout) {
struct timespec tv = calc_time(timeout);
return ppoll(fds, nfds, &tv, NULL);
}
static void
dispatchEvents(EventLoopData *eld) {
for (nfds_t i = 0; i < eld->watches_count; i++) {
Watch *ww = eld->watches + i;
struct pollfd *pfd = eld->fds + i;
if (pfd->revents & ww->events) {
ww->ready = 1;
if (ww->callback) ww->callback(ww->fd, pfd->revents, ww->callback_data);
} else ww->ready = 0;
}
}
unsigned
dispatchTimers(EventLoopData *eld) {
if (!eld->timers_count || eld->timers[0].trigger_at == MONOTONIC_T_MAX) return 0;
static struct {
timer_callback_func func;
id_type id;
void *data;
bool repeats;
} dispatches[sizeof(eld->timers) / sizeof(eld->timers[0])];
unsigned num_dispatches = 0;
monotonic_t now = monotonic();
for (nfds_t i = 0; i < eld->timers_count && eld->timers[i].trigger_at <= now; i++) {
eld->timers[i].trigger_at = now + eld->timers[i].interval;
dispatches[num_dispatches].func = eld->timers[i].callback;
dispatches[num_dispatches].id = eld->timers[i].id;
dispatches[num_dispatches].data = eld->timers[i].callback_data;
dispatches[num_dispatches].repeats = eld->timers[i].repeats;
num_dispatches++;
}
// we dispatch separately so that the callbacks can modify timers
for (unsigned i = 0; i < num_dispatches; i++) {
dispatches[i].func(dispatches[i].id, dispatches[i].data);
if (!dispatches[i].repeats) { removeTimer(eld, dispatches[i].id); }
}
if (num_dispatches) update_timers(eld);
return num_dispatches;
}
static void
drain_wakeup_fd(int fd, EventLoopData *eld) {
static char drain_buf[64];
eld->wakeup_data_read = false;
while (true) {
ssize_t ret = read(fd, drain_buf, sizeof(drain_buf));
if (ret < 0) {
if (errno == EINTR) continue;
break;
}
if (ret > 0) {
eld->wakeup_data_read = true;
continue;
}
break;
}
}
static void
mark_wakep_fd_ready(int fd UNUSED, int events UNUSED, void *data) {
((EventLoopData *)(data))->wakeup_fd_ready = true;
}
static void
mark_key_repeat_fd_ready(int fd UNUSED, int events UNUSED, void *data) {
((EventLoopData *)(data))->key_repeat_fd_ready = true;
}
bool
initPollData(EventLoopData *eld, int display_fd) {
if (!addWatch(eld, "display", display_fd, POLLIN, 1, NULL, NULL)) return false;
#ifdef HAS_EVENT_FD
eld->wakeupFd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (eld->wakeupFd == -1) return false;
const int wakeup_fd = eld->wakeupFd;
#else
if (pipe2(eld->wakeupFds, O_CLOEXEC | O_NONBLOCK) != 0) return false;
const int wakeup_fd = eld->wakeupFds[0];
#endif
if (!addWatch(eld, "wakeup", wakeup_fd, POLLIN, 1, mark_wakep_fd_ready, eld)) return false;
#ifdef HAS_TIMER_FD
eld->key_repeat_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
if (eld->key_repeat_fd < 0) return false;
const int key_repeat_fd = eld->key_repeat_fd;
#else
if (pipe2(eld->key_repeat_fds, O_CLOEXEC | O_NONBLOCK) != 0) return false;
const int key_repeat_fd = eld->key_repeat_fds[0];
#endif
#ifdef _GLFW_WAYLAND
if (!addWatch(eld, "key_repeat", key_repeat_fd, POLLIN, 1, mark_key_repeat_fd_ready, eld)) return false;
#else
(void)key_repeat_fd;
(void)mark_key_repeat_fd_ready;
#endif
return true;
}
void
check_for_wakeup_events(EventLoopData *eld) {
#ifdef HAS_EVENT_FD
int fd = eld->wakeupFd;
#else
int fd = eld->wakeupFds[0];
#endif
drain_wakeup_fd(fd, eld);
}
void
wakeupEventLoop(EventLoopData *eld) {
#ifdef HAS_EVENT_FD
static const uint64_t value = 1;
while (write(eld->wakeupFd, &value, sizeof value) < 0 && (errno == EINTR || errno == EAGAIN));
#else
while (write(eld->wakeupFds[1], "w", 1) < 0 && (errno == EINTR || errno == EAGAIN));
#endif
}
static void
closeFds(int *fds, size_t count) {
while (count--) {
if (*fds > 0) {
close(*fds);
*fds = -1;
}
fds++;
}
}
void
finalizePollData(EventLoopData *eld) {
(void)closeFds;
#ifdef HAS_EVENT_FD
close(eld->wakeupFd);
eld->wakeupFd = -1;
#else
closeFds(eld->wakeupFds, arraysz(eld->wakeupFds));
#endif
#ifdef HAS_TIMER_FD
close(eld->key_repeat_fd);
eld->key_repeat_fd = -1;
#else
closeFds(eld->key_repeat_fds, arraysz(eld->key_repeat_fds));
#endif
}
static int
display_fd_ready(EventLoopData *eld) {
// watches[0] is always the display fd. Errors count as ready: the display
// callback must complete the read rather than cancel it, so that a
// compositor disconnect is turned into a display error instead of a poll()
// that keeps returning immediately forever.
return eld->fds[0].revents & (POLLIN | POLLERR | POLLHUP | POLLNVAL);
}
int
pollForEvents(EventLoopData *eld, monotonic_t timeout, watch_callback_func display_callback) {
int read_ok = 0;
timeout = prepareForPoll(eld, timeout);
EVDBG("pollForEvents final timeout: %.3f", monotonic_t_to_s_double(timeout));
int result;
monotonic_t end_time = monotonic() + timeout;
eld->wakeup_fd_ready = false;
eld->key_repeat_fd_ready = false;
while (1) {
if (timeout >= 0) {
errno = 0;
result = pollWithTimeout(eld->fds, eld->watches_count, timeout);
int saved_errno = errno;
if (display_callback) display_callback(result, display_fd_ready(eld), NULL);
dispatchTimers(eld);
if (result > 0) {
dispatchEvents(eld);
read_ok = eld->watches[0].ready;
break;
}
timeout = end_time - monotonic();
if (timeout <= 0) break;
if (result < 0 && (saved_errno == EINTR || saved_errno == EAGAIN)) continue;
break;
} else {
errno = 0;
result = poll(eld->fds, eld->watches_count, -1);
int saved_errno = errno;
if (display_callback) display_callback(result, display_fd_ready(eld), NULL);
dispatchTimers(eld);
if (result > 0) {
dispatchEvents(eld);
read_ok = eld->watches[0].ready;
}
if (result < 0 && (saved_errno == EINTR || saved_errno == EAGAIN)) continue;
break;
}
}
return read_ok;
}
// Duplicate a UTF-8 encoded string
// but cut it so that it has at most max_length bytes plus the null byte.
// This does not take combining characters into account.
GLFWAPI char *
utf_8_strndup(const char *source, size_t max_length) {
if (!source) return NULL;
size_t length = strnlen(source, max_length);
if (length >= max_length) {
for (length = max_length; length > 0; length--) {
if ((source[length] & 0xC0) != 0x80) break;
}
}
char *result = malloc(length + 1);
memcpy(result, source, length);
result[length] = 0;
return result;
}
/*
* Create a new, unique, anonymous file of the given size, and
* return the file descriptor for it. The file descriptor is set
* CLOEXEC. The file is immediately suitable for mmap()'ing
* the given size at offset zero.
*
* The file should not have a permanent backing store like a disk,
* but may have if XDG_RUNTIME_DIR is not properly implemented in OS.
*
* The file name is deleted from the file system.
*
* The file is suitable for buffer sharing between processes by
* transmitting the file descriptor over Unix sockets using the
* SCM_RIGHTS methods.
*
* posix_fallocate() is used to guarantee that disk space is available
* for the file at the given size. If disk space is insufficient, errno
* is set to ENOSPC. If posix_fallocate() is not supported, program may
* receive SIGBUS on accessing mmap()'ed file contents instead.
*/
int
createAnonymousFile(off_t size) {
int ret, fd = -1, shm_anon = 0;
#ifdef HAS_MEMFD_CREATE
fd = glfw_memfd_create("glfw-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING);
if (fd < 0) return -1;
// We can add this seal before calling posix_fallocate(), as the file
// is currently zero-sized anyway.
//
// There is also no need to check for the return value, we couldn’t do
// anything with it anyway.
fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_SEAL);
#elif defined(SHM_ANON)
fd = shm_open(SHM_ANON, O_RDWR | O_CLOEXEC, 0600);
if (fd < 0) return -1;
shm_anon = 1;
#else
static const char template[] = "/glfw-shared-XXXXXX";
const char *path;
char *name;
path = getenv("XDG_RUNTIME_DIR");
if (!path) {
errno = ENOENT;
return -1;
}
name = calloc(strlen(path) + sizeof(template), 1);
strcpy(name, path);
strcat(name, template);
fd = createTmpfileCloexec(name);
free(name);
if (fd < 0) return -1;
#endif
// posix_fallocate does not work on SHM descriptors
ret = shm_anon ? ftruncate(fd, size) : posix_fallocate(fd, 0, size);
if (ret != 0) {
close(fd);
errno = ret;
return -1;
}
return fd;
}
+111
View File
@@ -0,0 +1,111 @@
//========================================================================
// GLFW 3.4
//------------------------------------------------------------------------
// Copyright (c) 2014 Kovid Goyal
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#pragma once
#include "../kitty/monotonic.h"
#include <poll.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/types.h>
#ifdef __has_include
#if __has_include(<sys/eventfd.h>)
#define HAS_EVENT_FD
#include <sys/eventfd.h>
#endif
#if __has_include(<sys/timerfd.h>)
#define HAS_TIMER_FD
#include <sys/timerfd.h>
#endif
#else
#define HAS_EVENT_FD
#include <sys/eventfd.h>
#endif
typedef unsigned long long id_type;
typedef void (*watch_callback_func)(int, int, void *);
typedef void (*timer_callback_func)(id_type, void *);
typedef void (*GLFWuserdatafreefun)(id_type, void *);
typedef struct {
int fd, events, enabled, ready;
watch_callback_func callback;
void *callback_data;
GLFWuserdatafreefun free;
id_type id;
const char *name;
} Watch;
typedef struct {
id_type id;
monotonic_t interval, trigger_at;
timer_callback_func callback;
void *callback_data;
GLFWuserdatafreefun free;
const char *name;
bool repeats;
} Timer;
#define MAX_NUM_OF_WATCHED_FDS 64
typedef struct {
struct pollfd fds[MAX_NUM_OF_WATCHED_FDS];
#ifdef HAS_EVENT_FD
int wakeupFd;
#else
int wakeupFds[2];
#endif
#ifdef HAS_TIMER_FD
int key_repeat_fd;
#else
int key_repeat_fds[2];
#endif
bool wakeup_data_read, wakeup_fd_ready, key_repeat_fd_ready;
nfds_t watches_count, timers_count;
Watch watches[MAX_NUM_OF_WATCHED_FDS];
Timer timers[128];
} EventLoopData;
void check_for_wakeup_events(EventLoopData *eld);
id_type addWatch(EventLoopData *eld, const char *name, int fd, int events, int enabled, watch_callback_func cb, void *cb_data);
void removeWatch(EventLoopData *eld, id_type watch_id);
void toggleWatch(EventLoopData *eld, id_type watch_id, int enabled);
id_type addTimer(
EventLoopData *eld, const char *name, monotonic_t interval, int enabled, bool repeats, timer_callback_func cb, void *cb_data, GLFWuserdatafreefun free);
void removeTimer(EventLoopData *eld, id_type timer_id);
void removeAllTimers(EventLoopData *eld);
void toggleTimer(EventLoopData *eld, id_type timer_id, int enabled);
void changeTimerInterval(EventLoopData *eld, id_type timer_id, monotonic_t interval);
monotonic_t prepareForPoll(EventLoopData *eld, monotonic_t timeout);
int pollWithTimeout(struct pollfd *fds, nfds_t nfds, monotonic_t timeout);
int pollForEvents(EventLoopData *eld, monotonic_t timeout, watch_callback_func);
unsigned dispatchTimers(EventLoopData *eld);
void finalizePollData(EventLoopData *eld);
bool initPollData(EventLoopData *eld, int display_fd);
void wakeupEventLoop(EventLoopData *eld);
char *utf_8_strndup(const char *source, size_t max_length);
int createAnonymousFile(off_t size);
+286
View File
@@ -0,0 +1,286 @@
/*
* cocoa_displaylink.m
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
// CVDisplayLink is deprecated replace with CADisplayLink via [NSScreen displayLink] once base macOS version is 14
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#include "internal.h"
#include <CoreVideo/CVDisplayLink.h>
#include <os/lock.h>
#define DISPLAY_LINK_SHUTDOWN_CHECK_INTERVAL s_to_monotonic_t(30ll)
#define MAX_NUM_OF_DISPLAYS 256
typedef struct _GLFWDisplayLinkNS {
CVDisplayLinkRef displayLink;
CGDirectDisplayID displayID;
monotonic_t lastRenderFrameRequestedAt, first_unserviced_render_frame_request_at;
bool pending_dispatch;
} _GLFWDisplayLinkNS;
static struct {
_GLFWDisplayLinkNS entries[MAX_NUM_OF_DISPLAYS];
os_unfair_lock locks[MAX_NUM_OF_DISPLAYS];
bool locks_initialized[MAX_NUM_OF_DISPLAYS];
size_t count;
} displayLinks = {0};
static inline size_t
index_for_entry(_GLFWDisplayLinkNS *entry) {
return (size_t)(entry - displayLinks.entries);
}
static inline os_unfair_lock *
lock_for_entry(_GLFWDisplayLinkNS *entry) {
return &displayLinks.locks[index_for_entry(entry)];
}
static CGDirectDisplayID
displayIDForWindow(_GLFWwindow *w) {
NSWindow *nw = w->ns.object;
NSDictionary *dict = [nw.screen deviceDescription];
NSNumber *displayIDns = dict[@"NSScreenNumber"];
if (displayIDns) return [displayIDns unsignedIntValue];
return (CGDirectDisplayID)-1;
}
void
_glfwClearDisplayLinks(void) {
for (size_t i = 0; i < displayLinks.count; i++) {
_GLFWDisplayLinkNS *entry = &displayLinks.entries[i];
os_unfair_lock *lock = &displayLinks.locks[i];
os_unfair_lock_lock(lock);
CVDisplayLinkRef link = entry->displayLink;
entry->displayLink = NULL;
entry->displayID = (CGDirectDisplayID)0;
entry->lastRenderFrameRequestedAt = 0;
entry->first_unserviced_render_frame_request_at = 0;
entry->pending_dispatch = false;
os_unfair_lock_unlock(lock);
if (link) {
CVDisplayLinkStop(link);
CVDisplayLinkRelease(link);
}
}
displayLinks.count = 0;
}
static void _glfwDispatchRenderFrame(void *);
static CVReturn
displayLinkCallback(
CVDisplayLinkRef displayLink UNUSED,
const CVTimeStamp *now UNUSED,
const CVTimeStamp *outputTime UNUSED,
CVOptionFlags flagsIn UNUSED,
CVOptionFlags *flagsOut UNUSED,
void *userInfo) {
_GLFWDisplayLinkNS *entry = (_GLFWDisplayLinkNS *)userInfo;
if (entry) {
os_unfair_lock *lock = lock_for_entry(entry);
os_unfair_lock_lock(lock);
const bool should_dispatch = entry->first_unserviced_render_frame_request_at && !entry->pending_dispatch;
CGDirectDisplayID displayID = entry->displayID;
if (should_dispatch) entry->pending_dispatch = true;
os_unfair_lock_unlock(lock);
if (should_dispatch) dispatch_async_f(dispatch_get_main_queue(), (void *)(uintptr_t)displayID, _glfwDispatchRenderFrame);
}
return kCVReturnSuccess;
}
static void
_glfw_create_cv_display_link(_GLFWDisplayLinkNS *entry) {
CVDisplayLinkCreateWithCGDisplay(entry->displayID, &entry->displayLink);
if (entry->displayLink) CVDisplayLinkSetOutputCallback(entry->displayLink, &displayLinkCallback, entry);
}
unsigned
_glfwCreateDisplayLink(CGDirectDisplayID displayID) {
for (unsigned i = 0; i < displayLinks.count; i++) {
os_unfair_lock *existing_lock = &displayLinks.locks[i];
os_unfair_lock_lock(existing_lock);
const bool already_created = displayLinks.entries[i].displayID == displayID;
os_unfair_lock_unlock(existing_lock);
if (already_created) return i;
}
if (displayLinks.count >= MAX_NUM_OF_DISPLAYS) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Too many monitors cannot create display link");
return displayLinks.count;
}
unsigned idx = displayLinks.count;
_GLFWDisplayLinkNS *entry = &displayLinks.entries[idx];
if (!displayLinks.locks_initialized[idx]) {
displayLinks.locks[idx] = OS_UNFAIR_LOCK_INIT;
displayLinks.locks_initialized[idx] = true;
}
os_unfair_lock *lock = &displayLinks.locks[idx];
os_unfair_lock_lock(lock);
memset(entry, 0, sizeof(entry[0]));
entry->displayID = displayID;
displayLinks.count++;
_glfw_create_cv_display_link(entry);
os_unfair_lock_unlock(lock);
return idx;
}
static unsigned long long display_link_shutdown_timer = 0;
static void
_glfwShutdownCVDisplayLink(unsigned long long timer_id UNUSED, void *user_data UNUSED) {
display_link_shutdown_timer = 0;
for (size_t i = 0; i < displayLinks.count; i++) {
_GLFWDisplayLinkNS *dl = &displayLinks.entries[i];
os_unfair_lock *lock = &displayLinks.locks[i];
os_unfair_lock_lock(lock);
CVDisplayLinkRef link = dl->displayLink;
if (link) CVDisplayLinkRetain(link);
dl->lastRenderFrameRequestedAt = 0;
dl->first_unserviced_render_frame_request_at = 0;
dl->pending_dispatch = false;
os_unfair_lock_unlock(lock);
if (link) {
CVDisplayLinkStop(link);
CVDisplayLinkRelease(link);
}
}
}
void
_glfwRequestRenderFrame(_GLFWwindow *w) {
CGDirectDisplayID displayID = displayIDForWindow(w);
if (display_link_shutdown_timer) {
_glfwPlatformUpdateTimer(display_link_shutdown_timer, DISPLAY_LINK_SHUTDOWN_CHECK_INTERVAL, true);
} else {
display_link_shutdown_timer = _glfwPlatformAddTimer(DISPLAY_LINK_SHUTDOWN_CHECK_INTERVAL, false, _glfwShutdownCVDisplayLink, NULL, NULL);
}
monotonic_t now = glfwGetTime();
bool found_display_link = false;
_GLFWDisplayLinkNS *dl = NULL;
for (size_t i = 0; i < displayLinks.count; i++) {
dl = &displayLinks.entries[i];
bool need_start = false, need_stop = false, need_recreate = false;
bool retain_link = false;
CVDisplayLinkRef link = NULL;
CVDisplayLinkRef new_link = NULL;
bool new_link_retained = false;
os_unfair_lock *lock = &displayLinks.locks[i];
os_unfair_lock_lock(lock);
link = dl->displayLink;
if (dl->displayID == displayID) {
found_display_link = true;
monotonic_t first_unserviced = dl->first_unserviced_render_frame_request_at;
dl->lastRenderFrameRequestedAt = now;
if (!first_unserviced) {
dl->first_unserviced_render_frame_request_at = now;
first_unserviced = now;
}
dl->pending_dispatch = false;
if (link) {
if (!CVDisplayLinkIsRunning(link)) {
need_start = true;
retain_link = true;
} else if (now - first_unserviced > s_to_monotonic_t(1ll)) {
need_recreate = true;
dl->first_unserviced_render_frame_request_at = now;
dl->displayLink = NULL;
}
}
} else if (link && dl->lastRenderFrameRequestedAt && now - dl->lastRenderFrameRequestedAt >= DISPLAY_LINK_SHUTDOWN_CHECK_INTERVAL) {
need_stop = true;
retain_link = true;
dl->lastRenderFrameRequestedAt = 0;
dl->first_unserviced_render_frame_request_at = 0;
dl->pending_dispatch = false;
}
if (retain_link && link) CVDisplayLinkRetain(link);
os_unfair_lock_unlock(lock);
if (need_recreate && link) {
CVDisplayLinkStop(link);
CVDisplayLinkRelease(link);
os_unfair_lock_lock(lock);
_glfw_create_cv_display_link(dl);
new_link = dl->displayLink;
if (new_link) {
CVDisplayLinkRetain(new_link);
new_link_retained = true;
}
dl->pending_dispatch = false;
os_unfair_lock_unlock(lock);
if (new_link) {
if (!CVDisplayLinkIsRunning(new_link)) CVDisplayLinkStart(new_link);
if (new_link_retained) CVDisplayLinkRelease(new_link);
}
_glfwInputError(GLFW_PLATFORM_ERROR, "CVDisplayLink stuck possibly because of sleep/screensaver + Apple's incompetence, recreating.");
} else {
if (need_start && link) CVDisplayLinkStart(link);
else if (need_stop && link) CVDisplayLinkStop(link);
if (retain_link && link) CVDisplayLinkRelease(link);
}
}
if (!found_display_link) {
unsigned idx = _glfwCreateDisplayLink(displayID);
if (idx < displayLinks.count) {
dl = &displayLinks.entries[idx];
os_unfair_lock *lock = &displayLinks.locks[idx];
os_unfair_lock_lock(lock);
dl->lastRenderFrameRequestedAt = now;
dl->first_unserviced_render_frame_request_at = now;
dl->pending_dispatch = false;
CVDisplayLinkRef link = dl->displayLink;
if (link) CVDisplayLinkRetain(link);
os_unfair_lock_unlock(lock);
if (link) {
if (!CVDisplayLinkIsRunning(link)) CVDisplayLinkStart(link);
CVDisplayLinkRelease(link);
}
}
}
}
static void
_glfwDispatchRenderFrame(void *passed_in_data) {
CGDirectDisplayID displayID = (uintptr_t)passed_in_data;
_GLFWwindow *w = _glfw.windowListHead;
while (w) {
if (w->ns.renderFrameRequested && displayID == displayIDForWindow(w)) {
w->ns.renderFrameRequested = false;
w->ns.renderFrameCallback((GLFWwindow *)w);
}
w = w->next;
}
for (size_t i = 0; i < displayLinks.count; i++) {
_GLFWDisplayLinkNS *dl = &displayLinks.entries[i];
bool need_stop = false;
CVDisplayLinkRef link = NULL;
os_unfair_lock *lock = &displayLinks.locks[i];
os_unfair_lock_lock(lock);
if (dl->displayID == displayID) {
dl->first_unserviced_render_frame_request_at = 0;
dl->pending_dispatch = false;
bool any_pending_request = false;
_GLFWwindow *window = _glfw.windowListHead;
while (window) {
if (window->ns.renderFrameRequested && displayID == displayIDForWindow(window)) {
any_pending_request = true;
break;
}
window = window->next;
}
link = dl->displayLink;
if (!any_pending_request && link && CVDisplayLinkIsRunning(link)) {
need_stop = true;
CVDisplayLinkRetain(link);
dl->lastRenderFrameRequestedAt = 0;
}
}
os_unfair_lock_unlock(lock);
if (need_stop && link) {
CVDisplayLinkStop(link);
CVDisplayLinkRelease(link);
}
}
}
+1187
View File
File diff suppressed because it is too large. Load diff
+44
View File
@@ -0,0 +1,44 @@
//========================================================================
// GLFW 3.4 Cocoa - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2006-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <IOKit/IOKitLib.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/hid/IOHIDLib.h>
#include <IOKit/hid/IOHIDKeys.h>
#define _GLFW_PLATFORM_JOYSTICK_STATE _GLFWjoystickNS ns
#define _GLFW_PLATFORM_LIBRARY_JOYSTICK_STATE
#define _GLFW_PLATFORM_MAPPING_NAME "Mac OS X"
// Cocoa-specific per-joystick data
//
typedef struct _GLFWjoystickNS {
IOHIDDeviceRef device;
CFMutableArrayRef axes;
CFMutableArrayRef buttons;
CFMutableArrayRef hats;
} _GLFWjoystickNS;
+379
View File
@@ -0,0 +1,379 @@
//========================================================================
// GLFW 3.4 Cocoa - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2009-2019 Camilla Löwy <elmindreda@glfw.org>
// Copyright (c) 2012 Torsten Walluhn <tw@mad-cad.net>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <mach/mach.h>
#include <mach/mach_error.h>
#include <CoreFoundation/CoreFoundation.h>
#include <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
// Joystick element information
//
typedef struct _GLFWjoyelementNS {
IOHIDElementRef native;
uint32_t usage;
int index;
long minimum;
long maximum;
} _GLFWjoyelementNS;
// Returns the value of the specified element of the specified joystick
//
static long
getElementValue(_GLFWjoystick *js, _GLFWjoyelementNS *element) {
IOHIDValueRef valueRef;
long value = 0;
if (js->ns.device) {
if (IOHIDDeviceGetValue(js->ns.device, element->native, &valueRef) == kIOReturnSuccess) { value = IOHIDValueGetIntegerValue(valueRef); }
}
return value;
}
// Comparison function for matching the SDL element order
//
static CFComparisonResult
compareElements(const void *fp, const void *sp, void *user UNUSED) {
const _GLFWjoyelementNS *fe = fp;
const _GLFWjoyelementNS *se = sp;
if (fe->usage < se->usage) return kCFCompareLessThan;
if (fe->usage > se->usage) return kCFCompareGreaterThan;
if (fe->index < se->index) return kCFCompareLessThan;
if (fe->index > se->index) return kCFCompareGreaterThan;
return kCFCompareEqualTo;
}
// Removes the specified joystick
//
static void
closeJoystick(_GLFWjoystick *js) {
int i;
if (!js->present) return;
for (i = 0; i < CFArrayGetCount(js->ns.axes); i++) free((void *)CFArrayGetValueAtIndex(js->ns.axes, i));
CFRelease(js->ns.axes);
for (i = 0; i < CFArrayGetCount(js->ns.buttons); i++) free((void *)CFArrayGetValueAtIndex(js->ns.buttons, i));
CFRelease(js->ns.buttons);
for (i = 0; i < CFArrayGetCount(js->ns.hats); i++) free((void *)CFArrayGetValueAtIndex(js->ns.hats, i));
CFRelease(js->ns.hats);
_glfwFreeJoystick(js);
_glfwInputJoystick(js, GLFW_DISCONNECTED);
}
// Callback for user-initiated joystick addition
//
static void
matchCallback(void *context UNUSED, IOReturn result UNUSED, void *sender UNUSED, IOHIDDeviceRef device) {
int jid;
char name[256];
char guid[33];
CFIndex i;
CFTypeRef property;
uint32_t vendor = 0, product = 0, version = 0;
_GLFWjoystick *js;
CFMutableArrayRef axes, buttons, hats;
for (jid = 0; jid <= GLFW_JOYSTICK_LAST; jid++) {
if (_glfw.joysticks[jid].ns.device == device) return;
}
axes = CFArrayCreateMutable(NULL, 0, NULL);
buttons = CFArrayCreateMutable(NULL, 0, NULL);
hats = CFArrayCreateMutable(NULL, 0, NULL);
property = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductKey));
if (property) {
CFStringGetCString(property, name, sizeof(name), kCFStringEncodingUTF8);
} else strncpy(name, "Unknown", sizeof(name));
property = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDVendorIDKey));
if (property) CFNumberGetValue(property, kCFNumberSInt32Type, &vendor);
property = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductIDKey));
if (property) CFNumberGetValue(property, kCFNumberSInt32Type, &product);
property = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDVersionNumberKey));
if (property) CFNumberGetValue(property, kCFNumberSInt32Type, &version);
// Generate a joystick GUID that matches the SDL 2.0.5+ one
if (vendor && product) {
snprintf(
guid,
sizeof(guid),
"03000000%02x%02x0000%02x%02x0000%02x%02x0000",
(uint8_t)vendor,
(uint8_t)(vendor >> 8),
(uint8_t)product,
(uint8_t)(product >> 8),
(uint8_t)version,
(uint8_t)(version >> 8));
} else {
snprintf(
guid,
sizeof(guid),
"05000000%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x00",
name[0],
name[1],
name[2],
name[3],
name[4],
name[5],
name[6],
name[7],
name[8],
name[9],
name[10]);
}
CFArrayRef elements = IOHIDDeviceCopyMatchingElements(device, NULL, kIOHIDOptionsTypeNone);
for (i = 0; i < CFArrayGetCount(elements); i++) {
IOHIDElementRef native = (IOHIDElementRef)CFArrayGetValueAtIndex(elements, i);
if (CFGetTypeID(native) != IOHIDElementGetTypeID()) continue;
const IOHIDElementType type = IOHIDElementGetType(native);
if ((type != kIOHIDElementTypeInput_Axis) && (type != kIOHIDElementTypeInput_Button) && (type != kIOHIDElementTypeInput_Misc)) { continue; }
CFMutableArrayRef target = NULL;
const uint32_t usage = IOHIDElementGetUsage(native);
const uint32_t page = IOHIDElementGetUsagePage(native);
if (page == kHIDPage_GenericDesktop) {
switch (usage) {
case kHIDUsage_GD_X:
case kHIDUsage_GD_Y:
case kHIDUsage_GD_Z:
case kHIDUsage_GD_Rx:
case kHIDUsage_GD_Ry:
case kHIDUsage_GD_Rz:
case kHIDUsage_GD_Slider:
case kHIDUsage_GD_Dial:
case kHIDUsage_GD_Wheel: target = axes; break;
case kHIDUsage_GD_Hatswitch: target = hats; break;
case kHIDUsage_GD_DPadUp:
case kHIDUsage_GD_DPadRight:
case kHIDUsage_GD_DPadDown:
case kHIDUsage_GD_DPadLeft:
case kHIDUsage_GD_SystemMainMenu:
case kHIDUsage_GD_Select:
case kHIDUsage_GD_Start: target = buttons; break;
}
} else if (page == kHIDPage_Simulation) {
switch (usage) {
case kHIDUsage_Sim_Accelerator:
case kHIDUsage_Sim_Brake:
case kHIDUsage_Sim_Throttle:
case kHIDUsage_Sim_Rudder:
case kHIDUsage_Sim_Steering: target = axes; break;
}
} else if (page == kHIDPage_Button || page == kHIDPage_Consumer) target = buttons;
if (target) {
_GLFWjoyelementNS *element = calloc(1, sizeof(_GLFWjoyelementNS));
element->native = native;
element->usage = usage;
element->index = (int)CFArrayGetCount(target);
element->minimum = IOHIDElementGetLogicalMin(native);
element->maximum = IOHIDElementGetLogicalMax(native);
CFArrayAppendValue(target, element);
}
}
CFRelease(elements);
CFArraySortValues(axes, CFRangeMake(0, CFArrayGetCount(axes)), compareElements, NULL);
CFArraySortValues(buttons, CFRangeMake(0, CFArrayGetCount(buttons)), compareElements, NULL);
CFArraySortValues(hats, CFRangeMake(0, CFArrayGetCount(hats)), compareElements, NULL);
js = _glfwAllocJoystick(name, guid, (int)CFArrayGetCount(axes), (int)CFArrayGetCount(buttons), (int)CFArrayGetCount(hats));
js->ns.device = device;
js->ns.axes = axes;
js->ns.buttons = buttons;
js->ns.hats = hats;
_glfwInputJoystick(js, GLFW_CONNECTED);
}
// Callback for user-initiated joystick removal
//
static void
removeCallback(void *context UNUSED, IOReturn result UNUSED, void *sender UNUSED, IOHIDDeviceRef device) {
int jid;
for (jid = 0; jid <= GLFW_JOYSTICK_LAST; jid++) {
if (_glfw.joysticks[jid].ns.device == device) {
closeJoystick(_glfw.joysticks + jid);
break;
}
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
bool
_glfwPlatformInitJoysticks(void) {
CFMutableArrayRef matching;
const long usages[] = {kHIDUsage_GD_Joystick, kHIDUsage_GD_GamePad, kHIDUsage_GD_MultiAxisController};
_glfw.ns.hidManager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
matching = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
if (!matching) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to create array");
return false;
}
for (size_t i = 0; i < sizeof(usages) / sizeof(long); i++) {
const long page = kHIDPage_GenericDesktop;
CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
if (!dict) continue;
CFNumberRef pageRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongType, &page);
CFNumberRef usageRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongType, &usages[i]);
if (pageRef && usageRef) {
CFDictionarySetValue(dict, CFSTR(kIOHIDDeviceUsagePageKey), pageRef);
CFDictionarySetValue(dict, CFSTR(kIOHIDDeviceUsageKey), usageRef);
CFArrayAppendValue(matching, dict);
}
if (pageRef) CFRelease(pageRef);
if (usageRef) CFRelease(usageRef);
CFRelease(dict);
}
IOHIDManagerSetDeviceMatchingMultiple(_glfw.ns.hidManager, matching);
CFRelease(matching);
IOHIDManagerRegisterDeviceMatchingCallback(_glfw.ns.hidManager, &matchCallback, NULL);
IOHIDManagerRegisterDeviceRemovalCallback(_glfw.ns.hidManager, &removeCallback, NULL);
IOHIDManagerScheduleWithRunLoop(_glfw.ns.hidManager, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
IOHIDManagerOpen(_glfw.ns.hidManager, kIOHIDOptionsTypeNone);
// Execute the run loop once in order to register any initially-attached
// joysticks
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, false);
return true;
}
void
_glfwPlatformTerminateJoysticks(void) {
int jid;
for (jid = 0; jid <= GLFW_JOYSTICK_LAST; jid++) closeJoystick(_glfw.joysticks + jid);
if (_glfw.ns.hidManager) {
CFRelease(_glfw.ns.hidManager);
_glfw.ns.hidManager = NULL;
}
}
int
_glfwPlatformPollJoystick(_GLFWjoystick *js, int mode) {
if (mode & _GLFW_POLL_AXES) {
CFIndex i;
for (i = 0; i < CFArrayGetCount(js->ns.axes); i++) {
_GLFWjoyelementNS *axis = (_GLFWjoyelementNS *)CFArrayGetValueAtIndex(js->ns.axes, i);
const long raw = getElementValue(js, axis);
// Perform auto calibration
if (raw < axis->minimum) axis->minimum = raw;
if (raw > axis->maximum) axis->maximum = raw;
const long size = axis->maximum - axis->minimum;
if (size == 0) _glfwInputJoystickAxis(js, (int)i, 0.f);
else {
const float value = (2.f * (raw - axis->minimum) / size) - 1.f;
_glfwInputJoystickAxis(js, (int)i, value);
}
}
}
if (mode & _GLFW_POLL_BUTTONS) {
CFIndex i;
for (i = 0; i < CFArrayGetCount(js->ns.buttons); i++) {
_GLFWjoyelementNS *button = (_GLFWjoyelementNS *)CFArrayGetValueAtIndex(js->ns.buttons, i);
const char value = getElementValue(js, button) - button->minimum;
const int state = (value > 0) ? GLFW_PRESS : GLFW_RELEASE;
_glfwInputJoystickButton(js, (int)i, state);
}
for (i = 0; i < CFArrayGetCount(js->ns.hats); i++) {
const int states[9] = {
GLFW_HAT_UP,
GLFW_HAT_RIGHT_UP,
GLFW_HAT_RIGHT,
GLFW_HAT_RIGHT_DOWN,
GLFW_HAT_DOWN,
GLFW_HAT_LEFT_DOWN,
GLFW_HAT_LEFT,
GLFW_HAT_LEFT_UP,
GLFW_HAT_CENTERED};
_GLFWjoyelementNS *hat = (_GLFWjoyelementNS *)CFArrayGetValueAtIndex(js->ns.hats, i);
long state = getElementValue(js, hat) - hat->minimum;
if (state < 0 || state > 8) state = 8;
_glfwInputJoystickHat(js, (int)i, states[state]);
}
}
return js->present;
}
void
_glfwPlatformUpdateGamepadGUID(char *guid) {
if ((strncmp(guid + 4, "000000000000", 12) == 0) && (strncmp(guid + 20, "000000000000", 12) == 0)) {
char original[33];
strncpy(original, guid, sizeof(original) - 1);
snprintf(guid, 33, "03000000%.4s0000%.4s000000000000", original, original + 16);
}
}
+520
View File
@@ -0,0 +1,520 @@
//========================================================================
// GLFW 3.4 macOS - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <assert.h>
#include <IOKit/graphics/IOGraphicsLib.h>
#include <CoreVideo/CVBase.h>
#include <ApplicationServices/ApplicationServices.h>
// Get the name of the specified display, or NULL
//
static char *
getDisplayName(CGDirectDisplayID displayID, NSScreen *screen) {
// IOKit doesn't work on Apple Silicon anymore
// Luckily, 10.15 introduced -[NSScreen localizedName].
// Use it if available, and fall back to IOKit otherwise.
if (screen) {
if ([screen respondsToSelector:@selector(localizedName)]) {
NSString *name = [screen valueForKey:@"localizedName"];
if (name) { return _glfw_strdup([name UTF8String]); }
}
}
io_iterator_t it;
io_service_t service;
CFDictionaryRef info;
if (IOServiceGetMatchingServices(0, IOServiceMatching("IODisplayConnect"), &it) != 0) {
// This may happen if a desktop Mac is running headless
return NULL;
}
while ((service = IOIteratorNext(it)) != 0) {
info = IODisplayCreateInfoDictionary(service, kIODisplayOnlyPreferredName);
CFNumberRef vendorIDRef = CFDictionaryGetValue(info, CFSTR(kDisplayVendorID));
CFNumberRef productIDRef = CFDictionaryGetValue(info, CFSTR(kDisplayProductID));
if (!vendorIDRef || !productIDRef) {
CFRelease(info);
continue;
}
unsigned int vendorID, productID;
CFNumberGetValue(vendorIDRef, kCFNumberIntType, &vendorID);
CFNumberGetValue(productIDRef, kCFNumberIntType, &productID);
if (CGDisplayVendorNumber(displayID) == vendorID && CGDisplayModelNumber(displayID) == productID) {
// Info dictionary is used and freed below
break;
}
CFRelease(info);
}
IOObjectRelease(it);
if (!service) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to find service port for display");
return NULL;
}
CFDictionaryRef names = CFDictionaryGetValue(info, CFSTR(kDisplayProductName));
CFStringRef nameRef;
if (!names || !CFDictionaryGetValueIfPresent(names, CFSTR("en_US"), (const void **)&nameRef)) {
// This may happen if a desktop Mac is running headless
CFRelease(info);
return NULL;
}
const CFIndex size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);
char *name = calloc(size + 1, 1);
CFStringGetCString(nameRef, name, size, kCFStringEncodingUTF8);
CFRelease(info);
return name;
}
// Check whether the display mode should be included in enumeration
//
static bool
modeIsGood(CGDisplayModeRef mode) {
uint32_t flags = CGDisplayModeGetIOFlags(mode);
if (!(flags & kDisplayModeValidFlag) || !(flags & kDisplayModeSafeFlag)) return false;
if (flags & kDisplayModeInterlacedFlag) return false;
if (flags & kDisplayModeStretchedFlag) return false;
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 101100
CFStringRef format = CGDisplayModeCopyPixelEncoding(mode);
if (CFStringCompare(format, CFSTR(IO16BitDirectPixels), 0) && CFStringCompare(format, CFSTR(IO32BitDirectPixels), 0)) {
CFRelease(format);
return false;
}
CFRelease(format);
#endif /* MAC_OS_X_VERSION_MAX_ALLOWED */
return true;
}
// Convert Core Graphics display mode to GLFW video mode
//
static GLFWvidmode
vidmodeFromCGDisplayMode(CGDisplayModeRef mode, double fallbackRefreshRate) {
GLFWvidmode result;
result.width = (int)CGDisplayModeGetWidth(mode);
result.height = (int)CGDisplayModeGetHeight(mode);
result.refreshRate = (int)round(CGDisplayModeGetRefreshRate(mode));
if (result.refreshRate == 0) result.refreshRate = (int)round(fallbackRefreshRate);
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 101100
CFStringRef format = CGDisplayModeCopyPixelEncoding(mode);
if (CFStringCompare(format, CFSTR(IO16BitDirectPixels), 0) == 0) {
result.redBits = 5;
result.greenBits = 5;
result.blueBits = 5;
} else
#endif /* MAC_OS_X_VERSION_MAX_ALLOWED */
{
result.redBits = 8;
result.greenBits = 8;
result.blueBits = 8;
}
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 101100
CFRelease(format);
#endif /* MAC_OS_X_VERSION_MAX_ALLOWED */
return result;
}
// Starts reservation for display fading
//
static CGDisplayFadeReservationToken
beginFadeReservation(void) {
CGDisplayFadeReservationToken token = kCGDisplayFadeReservationInvalidToken;
if (CGAcquireDisplayFadeReservation(5, &token) == kCGErrorSuccess) {
CGDisplayFade(token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE);
}
return token;
}
// Ends reservation for display fading
//
static void
endFadeReservation(CGDisplayFadeReservationToken token) {
if (token != kCGDisplayFadeReservationInvalidToken) {
CGDisplayFade(token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
CGReleaseDisplayFadeReservation(token);
}
}
// Finds and caches the NSScreen corresponding to the specified monitor
//
static bool
refreshMonitorScreen(_GLFWmonitor *monitor) {
if (monitor->ns.screen) return true;
for (NSScreen *screen in [NSScreen screens]) {
NSNumber *displayID = [screen deviceDescription][@"NSScreenNumber"];
// HACK: Compare unit numbers instead of display IDs to work around
// display replacement on machines with automatic graphics
// switching
if (monitor->ns.unitNumber == CGDisplayUnitNumber([displayID unsignedIntValue])) {
monitor->ns.screen = screen;
return true;
}
}
_glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to find a screen for monitor");
return false;
}
// Returns the display refresh rate queried from the I/O registry
//
static double
getFallbackRefreshRate(CGDirectDisplayID displayID) {
double refreshRate = 60.0;
io_iterator_t it;
io_service_t service;
if (IOServiceGetMatchingServices(0, IOServiceMatching("IOFramebuffer"), &it) != 0) { return refreshRate; }
while ((service = IOIteratorNext(it)) != 0) {
const CFNumberRef indexRef = IORegistryEntryCreateCFProperty(service, CFSTR("IOFramebufferOpenGLIndex"), kCFAllocatorDefault, kNilOptions);
if (!indexRef) continue;
uint32_t index = 0;
CFNumberGetValue(indexRef, kCFNumberIntType, &index);
CFRelease(indexRef);
if (CGOpenGLDisplayMaskToDisplayID(1 << index) != displayID) continue;
const CFNumberRef clockRef = IORegistryEntryCreateCFProperty(service, CFSTR("IOFBCurrentPixelClock"), kCFAllocatorDefault, kNilOptions);
const CFNumberRef countRef = IORegistryEntryCreateCFProperty(service, CFSTR("IOFBCurrentPixelCount"), kCFAllocatorDefault, kNilOptions);
uint32_t clock = 0, count = 0;
if (clockRef) {
CFNumberGetValue(clockRef, kCFNumberIntType, &clock);
CFRelease(clockRef);
}
if (countRef) {
CFNumberGetValue(countRef, kCFNumberIntType, &count);
CFRelease(countRef);
}
if (clock > 0 && count > 0) refreshRate = clock / (double)count;
break;
}
IOObjectRelease(it);
return refreshRate;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Poll for changes in the set of connected monitors
void
_glfwPollMonitorsNS(void) {
uint32_t displayCount;
CGGetOnlineDisplayList(0, NULL, &displayCount);
CGDirectDisplayID *displays = calloc(displayCount, sizeof(CGDirectDisplayID));
CGGetOnlineDisplayList(displayCount, displays, &displayCount);
_glfwClearDisplayLinks();
if (_glfw.hints.init.debugRendering) { fprintf(stderr, "Polling for monitors: %u found\n", displayCount); }
for (int i = 0; i < _glfw.monitorCount; i++) _glfw.monitors[i]->ns.screen = nil;
_GLFWmonitor **disconnected = NULL;
uint32_t disconnectedCount = _glfw.monitorCount;
if (disconnectedCount) {
disconnected = calloc(_glfw.monitorCount, sizeof(_GLFWmonitor *));
memcpy(disconnected, _glfw.monitors, _glfw.monitorCount * sizeof(_GLFWmonitor *));
}
for (uint32_t i = 0; i < displayCount; i++) {
if (CGDisplayIsAsleep(displays[i])) {
if (_glfw.hints.init.debugRendering) fprintf(stderr, "Ignoring sleeping display: %u", displays[i]);
continue;
}
const uint32_t unitNumber = CGDisplayUnitNumber(displays[i]);
NSScreen *screen = nil;
for (screen in [NSScreen screens]) {
NSNumber *screenNumber = [screen deviceDescription][@"NSScreenNumber"];
// HACK: Compare unit numbers instead of display IDs to work around
// display replacement on machines with automatic graphics
// switching
if (CGDisplayUnitNumber([screenNumber unsignedIntValue]) == unitNumber) break;
}
// HACK: Compare unit numbers instead of display IDs to work around
// display replacement on machines with automatic graphics
// switching
uint32_t j;
for (j = 0; j < disconnectedCount; j++) {
if (disconnected[j] && disconnected[j]->ns.unitNumber == unitNumber) {
disconnected[j]->ns.displayID = displays[i];
disconnected[j]->ns.screen = screen;
_glfwCreateDisplayLink(displays[i]);
disconnected[j] = NULL;
break;
}
}
if (j < disconnectedCount) continue;
const CGSize size = CGDisplayScreenSize(displays[i]);
char *name = getDisplayName(displays[i], screen);
if (!name) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Failed to get name for display, using generic name");
name = _glfw_strdup("Display with no name");
}
_GLFWmonitor *monitor = _glfwAllocMonitor(name, (int)size.width, (int)size.height);
monitor->ns.displayID = displays[i];
monitor->ns.unitNumber = unitNumber;
monitor->ns.screen = screen;
_glfwCreateDisplayLink(monitor->ns.displayID);
free(name);
CGDisplayModeRef mode = CGDisplayCopyDisplayMode(displays[i]);
if (CGDisplayModeGetRefreshRate(mode) == 0.0) monitor->ns.fallbackRefreshRate = getFallbackRefreshRate(displays[i]);
CGDisplayModeRelease(mode);
_glfwInputMonitor(monitor, GLFW_CONNECTED, _GLFW_INSERT_LAST);
}
for (uint32_t i = 0; i < disconnectedCount; i++) {
if (disconnected[i]) _glfwInputMonitor(disconnected[i], GLFW_DISCONNECTED, 0);
}
free(disconnected);
free(displays);
_glfwRestartDisplayLinks();
}
// Change the current video mode
//
void
_glfwSetVideoModeNS(_GLFWmonitor *monitor, const GLFWvidmode *desired) {
GLFWvidmode current;
_glfwPlatformGetVideoMode(monitor, &current);
const GLFWvidmode *best = _glfwChooseVideoMode(monitor, desired);
if (_glfwCompareVideoModes(&current, best) == 0) return;
CFArrayRef modes = CGDisplayCopyAllDisplayModes(monitor->ns.displayID, NULL);
const CFIndex count = CFArrayGetCount(modes);
CGDisplayModeRef native = NULL;
for (CFIndex i = 0; i < count; i++) {
CGDisplayModeRef dm = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i);
if (!modeIsGood(dm)) continue;
const GLFWvidmode mode = vidmodeFromCGDisplayMode(dm, monitor->ns.fallbackRefreshRate);
if (_glfwCompareVideoModes(best, &mode) == 0) {
native = dm;
break;
}
}
if (native) {
if (monitor->ns.previousMode == NULL) monitor->ns.previousMode = CGDisplayCopyDisplayMode(monitor->ns.displayID);
CGDisplayFadeReservationToken token = beginFadeReservation();
CGDisplaySetDisplayMode(monitor->ns.displayID, native, NULL);
endFadeReservation(token);
}
CFRelease(modes);
}
// Restore the previously saved (original) video mode
//
void
_glfwRestoreVideoModeNS(_GLFWmonitor *monitor) {
if (monitor->ns.previousMode) {
CGDisplayFadeReservationToken token = beginFadeReservation();
CGDisplaySetDisplayMode(monitor->ns.displayID, monitor->ns.previousMode, NULL);
endFadeReservation(token);
CGDisplayModeRelease(monitor->ns.previousMode);
monitor->ns.previousMode = NULL;
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
void
_glfwPlatformFreeMonitor(_GLFWmonitor *monitor UNUSED) {}
void
_glfwPlatformGetMonitorPos(_GLFWmonitor *monitor, int *xpos, int *ypos) {
const CGRect bounds = CGDisplayBounds(monitor->ns.displayID);
if (xpos) *xpos = (int)bounds.origin.x;
if (ypos) *ypos = (int)bounds.origin.y;
}
void
_glfwPlatformGetMonitorContentScale(_GLFWmonitor *monitor, float *xscale, float *yscale) {
if (!refreshMonitorScreen(monitor)) return;
const NSRect points = [monitor->ns.screen frame];
const NSRect pixels = [monitor->ns.screen convertRectToBacking:points];
if (xscale) *xscale = (float)(pixels.size.width / points.size.width);
if (yscale) *yscale = (float)(pixels.size.height / points.size.height);
}
void
_glfwPlatformGetMonitorWorkarea(_GLFWmonitor *monitor, int *xpos, int *ypos, int *width, int *height) {
if (!refreshMonitorScreen(monitor)) return;
const NSRect frameRect = [monitor->ns.screen visibleFrame];
if (xpos) *xpos = (int)frameRect.origin.x;
if (ypos) *ypos = (int)_glfwTransformYNS(frameRect.origin.y + frameRect.size.height - 1);
if (width) *width = (int)frameRect.size.width;
if (height) *height = (int)frameRect.size.height;
}
GLFWvidmode *
_glfwPlatformGetVideoModes(_GLFWmonitor *monitor, int *count) {
*count = 0;
CFArrayRef modes = CGDisplayCopyAllDisplayModes(monitor->ns.displayID, NULL);
const CFIndex found = CFArrayGetCount(modes);
GLFWvidmode *result = calloc(found, sizeof(GLFWvidmode));
for (CFIndex i = 0; i < found; i++) {
CGDisplayModeRef dm = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i);
if (!modeIsGood(dm)) continue;
const GLFWvidmode mode = vidmodeFromCGDisplayMode(dm, monitor->ns.fallbackRefreshRate);
CFIndex j;
for (j = 0; j < *count; j++) {
if (_glfwCompareVideoModes(result + j, &mode) == 0) break;
}
// Skip duplicate modes
if (j < *count) continue;
(*count)++;
result[*count - 1] = mode;
}
CFRelease(modes);
return result;
}
bool
_glfwPlatformGetVideoMode(_GLFWmonitor *monitor, GLFWvidmode *mode) {
CGDisplayModeRef native = CGDisplayCopyDisplayMode(monitor->ns.displayID);
if (!native) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to query display mode");
return false;
}
*mode = vidmodeFromCGDisplayMode(native, monitor->ns.fallbackRefreshRate);
CGDisplayModeRelease(native);
return true;
}
bool
_glfwPlatformGetGammaRamp(_GLFWmonitor *monitor, GLFWgammaramp *ramp) {
uint32_t size = CGDisplayGammaTableCapacity(monitor->ns.displayID);
CGGammaValue *values = calloc(size * 3, sizeof(CGGammaValue));
CGGetDisplayTransferByTable(monitor->ns.displayID, size, values, values + size, values + size * 2, &size);
_glfwAllocGammaArrays(ramp, size);
for (uint32_t i = 0; i < size; i++) {
ramp->red[i] = (unsigned short)(values[i] * 65535);
ramp->green[i] = (unsigned short)(values[i + size] * 65535);
ramp->blue[i] = (unsigned short)(values[i + size * 2] * 65535);
}
free(values);
return true;
}
void
_glfwPlatformSetGammaRamp(_GLFWmonitor *monitor, const GLFWgammaramp *ramp) {
CGGammaValue *values = calloc(ramp->size * 3, sizeof(CGGammaValue));
for (unsigned int i = 0; i < ramp->size; i++) {
values[i] = ramp->red[i] / 65535.f;
values[i + ramp->size] = ramp->green[i] / 65535.f;
values[i + ramp->size * 2] = ramp->blue[i] / 65535.f;
}
CGSetDisplayTransferByTable(monitor->ns.displayID, ramp->size, values, values + ramp->size, values + ramp->size * 2);
free(values);
}
//////////////////////////////////////////////////////////////////////////
////// GLFW native API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI CGDirectDisplayID
glfwGetCocoaMonitor(GLFWmonitor *handle) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(kCGNullDirectDisplay);
return monitor->ns.displayID;
}
+280
View File
@@ -0,0 +1,280 @@
//========================================================================
// GLFW 3.4 macOS - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2009-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <stdint.h>
#include <dlfcn.h>
#include <Carbon/Carbon.h>
#if defined(__OBJC__)
#import <Cocoa/Cocoa.h>
#else
typedef void *id;
#endif
// NOTE: Many Cocoa enum values have been renamed and we need to build across
// SDK versions where one is unavailable or the other deprecated
// We use the newer names in code and these macros to handle compatibility
#if MAC_OS_X_VERSION_MAX_ALLOWED < 101200
#define NSBitmapFormatAlphaNonpremultiplied NSAlphaNonpremultipliedBitmapFormat
#define NSEventMaskAny NSAnyEventMask
#define NSEventMaskKeyUp NSKeyUpMask
#define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
#define NSEventModifierFlagCommand NSCommandKeyMask
#define NSEventModifierFlagControl NSControlKeyMask
#define NSEventModifierFlagDeviceIndependentFlagsMask NSDeviceIndependentModifierFlagsMask
#define NSEventModifierFlagOption NSAlternateKeyMask
#define NSEventModifierFlagShift NSShiftKeyMask
#define NSEventTypeApplicationDefined NSApplicationDefined
#define NSWindowStyleMaskBorderless NSBorderlessWindowMask
#define NSWindowStyleMaskClosable NSClosableWindowMask
#define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
#define NSWindowStyleMaskResizable NSResizableWindowMask
#define NSWindowStyleMaskTitled NSTitledWindowMask
#endif
#if (MAC_OS_X_VERSION_MAX_ALLOWED < 101400)
#define NSPasteboardTypeFileURL NSFilenamesPboardType
#define NSBitmapFormatAlphaNonpremultiplied NSAlphaNonpremultipliedBitmapFormat
#define NSPasteboardTypeString NSStringPboardType
#define NSOpenGLContextParameterSurfaceOpacity NSOpenGLCPSurfaceOpacity
#endif
typedef int (*GLFWcocoatextinputfilterfun)(int, int, unsigned int, unsigned long);
typedef bool (*GLFWapplicationshouldhandlereopenfun)(int);
typedef bool (*GLFWhandleurlopen)(const char *);
typedef void (*GLFWapplicationwillfinishlaunchingfun)(bool);
typedef bool (*GLFWcocoatogglefullscreenfun)(GLFWwindow *);
typedef void (*GLFWcocoarenderframefun)(GLFWwindow *);
typedef VkFlags VkMacOSSurfaceCreateFlagsMVK;
typedef VkFlags VkMetalSurfaceCreateFlagsEXT;
typedef struct VkMacOSSurfaceCreateInfoMVK {
VkStructureType sType;
const void *pNext;
VkMacOSSurfaceCreateFlagsMVK flags;
const void *pView;
} VkMacOSSurfaceCreateInfoMVK;
typedef struct VkMetalSurfaceCreateInfoEXT {
VkStructureType sType;
const void *pNext;
VkMetalSurfaceCreateFlagsEXT flags;
const void *pLayer;
} VkMetalSurfaceCreateInfoEXT;
typedef VkResult(APIENTRY *PFN_vkCreateMacOSSurfaceMVK)(VkInstance, const VkMacOSSurfaceCreateInfoMVK *, const VkAllocationCallbacks *, VkSurfaceKHR *);
typedef VkResult(APIENTRY *PFN_vkCreateMetalSurfaceEXT)(VkInstance, const VkMetalSurfaceCreateInfoEXT *, const VkAllocationCallbacks *, VkSurfaceKHR *);
#include "posix_thread.h"
#include "cocoa_joystick.h"
#include "nsgl_context.h"
#define _glfw_dlopen(name) dlopen(name, RTLD_LAZY | RTLD_LOCAL)
#define _glfw_dlclose(handle) dlclose(handle)
#define _glfw_dlsym(handle, name) dlsym(handle, name)
#define _GLFW_PLATFORM_WINDOW_STATE _GLFWwindowNS ns
#define _GLFW_PLATFORM_LIBRARY_WINDOW_STATE _GLFWlibraryNS ns
#define _GLFW_PLATFORM_LIBRARY_TIMER_STATE _GLFWtimerNS ns
#define _GLFW_PLATFORM_MONITOR_STATE _GLFWmonitorNS ns
#define _GLFW_PLATFORM_CURSOR_STATE _GLFWcursorNS ns
// HIToolbox.framework pointer typedefs
#define kTISPropertyUnicodeKeyLayoutData _glfw.ns.tis.kPropertyUnicodeKeyLayoutData
typedef TISInputSourceRef (*PFN_TISCopyCurrentKeyboardLayoutInputSource)(void);
#define TISCopyCurrentKeyboardLayoutInputSource _glfw.ns.tis.CopyCurrentKeyboardLayoutInputSource
typedef void *(*PFN_TISGetInputSourceProperty)(TISInputSourceRef, CFStringRef);
#define TISGetInputSourceProperty _glfw.ns.tis.GetInputSourceProperty
typedef UInt8 (*PFN_LMGetKbdType)(void);
#define LMGetKbdType _glfw.ns.tis.GetKbdType
typedef struct _GLFWDropData {
const char **mimes; // Original MIME list; strings are owned here, never reordered
size_t mimes_count;
const char **copy_mimes; // Working copy passed to callbacks; pointers into mimes[]
size_t copy_mimes_count; // Accepted count after last callback
bool drag_accepted;
struct {
unsigned long long request_id;
id temp_dir;
id data_map; // map MIME to NSError or NSInputStream
id path_map; // map MIME to NSError or NSInputStream or NSUrl
id pending_requests;
bool promises_loaded;
bool keep_temp_dir; // when true temp_dir is not deleted at end of drop, the application owns it
} in_progress_drop;
} _GLFWDropData;
// Cocoa-specific per-window data
//
typedef struct _GLFWwindowNS {
id object;
id delegate;
id view;
id layer;
bool maximized;
bool retina;
bool in_traditional_fullscreen;
bool in_fullscreen_transition;
bool suppress_frame_constraints;
id notch_cover_window;
unsigned int notch_cover_color;
float notch_cover_opacity;
bool titlebar_hidden;
unsigned long pre_full_screen_style_mask;
CGRect pre_traditional_fullscreen_frame;
// Cached window properties to filter out duplicate events
int width, height;
int fbWidth, fbHeight;
float xscale, yscale;
int blur_radius;
bool live_resize_in_progress;
struct {
struct {
CGFloat red, green, blue, alpha;
bool was_set;
} color;
bool transparent;
} last_applied_titlebar_settings;
// The total sum of the distances the cursor has been warped
// since the last cursor motion event was processed
// This is kept to counteract Cocoa doing the same internally
double cursorWarpDeltaX, cursorWarpDeltaY;
// The text input filter callback
GLFWcocoatextinputfilterfun textInputFilterCallback;
// The toggle fullscreen intercept callback
GLFWcocoatogglefullscreenfun toggleFullscreenCallback;
// Dead key state
UInt32 deadKeyState;
// Layer shell windows
struct {
bool is_active;
GLFWLayerShellConfig config;
} layer_shell;
// Whether a render frame has been requested for this window
bool renderFrameRequested;
GLFWcocoarenderframefun renderFrameCallback;
// update cursor after switching desktops with Mission Control
bool delayed_cursor_update_requested;
GLFWcocoarenderframefun resizeCallback;
// Cached MIME types from drag enter (for move events)
_GLFWDropData drop_data;
unsigned long long drop_request_counter;
} _GLFWwindowNS;
// Cocoa-specific global data
//
typedef struct _GLFWlibraryNS {
CGEventSourceRef eventSource;
id delegate;
bool finishedLaunching;
bool cursorHidden;
TISInputSourceRef inputSource;
IOHIDManagerRef hidManager;
id unicodeData;
id helper;
id keyUpMonitor, keyDownMonitor, flagsChangedMonitor;
id appleSettings;
id nibObjects;
char keyName[64];
char text[512];
CGPoint cascadePoint;
// Where to place the cursor when re-enabled
double restoreCursorPosX, restoreCursorPosY;
// The window whose disabled cursor mode is active
_GLFWwindow *disabledCursorWindow;
pid_t previous_front_most_application;
struct {
CFBundleRef bundle;
PFN_TISCopyCurrentKeyboardLayoutInputSource CopyCurrentKeyboardLayoutInputSource;
PFN_TISGetInputSourceProperty GetInputSourceProperty;
PFN_LMGetKbdType GetKbdType;
CFStringRef kPropertyUnicodeKeyLayoutData;
} tis;
// the callback to handle url open events
GLFWhandleurlopen url_open_callback;
// Active drag session (NSDraggingSession*) and view (NSView*)
id drag_session, drag_view, drag_image;
} _GLFWlibraryNS;
// Cocoa-specific per-monitor data
//
typedef struct _GLFWmonitorNS {
CGDirectDisplayID displayID;
CGDisplayModeRef previousMode;
uint32_t unitNumber;
id screen;
double fallbackRefreshRate;
} _GLFWmonitorNS;
// Cocoa-specific per-cursor data
//
typedef struct _GLFWcursorNS {
id object;
} _GLFWcursorNS;
// Cocoa-specific global timer data
//
typedef struct _GLFWtimerNS {
uint64_t frequency;
} _GLFWtimerNS;
void _glfwPollMonitorsNS(void);
void _glfwSetVideoModeNS(_GLFWmonitor *monitor, const GLFWvidmode *desired);
void _glfwRestoreVideoModeNS(_GLFWmonitor *monitor);
float _glfwTransformYNS(float y);
void *_glfwLoadLocalVulkanLoaderNS(void);
// display links
void _glfwClearDisplayLinks(void);
void _glfwRestartDisplayLinks(void);
unsigned _glfwCreateDisplayLink(CGDirectDisplayID);
void _glfwRequestRenderFrame(_GLFWwindow *w);
// event loop
void _glfwDispatchTickCallback(void);
void _glfwCocoaPostEmptyEvent(void);
uint32_t vk_to_unicode_key_with_current_layout(uint16_t keycode);
+5081
View File
File diff suppressed because it is too large. Load diff
+453
View File
@@ -0,0 +1,453 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2016 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// Please use C89 style variable declarations in this file because VS 2010
//========================================================================
#include "internal.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Checks whether the desired context attributes are valid
//
// This function checks things like whether the specified client API version
// exists and whether all relevant options have supported and non-conflicting
// values
//
bool
_glfwIsValidContextConfig(const _GLFWctxconfig *ctxconfig) {
if (ctxconfig->share) {
if (ctxconfig->client == GLFW_NO_API || ctxconfig->share->context.client == GLFW_NO_API) {
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL);
return false;
}
}
if (ctxconfig->source != GLFW_NATIVE_CONTEXT_API && ctxconfig->source != GLFW_EGL_CONTEXT_API && ctxconfig->source != GLFW_OSMESA_CONTEXT_API) {
_glfwInputError(GLFW_INVALID_ENUM, "Invalid context creation API 0x%08X", ctxconfig->source);
return false;
}
if (ctxconfig->client != GLFW_NO_API && ctxconfig->client != GLFW_OPENGL_API && ctxconfig->client != GLFW_OPENGL_ES_API) {
_glfwInputError(GLFW_INVALID_ENUM, "Invalid client API 0x%08X", ctxconfig->client);
return false;
}
if (ctxconfig->client == GLFW_OPENGL_API) {
if ((ctxconfig->major < 1 || ctxconfig->minor < 0) || (ctxconfig->major == 1 && ctxconfig->minor > 5) ||
(ctxconfig->major == 2 && ctxconfig->minor > 1) || (ctxconfig->major == 3 && ctxconfig->minor > 3)) {
// OpenGL 1.0 is the smallest valid version
// OpenGL 1.x series ended with version 1.5
// OpenGL 2.x series ended with version 2.1
// OpenGL 3.x series ended with version 3.3
// For now, let everything else through
_glfwInputError(GLFW_INVALID_VALUE, "Invalid OpenGL version %i.%i", ctxconfig->major, ctxconfig->minor);
return false;
}
if (ctxconfig->profile) {
if (ctxconfig->profile != GLFW_OPENGL_CORE_PROFILE && ctxconfig->profile != GLFW_OPENGL_COMPAT_PROFILE) {
_glfwInputError(GLFW_INVALID_ENUM, "Invalid OpenGL profile 0x%08X", ctxconfig->profile);
return false;
}
if (ctxconfig->major <= 2 || (ctxconfig->major == 3 && ctxconfig->minor < 2)) {
// Desktop OpenGL context profiles are only defined for version 3.2
// and above
_glfwInputError(GLFW_INVALID_VALUE, "Context profiles are only defined for OpenGL version 3.2 and above");
return false;
}
}
if (ctxconfig->forward && ctxconfig->major <= 2) {
// Forward-compatible contexts are only defined for OpenGL version 3.0 and above
_glfwInputError(GLFW_INVALID_VALUE, "Forward-compatibility is only defined for OpenGL version 3.0 and above");
return false;
}
} else if (ctxconfig->client == GLFW_OPENGL_ES_API) {
if (ctxconfig->major < 1 || ctxconfig->minor < 0 || (ctxconfig->major == 1 && ctxconfig->minor > 1) ||
(ctxconfig->major == 2 && ctxconfig->minor > 0)) {
// OpenGL ES 1.0 is the smallest valid version
// OpenGL ES 1.x series ended with version 1.1
// OpenGL ES 2.x series ended with version 2.0
// For now, let everything else through
_glfwInputError(GLFW_INVALID_VALUE, "Invalid OpenGL ES version %i.%i", ctxconfig->major, ctxconfig->minor);
return false;
}
}
if (ctxconfig->robustness) {
if (ctxconfig->robustness != GLFW_NO_RESET_NOTIFICATION && ctxconfig->robustness != GLFW_LOSE_CONTEXT_ON_RESET) {
_glfwInputError(GLFW_INVALID_ENUM, "Invalid context robustness mode 0x%08X", ctxconfig->robustness);
return false;
}
}
if (ctxconfig->release) {
if (ctxconfig->release != GLFW_RELEASE_BEHAVIOR_NONE && ctxconfig->release != GLFW_RELEASE_BEHAVIOR_FLUSH) {
_glfwInputError(GLFW_INVALID_ENUM, "Invalid context release behavior 0x%08X", ctxconfig->release);
return false;
}
}
return true;
}
// Retrieves the attributes of the current context
//
bool
_glfwRefreshContextAttribs(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig) {
int i;
_GLFWwindow *previous;
const char *version;
const char *prefixes[] = {"OpenGL ES-CM ", "OpenGL ES-CL ", "OpenGL ES ", NULL};
window->context.source = ctxconfig->source;
window->context.client = GLFW_OPENGL_API;
previous = _glfwPlatformGetTls(&_glfw.contextSlot);
glfwMakeContextCurrent((GLFWwindow *)window);
window->context.GetIntegerv = (PFNGLGETINTEGERVPROC)window->context.getProcAddress("glGetIntegerv");
window->context.GetString = (PFNGLGETSTRINGPROC)window->context.getProcAddress("glGetString");
if (!window->context.GetIntegerv || !window->context.GetString) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Entry point retrieval is broken");
glfwMakeContextCurrent((GLFWwindow *)previous);
return false;
}
version = (const char *)window->context.GetString(GL_VERSION);
if (!version) {
if (ctxconfig->client == GLFW_OPENGL_API) {
_glfwInputError(GLFW_PLATFORM_ERROR, "OpenGL version string retrieval is broken");
} else {
_glfwInputError(GLFW_PLATFORM_ERROR, "OpenGL ES version string retrieval is broken");
}
glfwMakeContextCurrent((GLFWwindow *)previous);
return false;
}
for (i = 0; prefixes[i]; i++) {
const size_t length = strlen(prefixes[i]);
if (strncmp(version, prefixes[i], length) == 0) {
version += length;
window->context.client = GLFW_OPENGL_ES_API;
break;
}
}
if (sscanf(version, "%d.%d.%d", &window->context.major, &window->context.minor, &window->context.revision) < 1) {
if (window->context.client == GLFW_OPENGL_API) {
_glfwInputError(GLFW_PLATFORM_ERROR, "No version found in OpenGL version string");
} else {
_glfwInputError(GLFW_PLATFORM_ERROR, "No version found in OpenGL ES version string");
}
glfwMakeContextCurrent((GLFWwindow *)previous);
return false;
}
if (window->context.major < ctxconfig->major || (window->context.major == ctxconfig->major && window->context.minor < ctxconfig->minor)) {
// The desired OpenGL version is greater than the actual version
// This only happens if the machine lacks {GLX|WGL}_ARB_create_context
// /and/ the user has requested an OpenGL version greater than 1.0
// For API consistency, we emulate the behavior of the
// {GLX|WGL}_ARB_create_context extension and fail here
if (window->context.client == GLFW_OPENGL_API) {
_glfwInputError(
GLFW_VERSION_UNAVAILABLE,
"Requested OpenGL version %i.%i, got version %i.%i",
ctxconfig->major,
ctxconfig->minor,
window->context.major,
window->context.minor);
} else {
_glfwInputError(
GLFW_VERSION_UNAVAILABLE,
"Requested OpenGL ES version %i.%i, got version %i.%i",
ctxconfig->major,
ctxconfig->minor,
window->context.major,
window->context.minor);
}
glfwMakeContextCurrent((GLFWwindow *)previous);
return false;
}
if (window->context.major >= 3) {
// OpenGL 3.0+ uses a different function for extension string retrieval
// We cache it here instead of in glfwExtensionSupported mostly to alert
// users as early as possible that their build may be broken
window->context.GetStringi = (PFNGLGETSTRINGIPROC)window->context.getProcAddress("glGetStringi");
if (!window->context.GetStringi) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Entry point retrieval is broken");
glfwMakeContextCurrent((GLFWwindow *)previous);
return false;
}
}
if (window->context.client == GLFW_OPENGL_API) {
// Read back context flags (OpenGL 3.0 and above)
if (window->context.major >= 3) {
GLint flags;
window->context.GetIntegerv(GL_CONTEXT_FLAGS, &flags);
if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT) window->context.forward = true;
if (flags & GL_CONTEXT_FLAG_DEBUG_BIT) window->context.debug = true;
else if (glfwExtensionSupported("GL_ARB_debug_output") && ctxconfig->debug) {
// HACK: This is a workaround for older drivers (pre KHR_debug)
// not setting the debug bit in the context flags for
// debug contexts
window->context.debug = true;
}
if (flags & GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR) window->context.noerror = true;
}
// Read back OpenGL context profile (OpenGL 3.2 and above)
if (window->context.major >= 4 || (window->context.major == 3 && window->context.minor >= 2)) {
GLint mask;
window->context.GetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask);
if (mask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) window->context.profile = GLFW_OPENGL_COMPAT_PROFILE;
else if (mask & GL_CONTEXT_CORE_PROFILE_BIT) window->context.profile = GLFW_OPENGL_CORE_PROFILE;
else if (glfwExtensionSupported("GL_ARB_compatibility")) {
// HACK: This is a workaround for the compatibility profile bit
// not being set in the context flags if an OpenGL 3.2+
// context was created without having requested a specific
// version
window->context.profile = GLFW_OPENGL_COMPAT_PROFILE;
}
}
// Read back robustness strategy
if (glfwExtensionSupported("GL_ARB_robustness")) {
// NOTE: We avoid using the context flags for detection, as they are
// only present from 3.0 while the extension applies from 1.1
GLint strategy;
window->context.GetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);
if (strategy == GL_LOSE_CONTEXT_ON_RESET_ARB) window->context.robustness = GLFW_LOSE_CONTEXT_ON_RESET;
else if (strategy == GL_NO_RESET_NOTIFICATION_ARB) window->context.robustness = GLFW_NO_RESET_NOTIFICATION;
}
} else {
// Read back robustness strategy
if (glfwExtensionSupported("GL_EXT_robustness")) {
// NOTE: The values of these constants match those of the OpenGL ARB
// one, so we can reuse them here
GLint strategy;
window->context.GetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);
if (strategy == GL_LOSE_CONTEXT_ON_RESET_ARB) window->context.robustness = GLFW_LOSE_CONTEXT_ON_RESET;
else if (strategy == GL_NO_RESET_NOTIFICATION_ARB) window->context.robustness = GLFW_NO_RESET_NOTIFICATION;
}
}
if (glfwExtensionSupported("GL_KHR_context_flush_control")) {
GLint behavior;
window->context.GetIntegerv(GL_CONTEXT_RELEASE_BEHAVIOR, &behavior);
if (behavior == GL_NONE) window->context.release = GLFW_RELEASE_BEHAVIOR_NONE;
else if (behavior == GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH) window->context.release = GLFW_RELEASE_BEHAVIOR_FLUSH;
}
glfwMakeContextCurrent((GLFWwindow *)previous);
return true;
}
// Searches an extension string for the specified extension
//
bool
_glfwStringInExtensionString(const char *string, const char *extensions) {
const char *start = extensions;
for (;;) {
const char *where;
const char *terminator;
where = strstr(start, string);
if (!where) return false;
terminator = where + strlen(string);
if (where == start || *(where - 1) == ' ') {
if (*terminator == ' ' || *terminator == '\0') break;
}
start = terminator;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW public API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI void
glfwMakeContextCurrent(GLFWwindow *handle) {
_GLFW_REQUIRE_INIT();
_GLFWwindow *window = (_GLFWwindow *)handle;
_GLFWwindow *previous = _glfwPlatformGetTls(&_glfw.contextSlot);
if (window && window->context.client == GLFW_NO_API) {
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, "Cannot make current with a window that has no OpenGL or OpenGL ES context");
return;
}
if (previous) {
if (!window || window->context.source != previous->context.source) previous->context.makeCurrent(NULL);
}
if (window) window->context.makeCurrent(window);
}
GLFWAPI GLFWwindow *
glfwGetCurrentContext(void) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
return _glfwPlatformGetTls(&_glfw.contextSlot);
}
GLFWAPI void
glfwSwapBuffers(GLFWwindow *handle) {
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(window != NULL);
_GLFW_REQUIRE_INIT();
if (window->context.client == GLFW_NO_API) {
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, "Cannot swap buffers of a window that has no OpenGL or OpenGL ES context");
return;
}
window->context.swapBuffers(window);
#ifdef _GLFW_WAYLAND
_glfwWaylandAfterBufferSwap(window);
#endif
}
GLFWAPI void
glfwSwapInterval(int interval) {
_GLFWwindow *window;
_GLFW_REQUIRE_INIT();
window = _glfwPlatformGetTls(&_glfw.contextSlot);
if (!window) {
_glfwInputError(GLFW_NO_CURRENT_CONTEXT, "Cannot set swap interval without a current OpenGL or OpenGL ES context");
return;
}
window->context.swapInterval(interval);
}
GLFWAPI int
glfwExtensionSupported(const char *extension) {
_GLFWwindow *window;
assert(extension != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(false);
window = _glfwPlatformGetTls(&_glfw.contextSlot);
if (!window) {
_glfwInputError(GLFW_NO_CURRENT_CONTEXT, "Cannot query extension without a current OpenGL or OpenGL ES context");
return false;
}
if (*extension == '\0') {
_glfwInputError(GLFW_INVALID_VALUE, "Extension name cannot be an empty string");
return false;
}
if (window->context.major >= 3) {
int i;
GLint count;
// Check if extension is in the modern OpenGL extensions string list
window->context.GetIntegerv(GL_NUM_EXTENSIONS, &count);
for (i = 0; i < count; i++) {
const char *en = (const char *)window->context.GetStringi(GL_EXTENSIONS, i);
if (!en) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Extension string retrieval is broken");
return false;
}
if (strcmp(en, extension) == 0) return true;
}
} else {
// Check if extension is in the old style OpenGL extensions string
const char *extensions = (const char *)window->context.GetString(GL_EXTENSIONS);
if (!extensions) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Extension string retrieval is broken");
return false;
}
if (_glfwStringInExtensionString(extension, extensions)) return true;
}
// Check if extension is in the platform-specific string
return window->context.extensionSupported(extension);
}
GLFWAPI GLFWglproc
glfwGetProcAddress(const char *procname) {
_GLFWwindow *window;
assert(procname != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
window = _glfwPlatformGetTls(&_glfw.contextSlot);
if (!window) {
_glfwInputError(GLFW_NO_CURRENT_CONTEXT, "Cannot query entry point without a current OpenGL or OpenGL ES context");
return NULL;
}
return window->context.getProcAddress(procname);
}
+415
View File
@@ -0,0 +1,415 @@
//========================================================================
// GLFW 3.4 XKB - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2018 Kovid Goyal <kovid@kovidgoyal.net>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include "internal.h"
#include "dbus_glfw.h"
#include "../kitty/monotonic.h"
#include <stdlib.h>
#include <string.h>
static void
report_error(DBusError *err, const char *fmt, ...) {
static char buf[4096];
va_list args;
va_start(args, fmt);
int n = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
if (n >= 0 && (size_t)n < (sizeof(buf) - 256)) snprintf(buf + n, sizeof(buf) - n, ". DBUS error: %s", err->message ? err->message : "(null)");
_glfwInputError(GLFW_PLATFORM_ERROR, "%s", buf);
dbus_error_free(err);
}
static _GLFWDBUSData *dbus_data = NULL;
static DBusConnection *session_bus = NULL;
bool
glfw_dbus_init(_GLFWDBUSData *dbus, EventLoopData *eld) {
dbus->eld = eld;
dbus_data = dbus;
return true;
}
static void
on_dbus_watch_ready(int fd UNUSED, int events, void *data) {
DBusWatch *watch = (DBusWatch *)data;
unsigned int flags = 0;
if (events & POLLERR) flags |= DBUS_WATCH_ERROR;
if (events & POLLHUP) flags |= DBUS_WATCH_HANGUP;
if (events & POLLIN) flags |= DBUS_WATCH_READABLE;
if (events & POLLOUT) flags |= DBUS_WATCH_WRITABLE;
dbus_watch_handle(watch, flags);
}
static int
events_for_watch(DBusWatch *watch) {
int events = 0;
unsigned int flags = dbus_watch_get_flags(watch);
if (flags & DBUS_WATCH_READABLE) events |= POLLIN;
if (flags & DBUS_WATCH_WRITABLE) events |= POLLOUT;
return events;
}
static dbus_bool_t
add_dbus_watch(DBusWatch *watch, void *data) {
id_type watch_id =
addWatch(dbus_data->eld, data, dbus_watch_get_unix_fd(watch), events_for_watch(watch), dbus_watch_get_enabled(watch), on_dbus_watch_ready, watch);
if (!watch_id) return FALSE;
id_type *idp = malloc(sizeof(id_type));
if (!idp) return FALSE;
*idp = watch_id;
dbus_watch_set_data(watch, idp, free);
return TRUE;
}
static void
remove_dbus_watch(DBusWatch *watch, void *data UNUSED) {
id_type *idp = dbus_watch_get_data(watch);
if (idp) removeWatch(dbus_data->eld, *idp);
}
static void
toggle_dbus_watch(DBusWatch *watch, void *data UNUSED) {
id_type *idp = dbus_watch_get_data(watch);
if (idp) toggleWatch(dbus_data->eld, *idp, dbus_watch_get_enabled(watch));
}
static void
on_dbus_timer_ready(id_type timer_id UNUSED, void *data) {
if (data) {
DBusTimeout *t = (DBusTimeout *)data;
dbus_timeout_handle(t);
}
}
static dbus_bool_t
add_dbus_timeout(DBusTimeout *timeout, void *data) {
int enabled = dbus_timeout_get_enabled(timeout) ? 1 : 0;
monotonic_t interval = ms_to_monotonic_t(dbus_timeout_get_interval(timeout));
if (interval < 0) return FALSE;
id_type timer_id = addTimer(dbus_data->eld, data, interval, enabled, true, on_dbus_timer_ready, timeout, NULL);
if (!timer_id) return FALSE;
id_type *idp = malloc(sizeof(id_type));
if (!idp) {
removeTimer(dbus_data->eld, timer_id);
return FALSE;
}
*idp = timer_id;
dbus_timeout_set_data(timeout, idp, free);
return TRUE;
}
static void
remove_dbus_timeout(DBusTimeout *timeout, void *data UNUSED) {
id_type *idp = dbus_timeout_get_data(timeout);
if (idp) removeTimer(dbus_data->eld, *idp);
}
static void
toggle_dbus_timeout(DBusTimeout *timeout, void *data UNUSED) {
id_type *idp = dbus_timeout_get_data(timeout);
if (idp) toggleTimer(dbus_data->eld, *idp, dbus_timeout_get_enabled(timeout));
}
DBusConnection *
glfw_dbus_connect_to(const char *path, const char *err_msg, const char *name, bool register_on_bus) {
DBusError err;
dbus_error_init(&err);
DBusConnection *ans = dbus_connection_open_private(path, &err);
if (!ans) {
report_error(&err, err_msg);
return NULL;
}
dbus_connection_set_exit_on_disconnect(ans, FALSE);
dbus_error_free(&err);
if (register_on_bus) {
if (!dbus_bus_register(ans, &err)) {
report_error(&err, err_msg);
return NULL;
}
}
if (!dbus_connection_set_watch_functions(ans, add_dbus_watch, remove_dbus_watch, toggle_dbus_watch, (void *)name, NULL)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Failed to set DBUS watches on connection to: %s", path);
dbus_connection_close(ans);
dbus_connection_unref(ans);
return NULL;
}
if (!dbus_connection_set_timeout_functions(ans, add_dbus_timeout, remove_dbus_timeout, toggle_dbus_timeout, (void *)name, NULL)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Failed to set DBUS timeout functions on connection to: %s", path);
dbus_connection_close(ans);
dbus_connection_unref(ans);
return NULL;
}
return ans;
}
static unsigned session_bus_dispatch_depth = 0;
void
glfw_dbus_dispatch(DBusConnection *conn) {
const bool is_session_bus = conn == session_bus;
if (is_session_bus) session_bus_dispatch_depth++;
while (dbus_connection_dispatch(conn) == DBUS_DISPATCH_DATA_REMAINS);
if (is_session_bus) session_bus_dispatch_depth--;
}
bool
glfw_dbus_session_bus_read_write_dispatch(int timeout_ms) {
// Dispatching is not re-entrant, so refuse to do it from inside a DBus callback
if (!session_bus || session_bus_dispatch_depth) return false;
session_bus_dispatch_depth++;
const bool ok = dbus_connection_read_write_dispatch(session_bus, timeout_ms);
session_bus_dispatch_depth--;
return ok;
}
void
glfw_dbus_session_bus_dispatch(void) {
if (session_bus) glfw_dbus_dispatch(session_bus);
}
void
glfw_dbus_terminate(_GLFWDBUSData *dbus UNUSED) {
if (dbus_data) {
dbus_data->eld = NULL;
dbus_data = NULL;
}
if (session_bus) {
dbus_connection_unref(session_bus);
session_bus = NULL;
}
}
void
glfw_dbus_close_connection(DBusConnection *conn) {
dbus_connection_close(conn);
dbus_connection_unref(conn);
}
bool
glfw_dbus_get_args(DBusMessage *msg, const char *failmsg, ...) {
DBusError err;
dbus_error_init(&err);
va_list ap;
va_start(ap, failmsg);
int firstarg = va_arg(ap, int);
bool ret = dbus_message_get_args_valist(msg, &err, firstarg, ap) ? true : false;
va_end(ap);
if (!ret) report_error(&err, failmsg);
return ret;
}
typedef struct {
dbus_pending_callback callback;
void *user_data;
} MethodResponse;
static void
method_reply_received(DBusPendingCall *pending, void *user_data) {
MethodResponse *res = (MethodResponse *)user_data;
RAII_MSG(msg, dbus_pending_call_steal_reply(pending));
if (msg) {
DBusError err;
dbus_error_init(&err);
if (dbus_set_error_from_message(&err, msg)) {
res->callback(NULL, &err, res->user_data);
dbus_error_free(&err);
} else res->callback(msg, NULL, res->user_data);
}
}
bool
call_method_with_msg(DBusConnection *conn, DBusMessage *msg, int timeout, dbus_pending_callback callback, void *user_data, bool block) {
bool retval = false;
#define REPORT(errs) \
_glfwInputError( \
GLFW_PLATFORM_ERROR, \
"Failed to call DBUS method: node=%s path=%s interface=%s method=%s, with error: %s", \
dbus_message_get_destination(msg), \
dbus_message_get_path(msg), \
dbus_message_get_interface(msg), \
dbus_message_get_member(msg), \
errs)
if (callback) {
DBusPendingCall *pending = NULL;
if (block) {
DBusError error;
dbus_error_init(&error);
RAII_MSG(reply, dbus_connection_send_with_reply_and_block(session_bus, msg, timeout, &error));
if (dbus_error_is_set(&error)) {
callback(reply, &error, user_data);
dbus_error_free(&error);
return false;
} else if (reply) {
callback(reply, NULL, user_data);
} else return false;
} else if (dbus_connection_send_with_reply(conn, msg, &pending, timeout)) {
MethodResponse *res = malloc(sizeof(MethodResponse));
if (!res) return false;
res->callback = callback;
res->user_data = user_data;
dbus_pending_call_set_notify(pending, method_reply_received, res, free);
retval = true;
} else {
REPORT("out of memory");
}
} else {
if (dbus_connection_send(conn, msg, NULL)) {
retval = true;
} else {
REPORT("out of memory");
}
}
return retval;
#undef REPORT
}
static bool
call_method(
DBusConnection *conn,
const char *node,
const char *path,
const char *interface,
const char *method,
int timeout,
dbus_pending_callback callback,
void *user_data,
bool blocking,
va_list ap) {
if (!conn || !path) return false;
RAII_MSG(msg, dbus_message_new_method_call(node, path, interface, method));
if (!msg) return false;
bool retval = false;
int firstarg = va_arg(ap, int);
if ((firstarg == DBUS_TYPE_INVALID) || dbus_message_append_args_valist(msg, firstarg, ap)) {
retval = call_method_with_msg(conn, msg, timeout, callback, user_data, blocking);
} else {
_glfwInputError(GLFW_PLATFORM_ERROR, "Failed to call DBUS method: %s on node: %s and interface: %s could not add arguments", method, node, interface);
}
return retval;
}
bool
glfw_dbus_call_method_with_reply(
DBusConnection *conn,
const char *node,
const char *path,
const char *interface,
const char *method,
int timeout,
dbus_pending_callback callback,
void *user_data,
...) {
bool retval;
va_list ap;
va_start(ap, user_data);
retval = call_method(conn, node, path, interface, method, timeout, callback, user_data, false, ap);
va_end(ap);
return retval;
}
bool
glfw_dbus_call_blocking_method(
DBusConnection *conn,
const char *node,
const char *path,
const char *interface,
const char *method,
int timeout,
dbus_pending_callback callback,
void *user_data,
...) {
bool retval;
va_list ap;
va_start(ap, user_data);
retval = call_method(conn, node, path, interface, method, timeout, callback, user_data, true, ap);
va_end(ap);
return retval;
}
bool
glfw_dbus_call_method_no_reply(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...) {
bool retval;
va_list ap;
va_start(ap, method);
retval = call_method(conn, node, path, interface, method, DBUS_TIMEOUT_USE_DEFAULT, NULL, NULL, false, ap);
va_end(ap);
return retval;
}
int
glfw_dbus_match_signal(DBusMessage *msg, const char *interface, ...) {
va_list ap;
va_start(ap, interface);
int ans = -1, num = -1;
while (1) {
num++;
const char *name = va_arg(ap, const char *);
if (!name) break;
if (dbus_message_is_signal(msg, interface, name)) {
ans = num;
break;
}
}
va_end(ap);
return ans;
}
static void
glfw_dbus_connect_to_session_bus(void) {
DBusError error;
dbus_error_init(&error);
if (session_bus) { dbus_connection_unref(session_bus); }
session_bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
if (dbus_error_is_set(&error)) {
report_error(&error, "Failed to connect to DBUS session bus");
session_bus = NULL;
return;
}
static const char *name = "session-bus";
if (!dbus_connection_set_watch_functions(session_bus, add_dbus_watch, remove_dbus_watch, toggle_dbus_watch, (void *)name, NULL)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Failed to set DBUS watches on connection to: %s", name);
dbus_connection_close(session_bus);
dbus_connection_unref(session_bus);
return;
}
if (!dbus_connection_set_timeout_functions(session_bus, add_dbus_timeout, remove_dbus_timeout, toggle_dbus_timeout, (void *)name, NULL)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Failed to set DBUS timeout functions on connection to: %s", name);
dbus_connection_close(session_bus);
dbus_connection_unref(session_bus);
return;
}
}
DBusConnection *
glfw_dbus_session_bus(void) {
if (!session_bus) glfw_dbus_connect_to_session_bus();
return session_bus;
}
+79
View File
@@ -0,0 +1,79 @@
//========================================================================
// GLFW 3.4 XKB - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2018 Kovid Goyal <kovid@kovidgoyal.net>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#pragma once
#include <dbus/dbus.h>
#include "backend_utils.h"
static inline void
cleanup_msg(void *p) {
DBusMessage *m = *(DBusMessage **)p;
if (m) dbus_message_unref(m);
m = NULL;
}
#define RAII_MSG(name, initializer) __attribute__((cleanup(cleanup_msg))) DBusMessage *name = initializer
typedef void (*dbus_pending_callback)(DBusMessage *msg, const DBusError *err, void *data);
typedef struct {
EventLoopData *eld;
} _GLFWDBUSData;
bool glfw_dbus_init(_GLFWDBUSData *dbus, EventLoopData *eld);
void glfw_dbus_terminate(_GLFWDBUSData *dbus);
DBusConnection *glfw_dbus_connect_to(const char *path, const char *err_msg, const char *name, bool register_on_bus);
void glfw_dbus_close_connection(DBusConnection *conn);
bool call_method_with_msg(DBusConnection *conn, DBusMessage *msg, int timeout, dbus_pending_callback callback, void *user_data, bool block);
bool glfw_dbus_call_method_no_reply(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...);
bool glfw_dbus_call_method_with_reply(
DBusConnection *conn,
const char *node,
const char *path,
const char *interface,
const char *method,
int timeout_ms,
dbus_pending_callback callback,
void *user_data,
...);
bool glfw_dbus_call_blocking_method(
DBusConnection *conn,
const char *node,
const char *path,
const char *interface,
const char *method,
int timeout,
dbus_pending_callback callback,
void *user_data,
...);
void glfw_dbus_dispatch(DBusConnection *);
void glfw_dbus_session_bus_dispatch(void);
bool glfw_dbus_session_bus_read_write_dispatch(int timeout_ms);
bool glfw_dbus_get_args(DBusMessage *msg, const char *failmsg, ...);
int glfw_dbus_match_signal(DBusMessage *msg, const char *interface, ...);
DBusConnection *glfw_dbus_session_bus(void);
+642
View File
@@ -0,0 +1,642 @@
//========================================================================
// GLFW 3.4 EGL - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// Please use C89 style variable declarations in this file because VS 2010
//========================================================================
#include "internal.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
// Return a description of the specified EGL error
//
static const char *
getEGLErrorString(EGLint error) {
switch (error) {
case EGL_SUCCESS: return "Success";
case EGL_NOT_INITIALIZED: return "EGL is not or could not be initialized";
case EGL_BAD_ACCESS: return "EGL cannot access a requested resource";
case EGL_BAD_ALLOC: return "EGL failed to allocate resources for the requested operation";
case EGL_BAD_ATTRIBUTE: return "An unrecognized attribute or attribute value was passed in the attribute list";
case EGL_BAD_CONTEXT: return "An EGLContext argument does not name a valid EGL rendering context";
case EGL_BAD_CONFIG: return "An EGLConfig argument does not name a valid EGL frame buffer configuration";
case EGL_BAD_CURRENT_SURFACE: return "The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid";
case EGL_BAD_DISPLAY: return "An EGLDisplay argument does not name a valid EGL display connection";
case EGL_BAD_SURFACE: return "An EGLSurface argument does not name a valid surface configured for GL rendering";
case EGL_BAD_MATCH: return "Arguments are inconsistent";
case EGL_BAD_PARAMETER: return "One or more argument values are invalid";
case EGL_BAD_NATIVE_PIXMAP: return "A NativePixmapType argument does not refer to a valid native pixmap";
case EGL_BAD_NATIVE_WINDOW: return "A NativeWindowType argument does not refer to a valid native window";
case EGL_CONTEXT_LOST: return "The application must destroy all contexts and reinitialise";
default: return "ERROR: UNKNOWN EGL ERROR";
}
}
#ifdef _GLFW_X11
// Returns the specified attribute of the specified EGLConfig
//
static int
getEGLConfigAttrib(EGLConfig config, int attrib) {
int value;
eglGetConfigAttrib(_glfw.egl.display, config, attrib, &value);
return value;
}
#endif
// Return the EGLConfig most closely matching the specified hints
//
static bool
chooseEGLConfig(const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *desired, EGLConfig *result) {
EGLConfig configs[512];
int i = 0, nativeCount = 0, ans_idx = 0;
EGLint attributes[64];
#define ATTR(k, v) \
{ \
attributes[i++] = k; \
attributes[i++] = v; \
}
ATTR(EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER);
ATTR(EGL_SURFACE_TYPE, EGL_WINDOW_BIT);
if (ctxconfig->client == GLFW_OPENGL_ES_API) {
if (ctxconfig->major == 1) ATTR(EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT)
else ATTR(EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT);
} else if (ctxconfig->client == GLFW_OPENGL_API) ATTR(EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT);
if (desired->samples > 0) ATTR(EGL_SAMPLES, desired->samples);
if (desired->depthBits > 0) ATTR(EGL_DEPTH_SIZE, desired->depthBits);
if (desired->stencilBits > 0) ATTR(EGL_STENCIL_SIZE, desired->stencilBits);
if (desired->redBits > 0) ATTR(EGL_RED_SIZE, desired->redBits);
if (desired->greenBits > 0) ATTR(EGL_GREEN_SIZE, desired->greenBits);
if (desired->blueBits > 0) ATTR(EGL_BLUE_SIZE, desired->blueBits);
if (desired->alphaBits > 0) ATTR(EGL_ALPHA_SIZE, desired->alphaBits);
ATTR(EGL_NONE, EGL_NONE);
#undef ATTR
if (!eglChooseConfig(_glfw.egl.display, attributes, configs, sizeof(configs) / sizeof(configs[0]), &nativeCount)) {
_glfwInputError(GLFW_API_UNAVAILABLE, "EGL: eglChooseConfig failed");
return false;
}
if (!nativeCount) {
_glfwInputError(GLFW_API_UNAVAILABLE, "EGL: No EGLConfigs returned");
return false;
}
for (i = 0; i < nativeCount; i++) {
#if defined(_GLFW_X11)
{
const EGLConfig n = configs[i];
XVisualInfo vi = {0};
// Only consider EGLConfigs with associated Visuals
vi.visualid = getEGLConfigAttrib(n, EGL_NATIVE_VISUAL_ID);
if (!vi.visualid) continue;
if (desired->transparent) {
int count;
XVisualInfo *vis = XGetVisualInfo(_glfw.x11.display, VisualIDMask, &vi, &count);
if (vis) {
bool transparent = _glfwIsVisualTransparentX11(vis[0].visual);
XFree(vis);
if (!transparent) continue;
}
}
}
#endif // _GLFW_X11
ans_idx = i;
break;
}
*result = configs[ans_idx];
return true;
}
static void
makeContextCurrentEGL(_GLFWwindow *window) {
if (window) {
if (!eglMakeCurrent(_glfw.egl.display, window->context.egl.surface, window->context.egl.surface, window->context.egl.handle)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to make context current: %s", getEGLErrorString(eglGetError()));
return;
}
} else {
if (!eglMakeCurrent(_glfw.egl.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to clear current context: %s", getEGLErrorString(eglGetError()));
return;
}
}
_glfwPlatformSetTls(&_glfw.contextSlot, window);
}
static void
swapBuffersEGL(_GLFWwindow *window) {
if (window != _glfwPlatformGetTls(&_glfw.contextSlot)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "EGL: The context must be current on the calling thread when swapping buffers");
return;
}
eglSwapBuffers(_glfw.egl.display, window->context.egl.surface);
}
static void
swapIntervalEGL(int interval) {
eglSwapInterval(_glfw.egl.display, interval);
}
static int
extensionSupportedEGL(const char *extension) {
const char *extensions = eglQueryString(_glfw.egl.display, EGL_EXTENSIONS);
if (extensions) {
if (_glfwStringInExtensionString(extension, extensions)) return true;
}
return false;
}
static GLFWglproc
getProcAddressEGL(const char *procname) {
_GLFWwindow *window = _glfwPlatformGetTls(&_glfw.contextSlot);
assert(window != NULL);
if (window->context.egl.client) {
GLFWglproc proc = NULL;
glfw_dlsym(proc, window->context.egl.client, procname);
if (proc) return proc;
}
return eglGetProcAddress(procname);
}
static void
destroyContextEGL(_GLFWwindow *window) {
#if defined(_GLFW_X11)
// NOTE: Do not unload libGL.so.1 while the X11 display is still open,
// as it will make XCloseDisplay segfault
if (window->context.client != GLFW_OPENGL_API)
#endif // _GLFW_X11
{
if (window->context.egl.client) {
_glfw_dlclose(window->context.egl.client);
window->context.egl.client = NULL;
}
}
if (window->context.egl.surface) {
eglDestroySurface(_glfw.egl.display, window->context.egl.surface);
window->context.egl.surface = EGL_NO_SURFACE;
}
if (window->context.egl.handle) {
eglDestroyContext(_glfw.egl.display, window->context.egl.handle);
window->context.egl.handle = EGL_NO_CONTEXT;
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Initialize EGL
//
bool
_glfwInitEGL(void) {
int i;
EGLint *attribs = NULL;
const char *extensions;
const char *sonames[] = {
#if defined(_GLFW_EGL_LIBRARY)
_GLFW_EGL_LIBRARY,
#elif defined(_GLFW_WIN32)
"libEGL.dll",
"EGL.dll",
#elif defined(_GLFW_COCOA)
"libEGL.dylib",
#elif defined(__CYGWIN__)
"libEGL-1.so",
#else
"libEGL.so.1",
#endif
NULL};
if (_glfw.egl.handle) return true;
for (i = 0; sonames[i]; i++) {
_glfw.egl.handle = _glfw_dlopen(sonames[i]);
if (_glfw.egl.handle) break;
}
if (!_glfw.egl.handle) {
_glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Library not found");
return false;
}
_glfw.egl.prefix = (strncmp(sonames[i], "lib", 3) == 0);
glfw_dlsym(_glfw.egl.GetConfigAttrib, _glfw.egl.handle, "eglGetConfigAttrib");
glfw_dlsym(_glfw.egl.GetConfigs, _glfw.egl.handle, "eglGetConfigs");
glfw_dlsym(_glfw.egl.ChooseConfig, _glfw.egl.handle, "eglChooseConfig");
glfw_dlsym(_glfw.egl.GetDisplay, _glfw.egl.handle, "eglGetDisplay");
glfw_dlsym(_glfw.egl.GetError, _glfw.egl.handle, "eglGetError");
glfw_dlsym(_glfw.egl.Initialize, _glfw.egl.handle, "eglInitialize");
glfw_dlsym(_glfw.egl.Terminate, _glfw.egl.handle, "eglTerminate");
glfw_dlsym(_glfw.egl.BindAPI, _glfw.egl.handle, "eglBindAPI");
glfw_dlsym(_glfw.egl.CreateContext, _glfw.egl.handle, "eglCreateContext");
glfw_dlsym(_glfw.egl.DestroySurface, _glfw.egl.handle, "eglDestroySurface");
glfw_dlsym(_glfw.egl.DestroyContext, _glfw.egl.handle, "eglDestroyContext");
glfw_dlsym(_glfw.egl.CreateWindowSurface, _glfw.egl.handle, "eglCreateWindowSurface");
glfw_dlsym(_glfw.egl.MakeCurrent, _glfw.egl.handle, "eglMakeCurrent");
glfw_dlsym(_glfw.egl.SwapBuffers, _glfw.egl.handle, "eglSwapBuffers");
glfw_dlsym(_glfw.egl.SwapInterval, _glfw.egl.handle, "eglSwapInterval");
glfw_dlsym(_glfw.egl.QueryString, _glfw.egl.handle, "eglQueryString");
glfw_dlsym(_glfw.egl.QuerySurface, _glfw.egl.handle, "eglQuerySurface");
glfw_dlsym(_glfw.egl.GetProcAddress, _glfw.egl.handle, "eglGetProcAddress");
if (!_glfw.egl.GetConfigAttrib || !_glfw.egl.GetConfigs || !_glfw.egl.ChooseConfig || !_glfw.egl.GetDisplay || !_glfw.egl.GetError ||
!_glfw.egl.Initialize || !_glfw.egl.Terminate || !_glfw.egl.BindAPI || !_glfw.egl.CreateContext || !_glfw.egl.DestroySurface ||
!_glfw.egl.DestroyContext || !_glfw.egl.CreateWindowSurface || !_glfw.egl.MakeCurrent || !_glfw.egl.SwapBuffers || !_glfw.egl.SwapInterval ||
!_glfw.egl.QueryString || !_glfw.egl.GetProcAddress) {
_glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to load required entry points");
_glfwTerminateEGL();
return false;
}
extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if (extensions && eglGetError() == EGL_SUCCESS) _glfw.egl.EXT_client_extensions = true;
if (_glfw.egl.EXT_client_extensions) {
_glfw.egl.EXT_platform_base = _glfwStringInExtensionString("EGL_EXT_platform_base", extensions);
_glfw.egl.EXT_platform_x11 = _glfwStringInExtensionString("EGL_EXT_platform_x11", extensions);
_glfw.egl.EXT_platform_wayland = _glfwStringInExtensionString("EGL_EXT_platform_wayland", extensions);
_glfw.egl.ANGLE_platform_angle = _glfwStringInExtensionString("EGL_ANGLE_platform_angle", extensions);
_glfw.egl.ANGLE_platform_angle_opengl = _glfwStringInExtensionString("EGL_ANGLE_platform_angle_opengl", extensions);
_glfw.egl.ANGLE_platform_angle_d3d = _glfwStringInExtensionString("EGL_ANGLE_platform_angle_d3d", extensions);
_glfw.egl.ANGLE_platform_angle_vulkan = _glfwStringInExtensionString("EGL_ANGLE_platform_angle_vulkan", extensions);
_glfw.egl.ANGLE_platform_angle_metal = _glfwStringInExtensionString("EGL_ANGLE_platform_angle_metal", extensions);
}
if (_glfw.egl.EXT_platform_base) {
_glfw.egl.GetPlatformDisplayEXT = (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
_glfw.egl.CreatePlatformWindowSurfaceEXT = (PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)eglGetProcAddress("eglCreatePlatformWindowSurfaceEXT");
}
_glfw.egl.platform = _glfwPlatformGetEGLPlatform(&attribs);
_glfw.egl.display = EGL_NO_DISPLAY;
if (_glfw.egl.platform) { _glfw.egl.display = eglGetPlatformDisplayEXT(_glfw.egl.platform, _glfwPlatformGetEGLNativeDisplay(), attribs); }
free(attribs);
if (_glfw.egl.display == EGL_NO_DISPLAY) _glfw.egl.display = eglGetDisplay(_glfwPlatformGetEGLNativeDisplay());
EGLint egl_err;
if (_glfw.egl.display == EGL_NO_DISPLAY && (egl_err = eglGetError()) != EGL_SUCCESS) {
_glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Failed to get EGL display: %s", getEGLErrorString(egl_err));
_glfwTerminateEGL();
return false;
}
if (!eglInitialize(_glfw.egl.display, &_glfw.egl.major, &_glfw.egl.minor)) {
_glfwInputError(
GLFW_API_UNAVAILABLE,
"EGL: Failed to initialize EGL: %s display_present: %d egl_platform_present: %d",
getEGLErrorString(eglGetError()),
_glfw.egl.display != EGL_NO_DISPLAY,
_glfw.egl.platform != 0);
_glfwTerminateEGL();
return false;
}
_glfw.egl.KHR_create_context = extensionSupportedEGL("EGL_KHR_create_context");
_glfw.egl.KHR_create_context_no_error = extensionSupportedEGL("EGL_KHR_create_context_no_error");
_glfw.egl.KHR_gl_colorspace = extensionSupportedEGL("EGL_KHR_gl_colorspace");
_glfw.egl.KHR_get_all_proc_addresses = extensionSupportedEGL("EGL_KHR_get_all_proc_addresses");
_glfw.egl.KHR_context_flush_control = extensionSupportedEGL("EGL_KHR_context_flush_control");
_glfw.egl.EXT_present_opaque = extensionSupportedEGL("EGL_EXT_present_opaque");
return true;
}
// Terminate EGL
//
void
_glfwTerminateEGL(void) {
if (_glfw.egl.display) {
eglTerminate(_glfw.egl.display);
_glfw.egl.display = EGL_NO_DISPLAY;
}
if (_glfw.egl.handle) {
_glfw_dlclose(_glfw.egl.handle);
_glfw.egl.handle = NULL;
}
}
#define setAttrib(a, v) \
{ \
assert(((size_t)index + 1) < sizeof(attribs) / sizeof(attribs[0])); \
attribs[index++] = a; \
attribs[index++] = v; \
}
// Create the OpenGL or OpenGL ES context
//
bool
_glfwCreateContextEGL(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) {
EGLint attribs[40];
EGLConfig config;
EGLContext share = NULL;
EGLNativeWindowType native;
int index = 0;
if (!_glfw.egl.display) {
_glfwInputError(GLFW_API_UNAVAILABLE, "EGL: API not available");
return false;
}
if (ctxconfig->share) share = ctxconfig->share->context.egl.handle;
if (!chooseEGLConfig(ctxconfig, fbconfig, &config)) {
_glfwInputError(GLFW_FORMAT_UNAVAILABLE, "EGL: Failed to find a suitable EGLConfig");
return false;
}
if (ctxconfig->client == GLFW_OPENGL_ES_API) {
if (!eglBindAPI(EGL_OPENGL_ES_API)) {
_glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Failed to bind OpenGL ES: %s", getEGLErrorString(eglGetError()));
return false;
}
} else {
if (!eglBindAPI(EGL_OPENGL_API)) {
_glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Failed to bind OpenGL: %s", getEGLErrorString(eglGetError()));
return false;
}
}
if (_glfw.egl.KHR_create_context) {
int mask = 0, flags = 0;
if (ctxconfig->client == GLFW_OPENGL_API) {
if (ctxconfig->forward) flags |= EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR;
if (ctxconfig->profile == GLFW_OPENGL_CORE_PROFILE) mask |= EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR;
else if (ctxconfig->profile == GLFW_OPENGL_COMPAT_PROFILE) mask |= EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR;
}
if (ctxconfig->debug) flags |= EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR;
if (ctxconfig->robustness) {
if (ctxconfig->robustness == GLFW_NO_RESET_NOTIFICATION) {
setAttrib(EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR, EGL_NO_RESET_NOTIFICATION_KHR);
} else if (ctxconfig->robustness == GLFW_LOSE_CONTEXT_ON_RESET) {
setAttrib(EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR, EGL_LOSE_CONTEXT_ON_RESET_KHR);
}
flags |= EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR;
}
if (ctxconfig->major != 1 || ctxconfig->minor != 0) {
setAttrib(EGL_CONTEXT_MAJOR_VERSION_KHR, ctxconfig->major);
setAttrib(EGL_CONTEXT_MINOR_VERSION_KHR, ctxconfig->minor);
}
if (ctxconfig->noerror) {
if (_glfw.egl.KHR_create_context_no_error) setAttrib(EGL_CONTEXT_OPENGL_NO_ERROR_KHR, true);
}
if (mask) setAttrib(EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR, mask);
if (flags) setAttrib(EGL_CONTEXT_FLAGS_KHR, flags);
} else {
if (ctxconfig->client == GLFW_OPENGL_ES_API) setAttrib(EGL_CONTEXT_CLIENT_VERSION, ctxconfig->major);
}
if (_glfw.egl.KHR_context_flush_control) {
if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_NONE) {
setAttrib(EGL_CONTEXT_RELEASE_BEHAVIOR_KHR, EGL_CONTEXT_RELEASE_BEHAVIOR_NONE_KHR);
} else if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_FLUSH) {
setAttrib(EGL_CONTEXT_RELEASE_BEHAVIOR_KHR, EGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR);
}
}
setAttrib(EGL_NONE, EGL_NONE);
window->context.egl.handle = eglCreateContext(_glfw.egl.display, config, share, attribs);
if (window->context.egl.handle == EGL_NO_CONTEXT) {
_glfwInputError(GLFW_VERSION_UNAVAILABLE, "EGL: Failed to create context: %s", getEGLErrorString(eglGetError()));
return false;
}
// Set up attributes for surface creation
index = 0;
if (fbconfig->sRGB) {
if (_glfw.egl.KHR_gl_colorspace) setAttrib(EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_SRGB_KHR);
}
// Disabled because it prevents transparency from working on NVIDIA drivers under Wayland
// https://github.com/kovidgoyal/kitty/issues/5479
// We anyway dont use the alpha bits for anything.
/* if (_glfw.egl.EXT_present_opaque) */
/* setAttrib(EGL_PRESENT_OPAQUE_EXT, !fbconfig->transparent); */
setAttrib(EGL_NONE, EGL_NONE);
native = _glfwPlatformGetEGLNativeWindow(window);
// HACK: ANGLE does not implement eglCreatePlatformWindowSurfaceEXT
// despite reporting EGL_EXT_platform_base
if (_glfw.egl.platform && _glfw.egl.platform != EGL_PLATFORM_ANGLE_ANGLE) {
window->context.egl.surface = eglCreatePlatformWindowSurfaceEXT(_glfw.egl.display, config, native, attribs);
} else {
window->context.egl.surface = eglCreateWindowSurface(_glfw.egl.display, config, native, attribs);
}
if (window->context.egl.surface == EGL_NO_SURFACE) {
_glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to create window surface: %s", getEGLErrorString(eglGetError()));
return false;
}
window->context.egl.config = config;
EGLint a = EGL_MIN_SWAP_INTERVAL;
if (!eglGetConfigAttrib(_glfw.egl.display, config, a, &a)) {
_glfwInputError(GLFW_VERSION_UNAVAILABLE, "EGL: could not check for non-blocking buffer swap with error: %s", getEGLErrorString(eglGetError()));
} else {
if (a > 0) { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "EGL: non-blocking swap buffers not available, minimum swap interval is: %d", a); }
}
// Load the appropriate client library
if (!_glfw.egl.KHR_get_all_proc_addresses) {
int i;
const char **sonames;
const char *es1sonames[] = {
#if defined(_GLFW_GLESV1_LIBRARY)
_GLFW_GLESV1_LIBRARY,
#elif defined(_GLFW_WIN32)
"GLESv1_CM.dll",
"libGLES_CM.dll",
#elif defined(_GLFW_COCOA)
"libGLESv1_CM.dylib",
#else
"libGLESv1_CM.so.1",
"libGLES_CM.so.1",
#endif
NULL};
const char *es2sonames[] = {
#if defined(_GLFW_GLESV2_LIBRARY)
_GLFW_GLESV2_LIBRARY,
#elif defined(_GLFW_WIN32)
"GLESv2.dll",
"libGLESv2.dll",
#elif defined(_GLFW_COCOA)
"libGLESv2.dylib",
#elif defined(__CYGWIN__)
"libGLESv2-2.so",
#else
"libGLESv2.so.2",
#endif
NULL};
const char *glsonames[] = {
#if defined(_GLFW_OPENGL_LIBRARY)
_GLFW_OPENGL_LIBRARY,
#elif defined(_GLFW_WIN32)
#elif defined(_GLFW_COCOA)
#else
"libGL.so.1",
#endif
NULL};
if (ctxconfig->client == GLFW_OPENGL_ES_API) {
if (ctxconfig->major == 1) sonames = es1sonames;
else sonames = es2sonames;
} else sonames = glsonames;
for (i = 0; sonames[i]; i++) {
// HACK: Match presence of lib prefix to increase chance of finding
// a matching pair in the jungle that is Win32 EGL/GLES
if (_glfw.egl.prefix != (strncmp(sonames[i], "lib", 3) == 0)) continue;
window->context.egl.client = _glfw_dlopen(sonames[i]);
if (window->context.egl.client) break;
}
if (!window->context.egl.client) {
_glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Failed to load client library");
return false;
}
}
window->context.makeCurrent = makeContextCurrentEGL;
window->context.swapBuffers = swapBuffersEGL;
window->context.swapInterval = swapIntervalEGL;
window->context.extensionSupported = extensionSupportedEGL;
window->context.getProcAddress = getProcAddressEGL;
window->context.destroy = destroyContextEGL;
return true;
}
#undef setAttrib
// Returns the Visual and depth of the chosen EGLConfig
//
#if defined(_GLFW_X11)
bool
_glfwChooseVisualEGL(const _GLFWwndconfig *wndconfig UNUSED, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, Visual **visual, int *depth) {
XVisualInfo *result;
XVisualInfo desired;
EGLConfig native;
EGLint visualID = 0, count = 0;
const long vimask = VisualScreenMask | VisualIDMask;
if (!chooseEGLConfig(ctxconfig, fbconfig, &native)) {
_glfwInputError(GLFW_FORMAT_UNAVAILABLE, "EGL: Failed to find a suitable EGLConfig");
return false;
}
eglGetConfigAttrib(_glfw.egl.display, native, EGL_NATIVE_VISUAL_ID, &visualID);
desired.screen = _glfw.x11.screen;
desired.visualid = visualID;
result = XGetVisualInfo(_glfw.x11.display, vimask, &desired, &count);
if (!result) {
_glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to retrieve Visual for EGLConfig");
return false;
}
*visual = result->visual;
*depth = result->depth;
XFree(result);
return true;
}
#endif // _GLFW_X11
//////////////////////////////////////////////////////////////////////////
////// GLFW native API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI EGLDisplay
glfwGetEGLDisplay(void) {
_GLFW_REQUIRE_INIT_OR_RETURN(EGL_NO_DISPLAY);
return _glfw.egl.display;
}
GLFWAPI EGLContext
glfwGetEGLContext(GLFWwindow *handle) {
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(window != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(EGL_NO_CONTEXT);
if (window->context.client == GLFW_NO_API) {
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL);
return EGL_NO_CONTEXT;
}
return window->context.egl.handle;
}
GLFWAPI EGLSurface
glfwGetEGLSurface(GLFWwindow *handle) {
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(window != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(EGL_NO_SURFACE);
if (window->context.client == GLFW_NO_API) {
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL);
return EGL_NO_SURFACE;
}
return window->context.egl.surface;
}
+228
View File
@@ -0,0 +1,228 @@
//========================================================================
// GLFW 3.4 EGL - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#if defined(_GLFW_WIN32)
#define EGLAPIENTRY __stdcall
#else
#define EGLAPIENTRY
#endif
#define EGL_SUCCESS 0x3000
#define EGL_NOT_INITIALIZED 0x3001
#define EGL_BAD_ACCESS 0x3002
#define EGL_BAD_ALLOC 0x3003
#define EGL_BAD_ATTRIBUTE 0x3004
#define EGL_BAD_CONFIG 0x3005
#define EGL_BAD_CONTEXT 0x3006
#define EGL_BAD_CURRENT_SURFACE 0x3007
#define EGL_BAD_DISPLAY 0x3008
#define EGL_BAD_MATCH 0x3009
#define EGL_BAD_NATIVE_PIXMAP 0x300a
#define EGL_BAD_NATIVE_WINDOW 0x300b
#define EGL_BAD_PARAMETER 0x300c
#define EGL_BAD_SURFACE 0x300d
#define EGL_CONTEXT_LOST 0x300e
#define EGL_COLOR_BUFFER_TYPE 0x303f
#define EGL_RGB_BUFFER 0x308e
#define EGL_SURFACE_TYPE 0x3033
#define EGL_WINDOW_BIT 0x0004
#define EGL_RENDERABLE_TYPE 0x3040
#define EGL_OPENGL_ES_BIT 0x0001
#define EGL_OPENGL_ES2_BIT 0x0004
#define EGL_OPENGL_BIT 0x0008
#define EGL_ALPHA_SIZE 0x3021
#define EGL_BLUE_SIZE 0x3022
#define EGL_GREEN_SIZE 0x3023
#define EGL_RED_SIZE 0x3024
#define EGL_DEPTH_SIZE 0x3025
#define EGL_STENCIL_SIZE 0x3026
#define EGL_SAMPLES 0x3031
#define EGL_OPENGL_ES_API 0x30a0
#define EGL_OPENGL_API 0x30a2
#define EGL_NONE 0x3038
#define EGL_EXTENSIONS 0x3055
#define EGL_CONTEXT_CLIENT_VERSION 0x3098
#define EGL_NATIVE_VISUAL_ID 0x302e
#define EGL_NO_SURFACE ((EGLSurface)0)
#define EGL_NO_DISPLAY ((EGLDisplay)0)
#define EGL_NO_CONTEXT ((EGLContext)0)
#define EGL_DEFAULT_DISPLAY ((EGLNativeDisplayType)0)
#define EGL_MIN_SWAP_INTERVAL 0x303B
#define EGL_MAX_SWAP_INTERVAL 0x303C
#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR 0x00000002
#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR 0x00000001
#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR 0x00000002
#define EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR 0x00000001
#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR 0x31bd
#define EGL_NO_RESET_NOTIFICATION_KHR 0x31be
#define EGL_LOSE_CONTEXT_ON_RESET_KHR 0x31bf
#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR 0x00000004
#define EGL_CONTEXT_MAJOR_VERSION_KHR 0x3098
#define EGL_CONTEXT_MINOR_VERSION_KHR 0x30fb
#define EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR 0x30fd
#define EGL_CONTEXT_FLAGS_KHR 0x30fc
#define EGL_CONTEXT_OPENGL_NO_ERROR_KHR 0x31b3
#define EGL_GL_COLORSPACE_KHR 0x309d
#define EGL_GL_COLORSPACE_SRGB_KHR 0x3089
#define EGL_CONTEXT_RELEASE_BEHAVIOR_KHR 0x2097
#define EGL_CONTEXT_RELEASE_BEHAVIOR_NONE_KHR 0
#define EGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR 0x2098
#define EGL_PLATFORM_X11_EXT 0x31d5
#define EGL_PLATFORM_WAYLAND_EXT 0x31d8
#define EGL_PLATFORM_ANGLE_ANGLE 0x3202
#define EGL_PLATFORM_ANGLE_TYPE_ANGLE 0x3203
#define EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE 0x320d
#define EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE 0x320e
#define EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE 0x3207
#define EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE 0x3208
#define EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE 0x3450
#define EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE 0x3489
#define EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE 0x348f
typedef int EGLint;
typedef unsigned int EGLBoolean;
typedef unsigned int EGLenum;
typedef void *EGLConfig;
typedef void *EGLContext;
typedef void *EGLDisplay;
typedef void *EGLSurface;
typedef void *EGLNativeDisplayType;
typedef void *EGLNativeWindowType;
// EGL function pointer typedefs
typedef EGLBoolean(EGLAPIENTRY *PFN_eglGetConfigAttrib)(EGLDisplay, EGLConfig, EGLint, EGLint *);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglGetConfigs)(EGLDisplay, EGLConfig *, EGLint, EGLint *);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglChooseConfig)(EGLDisplay, EGLint const *, EGLConfig *, EGLint, EGLint *);
typedef EGLDisplay(EGLAPIENTRY *PFN_eglGetDisplay)(EGLNativeDisplayType);
typedef EGLint(EGLAPIENTRY *PFN_eglGetError)(void);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglInitialize)(EGLDisplay, EGLint *, EGLint *);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglTerminate)(EGLDisplay);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglBindAPI)(EGLenum);
typedef EGLContext(EGLAPIENTRY *PFN_eglCreateContext)(EGLDisplay, EGLConfig, EGLContext, const EGLint *);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglDestroySurface)(EGLDisplay, EGLSurface);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglDestroyContext)(EGLDisplay, EGLContext);
typedef EGLSurface(EGLAPIENTRY *PFN_eglCreateWindowSurface)(EGLDisplay, EGLConfig, EGLNativeWindowType, const EGLint *);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglMakeCurrent)(EGLDisplay, EGLSurface, EGLSurface, EGLContext);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglSwapBuffers)(EGLDisplay, EGLSurface);
typedef EGLBoolean(EGLAPIENTRY *PFN_eglSwapInterval)(EGLDisplay, EGLint);
typedef const char *(EGLAPIENTRY *PFN_eglQueryString)(EGLDisplay, EGLint);
typedef const char *(EGLAPIENTRY *PFN_eglQuerySurface)(EGLDisplay, EGLSurface, EGLint, EGLint *);
typedef GLFWglproc(EGLAPIENTRY *PFN_eglGetProcAddress)(const char *);
#define eglGetConfigAttrib _glfw.egl.GetConfigAttrib
#define eglGetConfigs _glfw.egl.GetConfigs
#define eglChooseConfig _glfw.egl.ChooseConfig
#define eglGetDisplay _glfw.egl.GetDisplay
#define eglGetError _glfw.egl.GetError
#define eglInitialize _glfw.egl.Initialize
#define eglTerminate _glfw.egl.Terminate
#define eglBindAPI _glfw.egl.BindAPI
#define eglCreateContext _glfw.egl.CreateContext
#define eglDestroySurface _glfw.egl.DestroySurface
#define eglDestroyContext _glfw.egl.DestroyContext
#define eglCreateWindowSurface _glfw.egl.CreateWindowSurface
#define eglMakeCurrent _glfw.egl.MakeCurrent
#define eglSwapBuffers _glfw.egl.SwapBuffers
#define eglSwapInterval _glfw.egl.SwapInterval
#define eglQueryString _glfw.egl.QueryString
#define eglQuerySurface _glfw.egl.QuerySurface
#define eglGetProcAddress _glfw.egl.GetProcAddress
typedef EGLDisplay(EGLAPIENTRY *PFNEGLGETPLATFORMDISPLAYEXTPROC)(EGLenum, void *, const EGLint *);
typedef EGLSurface(EGLAPIENTRY *PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)(EGLDisplay, EGLConfig, void *, const EGLint *);
#define eglGetPlatformDisplayEXT _glfw.egl.GetPlatformDisplayEXT
#define eglCreatePlatformWindowSurfaceEXT _glfw.egl.CreatePlatformWindowSurfaceEXT
// EGL-specific per-context data
//
typedef struct _GLFWcontextEGL {
EGLConfig config;
EGLContext handle;
EGLSurface surface;
void *client;
} _GLFWcontextEGL;
// EGL-specific global data
//
typedef struct _GLFWlibraryEGL {
EGLenum platform;
EGLDisplay display;
EGLint major, minor;
bool prefix;
bool KHR_create_context;
bool KHR_create_context_no_error;
bool KHR_gl_colorspace;
bool KHR_get_all_proc_addresses;
bool KHR_context_flush_control;
bool EXT_client_extensions;
bool EXT_platform_base;
bool EXT_platform_x11;
bool EXT_platform_wayland;
bool EXT_present_opaque;
bool ANGLE_platform_angle;
bool ANGLE_platform_angle_opengl;
bool ANGLE_platform_angle_d3d;
bool ANGLE_platform_angle_vulkan;
bool ANGLE_platform_angle_metal;
void *handle;
PFN_eglGetConfigAttrib GetConfigAttrib;
PFN_eglGetConfigs GetConfigs;
PFN_eglChooseConfig ChooseConfig;
PFN_eglGetDisplay GetDisplay;
PFN_eglGetError GetError;
PFN_eglInitialize Initialize;
PFN_eglTerminate Terminate;
PFN_eglBindAPI BindAPI;
PFN_eglCreateContext CreateContext;
PFN_eglDestroySurface DestroySurface;
PFN_eglDestroyContext DestroyContext;
PFN_eglCreateWindowSurface CreateWindowSurface;
PFN_eglMakeCurrent MakeCurrent;
PFN_eglSwapBuffers SwapBuffers;
PFN_eglSwapInterval SwapInterval;
PFN_eglQueryString QueryString;
PFN_eglQuerySurface QuerySurface;
PFN_eglGetProcAddress GetProcAddress;
PFNEGLGETPLATFORMDISPLAYEXTPROC GetPlatformDisplayEXT;
PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC CreatePlatformWindowSurfaceEXT;
} _GLFWlibraryEGL;
bool _glfwInitEGL(void);
void _glfwTerminateEGL(void);
bool _glfwCreateContextEGL(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig);
#if defined(_GLFW_X11)
bool _glfwChooseVisualEGL(const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, Visual **visual, int *depth);
#endif /*_GLFW_X11*/
Executable
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import os
import re
import sys
_plat = sys.platform.lower()
is_linux = 'linux' in _plat
is_openbsd = 'openbsd' in _plat
class Arg:
def __init__(self, decl: str):
self.type, self.name = decl.rsplit(' ', 1)
self.type = self.type.strip()
self.name = self.name.strip()
while self.name.startswith('*'):
self.name = self.name[1:]
self.type = self.type + '*'
if '[' in self.name:
self.type += '[' + self.name.partition('[')[-1]
def __repr__(self) -> str:
return f'Arg({self.type}, {self.name})'
class Function:
def __init__(self, declaration: str, check_fail: bool = True):
self.check_fail = check_fail
m = re.match(r'(.+?)\s+(\**glfw[A-Z][a-zA-Z0-9]+)[(](.+)[)]$', declaration)
if m is None: # ]]]]]}})))
raise SystemExit('Failed to parse ' + repr(declaration))
self.restype = m.group(1).strip()
self.name = m.group(2)
if self.name.startswith('*'):
name = self.name.lstrip('*')
num_of_stars = len(self.name) - len(name)
self.name = name
self.restype += '*' * num_of_stars
args = m.group(3).strip().split(',')
args = [x.strip() for x in args]
self.args = []
for a in args:
if a == 'void':
continue
self.args.append(Arg(a))
if not self.args:
self.args = [Arg('void v')]
def declaration(self) -> str:
return 'typedef {restype} (*{name}_func)({args});\nGFW_EXTERN {name}_func {name}_impl;\n#define {name} {name}_impl'.format(
restype=self.restype, name=self.name, args=', '.join(a.type for a in self.args)
)
def load(self) -> str:
ans = f'*(void **) (&{self.name}_impl) = dlsym(handle, "{self.name}");'
ans += f'\n if ({self.name}_impl == NULL) '
if self.check_fail:
ans += f'fail("Failed to load glfw function {self.name} with error: %s", dlerror());'
else:
ans += 'dlerror(); // clear error indicator'
return ans
def generate_wrappers(glfw_header: str) -> None:
with open(glfw_header) as f:
src = f.read()
functions = []
first = None
for m in re.finditer(r'^GLFWAPI\s+(.+?\));\s*$', src, flags=re.MULTILINE | re.DOTALL):
if first is None:
first = m.start()
decl = m.group(1).replace('\n', ' ')
if 'VkInstance' in decl:
continue
functions.append(Function(decl))
for line in """\
void* glfwGetCocoaWindow(GLFWwindow* window)
void* glfwGetNSGLContext(GLFWwindow *window)
uint32_t glfwGetCocoaMonitor(GLFWmonitor* monitor)
GLFWcocoatextinputfilterfun glfwSetCocoaTextInputFilter(GLFWwindow* window, GLFWcocoatextinputfilterfun callback)
GLFWhandleurlopen glfwSetCocoaURLOpenCallback(GLFWhandleurlopen callback)
GLFWcocoatogglefullscreenfun glfwSetCocoaToggleFullscreenIntercept(GLFWwindow *window, GLFWcocoatogglefullscreenfun callback)
GLFWapplicationshouldhandlereopenfun glfwSetApplicationShouldHandleReopen(GLFWapplicationshouldhandlereopenfun callback)
GLFWapplicationwillfinishlaunchingfun glfwSetApplicationWillFinishLaunching(GLFWapplicationwillfinishlaunchingfun callback)
uint32_t glfwGetCocoaKeyEquivalent(uint32_t glfw_key, int glfw_mods, int* cocoa_mods)
void glfwCocoaRequestRenderFrame(GLFWwindow *w, GLFWcocoarenderframefun callback)
bool glfwCocoaRecreateGLDrawable(GLFWwindow *w)
GLFWcocoarenderframefun glfwCocoaSetWindowResizeCallback(GLFWwindow *w, GLFWcocoarenderframefun callback)
void* glfwGetX11Display(void)
unsigned long glfwGetX11Window(GLFWwindow* window)
void glfwSetPrimarySelectionString(GLFWwindow* window, const char* string)
void glfwCocoaCycleThroughOSWindows(bool backwards)
void glfwCocoaSetWindowChrome(GLFWwindow* window, unsigned int color, bool use_system_color, unsigned int system_color,\
int background_blur, unsigned int hide_window_decorations, bool show_text_in_titlebar, int color_space, float background_opacity, bool resizable)
void glfwCocoaRegisterMIMETypes(GLFWwindow *window, const char **mimes, size_t count)
const char* glfwCocoaPreserveDroppedFilePromises(GLFWwindow *window)
void glfwCocoaSetWindowLevel(GLFWwindow *window, const char *level_spec)
const char* glfwGetPrimarySelectionString(GLFWwindow* window, void)
int glfwGetNativeKeyForName(const char* key_name, int case_sensitive)
void glfwRequestWaylandFrameEvent(GLFWwindow *handle, unsigned long long id, GLFWwaylandframecallbackfunc callback)
void glfwWaylandActivateWindow(GLFWwindow *handle, const char *activation_token)
const char* glfwWaylandMissingCapabilities(void)
void glfwWaylandRunWithActivationToken(GLFWwindow *handle, GLFWactivationcallback cb, void *cb_data)
bool glfwWaylandSetTitlebarColor(GLFWwindow *handle, uint32_t color, bool use_system_color)
void glfwWaylandSetTitlebarHidden(GLFWwindow *handle, bool hidden)
void glfwWaylandSetInitialWindowSizeCallback(GLFWwaylandinitialsizefun callback)
void glfwWaylandRedrawCSDWindowTitle(GLFWwindow *handle)
bool glfwWaylandIsWindowFullyCreated(GLFWwindow *handle)
bool glfwWaylandBeep(GLFWwindow *handle)
pid_t glfwWaylandCompositorPID(void)
double glfwGetWaylandCurrentMonitorFractionalScale(void)
void glfwConfigureMomentumScroller(double friction, double min_velocity, double max_velocity, unsigned timer_interval)
void glfwFeedMomentumScroller(GLFWwindow *window, double dx, double dy, int keyboard_modifiers, bool stopped, monotonic_t timestamp)
void glfwCancelMomentumScroll(void)
unsigned long long glfwDBusUserNotify(const GLFWDBUSNotificationData *n, GLFWDBusnotificationcreatedfun callback, void *data)
void glfwDBusSetUserNotificationHandler(GLFWDBusnotificationactivatedfun handler)
bool glfwDBusMonitorSessionState(GLFWDBussessionstatefun callback)
int glfwSetX11LaunchCommand(GLFWwindow *handle, char **argv, int argc)
bool glfwWaylandCreateVirtualDevices(void)
void glfwWaylandInjectMouseMotionAbsolute(unsigned int x, unsigned int y, unsigned int x_extent, unsigned int y_extent)
void glfwWaylandInjectMouseButton(int button, int action)
void glfwWaylandInjectKey(int key, int action, int mods)
""".splitlines():
if line:
functions.append(Function(line.strip(), check_fail=False))
declarations = [f.declaration() for f in functions]
p = src.find(' * GLFW API tokens')
p = src.find('*/', p)
preamble = src[p + 2 : first]
header = """\
//
// THIS FILE IS GENERATED BY glfw.py
//
// SAVE YOURSELF SOME TIME, DO NOT MANUALLY EDIT
//
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "monotonic.h"
#ifndef GFW_EXTERN
#define GFW_EXTERN extern
#endif
{}
typedef int (* GLFWcocoatextinputfilterfun)(int,int,unsigned int,unsigned long);
typedef bool (* GLFWapplicationshouldhandlereopenfun)(int);
typedef bool (* GLFWhandleurlopen)(const char*);
typedef void (* GLFWapplicationwillfinishlaunchingfun)(bool);
typedef bool (* GLFWcocoatogglefullscreenfun)(GLFWwindow*);
typedef void (* GLFWcocoarenderframefun)(GLFWwindow*);
typedef void (*GLFWwaylandframecallbackfunc)(unsigned long long id);
typedef void (*GLFWDBusnotificationcreatedfun)(unsigned long long, uint32_t, void*);
typedef void (*GLFWDBusnotificationactivatedfun)(uint32_t, int, const char*);
typedef void (*GLFWDBussessionstatefun)(uint32_t);
{}
const char* load_glfw(const char* path);
""".format(preamble, '\n\n'.join(declarations))
with open('../kitty/glfw-wrapper.h', 'w') as f:
f.write(header)
code = """
// generated by glfw.py DO NOT edit
#define GFW_EXTERN
#include "data-types.h"
#include "glfw-wrapper.h"
#include <dlfcn.h>
static void* handle = NULL;
#define fail(msg, ...) { snprintf(buf, sizeof(buf), msg, __VA_ARGS__); return buf; }
const char*
load_glfw(const char* path) {
static char buf[2048];
handle = dlopen(path, RTLD_LAZY);
if (handle == NULL) fail("Failed to dlopen %s with error: %s", path, dlerror());
dlerror();
LOAD
return NULL;
}
void
unload_glfw(void) {
if (handle) { dlclose(handle); handle = NULL; }
}
""".replace('LOAD', '\n\n '.join(f.load() for f in functions))
with open('../kitty/glfw-wrapper.c', 'w') as f:
f.write(code)
def main() -> None:
import subprocess
af = os.path.abspath('autoformat')
os.chdir(os.path.dirname(os.path.abspath(__file__)))
generate_wrappers('glfw3.h')
subprocess.check_call([af])
if __name__ == '__main__':
main()
+6078
View File
File diff suppressed because it is too large. Load diff
+546
View File
@@ -0,0 +1,546 @@
//========================================================================
// GLFW 3.4 GLX - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#ifndef GLXBadProfileARB
#define GLXBadProfileARB 13
#endif
// Returns the specified attribute of the specified GLXFBConfig
//
static int
getGLXFBConfigAttrib(GLXFBConfig fbconfig, int attrib) {
int value;
glXGetFBConfigAttrib(_glfw.x11.display, fbconfig, attrib, &value);
return value;
}
static GLXFBConfig *
choose_fb_config(const _GLFWfbconfig *desired, bool trust_window_bit, int *nelements, bool use_best_color_depth) {
int attrib_list[64];
int pos = 0;
#define ATTR(x, y) \
{ \
attrib_list[pos++] = x; \
attrib_list[pos++] = y; \
}
ATTR(GLX_DOUBLEBUFFER, desired->doublebuffer ? True : False);
if (desired->stereo > 0) ATTR(GLX_STEREO, desired->stereo ? True : False);
if (desired->auxBuffers > 0) ATTR(GLX_AUX_BUFFERS, desired->auxBuffers);
if (_glfw.glx.ARB_multisample && desired->samples > 0) ATTR(GLX_SAMPLES, desired->samples);
if (desired->depthBits != GLFW_DONT_CARE) ATTR(GLX_DEPTH_SIZE, desired->depthBits);
if (desired->stencilBits != GLFW_DONT_CARE) ATTR(GLX_STENCIL_SIZE, desired->stencilBits);
if (use_best_color_depth) {
// we just ask for the highest available R+G+B+A color depth. This hopefully
// works with 10bit (r=10, g=10, b=19, a=2) visuals
ATTR(GLX_RED_SIZE, 1);
ATTR(GLX_GREEN_SIZE, 1);
ATTR(GLX_BLUE_SIZE, 1);
ATTR(GLX_ALPHA_SIZE, 1);
} else {
if (desired->redBits != GLFW_DONT_CARE) ATTR(GLX_RED_SIZE, desired->redBits);
if (desired->greenBits != GLFW_DONT_CARE) ATTR(GLX_GREEN_SIZE, desired->greenBits);
if (desired->blueBits != GLFW_DONT_CARE) ATTR(GLX_BLUE_SIZE, desired->blueBits);
if (desired->alphaBits != GLFW_DONT_CARE) ATTR(GLX_ALPHA_SIZE, desired->alphaBits);
}
if (desired->accumRedBits != GLFW_DONT_CARE) ATTR(GLX_ACCUM_RED_SIZE, desired->accumRedBits);
if (desired->accumGreenBits != GLFW_DONT_CARE) ATTR(GLX_ACCUM_GREEN_SIZE, desired->accumGreenBits);
if (desired->accumBlueBits != GLFW_DONT_CARE) ATTR(GLX_ACCUM_BLUE_SIZE, desired->accumBlueBits);
if (desired->accumAlphaBits != GLFW_DONT_CARE) ATTR(GLX_ACCUM_ALPHA_SIZE, desired->accumAlphaBits);
if (!trust_window_bit) ATTR(GLX_DRAWABLE_TYPE, 0);
ATTR(None, None);
return glXChooseFBConfig(_glfw.x11.display, _glfw.x11.screen, attrib_list, nelements);
#undef ATTR
}
// Return the GLXFBConfig most closely matching the specified hints
//
static bool
chooseGLXFBConfig(const _GLFWfbconfig *desired, GLXFBConfig *result) {
GLXFBConfig *nativeConfigs;
int i, nativeCount, ans_idx = 0;
const char *vendor;
bool trustWindowBit = true;
static _GLFWfbconfig prev_desired = {0};
static GLXFBConfig prev_result = 0;
if (prev_result != 0 && memcmp(&prev_desired, desired, sizeof(_GLFWfbconfig)) == 0) {
*result = prev_result;
return true;
}
prev_desired = *desired;
// HACK: This is a (hopefully temporary) workaround for Chromium
// (VirtualBox GL) not setting the window bit on any GLXFBConfigs
vendor = glXGetClientString(_glfw.x11.display, GLX_VENDOR);
if (vendor && strcmp(vendor, "Chromium") == 0) trustWindowBit = false;
nativeConfigs = choose_fb_config(desired, trustWindowBit, &nativeCount, false);
if (!nativeConfigs || !nativeCount) {
nativeConfigs = choose_fb_config(desired, trustWindowBit, &nativeCount, true);
if (!nativeConfigs || !nativeCount) {
_glfwInputError(GLFW_API_UNAVAILABLE, "GLX: No GLXFBConfigs returned");
return false;
}
}
for (i = 0; i < nativeCount; i++) {
const GLXFBConfig n = nativeConfigs[i];
bool transparency_matches = true, srgb_matches = true;
if (desired->transparent) {
transparency_matches = false;
XVisualInfo *vi = glXGetVisualFromFBConfig(_glfw.x11.display, n);
if (vi && _glfwIsVisualTransparentX11(vi->visual)) transparency_matches = true;
}
if (desired->sRGB && (_glfw.glx.ARB_framebuffer_sRGB || _glfw.glx.EXT_framebuffer_sRGB)) {
srgb_matches = getGLXFBConfigAttrib(n, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB) ? true : false;
}
if (transparency_matches && srgb_matches) {
ans_idx = i;
break;
}
}
*result = nativeConfigs[ans_idx];
prev_result = nativeConfigs[ans_idx];
XFree(nativeConfigs);
return true;
}
// Create the OpenGL context using legacy API
//
static GLXContext
createLegacyContextGLX(_GLFWwindow *window UNUSED, GLXFBConfig fbconfig, GLXContext share) {
return glXCreateNewContext(_glfw.x11.display, fbconfig, GLX_RGBA_TYPE, share, True);
}
static void
makeContextCurrentGLX(_GLFWwindow *window) {
if (window) {
if (!glXMakeCurrent(_glfw.x11.display, window->context.glx.window, window->context.glx.handle)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to make context current");
return;
}
} else {
if (!glXMakeCurrent(_glfw.x11.display, None, NULL)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to clear current context");
return;
}
}
_glfwPlatformSetTls(&_glfw.contextSlot, window);
}
static void
swapBuffersGLX(_GLFWwindow *window) {
glXSwapBuffers(_glfw.x11.display, window->context.glx.window);
}
static void
swapIntervalGLX(int interval) {
_GLFWwindow *window = _glfwPlatformGetTls(&_glfw.contextSlot);
if (_glfw.glx.EXT_swap_control) {
_glfw.glx.SwapIntervalEXT(_glfw.x11.display, window->context.glx.window, interval);
} else if (_glfw.glx.MESA_swap_control) _glfw.glx.SwapIntervalMESA(interval);
else if (_glfw.glx.SGI_swap_control) {
if (interval > 0) _glfw.glx.SwapIntervalSGI(interval);
}
}
static int
extensionSupportedGLX(const char *extension) {
const char *extensions = glXQueryExtensionsString(_glfw.x11.display, _glfw.x11.screen);
if (extensions) {
if (_glfwStringInExtensionString(extension, extensions)) return true;
}
return false;
}
static GLFWglproc
getProcAddressGLX(const char *procname) {
if (_glfw.glx.GetProcAddress) return _glfw.glx.GetProcAddress((const GLubyte *)procname);
else if (_glfw.glx.GetProcAddressARB) return _glfw.glx.GetProcAddressARB((const GLubyte *)procname);
else {
GLFWglproc ans = NULL;
glfw_dlsym(ans, _glfw.glx.handle, procname);
return ans;
}
}
static void
destroyContextGLX(_GLFWwindow *window) {
if (window->context.glx.window) {
glXDestroyWindow(_glfw.x11.display, window->context.glx.window);
window->context.glx.window = None;
}
if (window->context.glx.handle) {
glXDestroyContext(_glfw.x11.display, window->context.glx.handle);
window->context.glx.handle = NULL;
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Initialize GLX
//
bool
_glfwInitGLX(void) {
int i;
const char *sonames[] = {
#if defined(_GLFW_GLX_LIBRARY)
_GLFW_GLX_LIBRARY,
#elif defined(__CYGWIN__)
"libGL-1.so",
#else
"libGL.so.1",
"libGL.so",
#endif
NULL};
if (_glfw.glx.handle) return true;
for (i = 0; sonames[i]; i++) {
_glfw.glx.handle = _glfw_dlopen(sonames[i]);
if (_glfw.glx.handle) break;
}
if (!_glfw.glx.handle) {
_glfwInputError(GLFW_API_UNAVAILABLE, "GLX: Failed to load GLX");
return false;
}
glfw_dlsym(_glfw.glx.GetFBConfigs, _glfw.glx.handle, "glXGetFBConfigs");
glfw_dlsym(_glfw.glx.GetFBConfigAttrib, _glfw.glx.handle, "glXGetFBConfigAttrib");
glfw_dlsym(_glfw.glx.ChooseFBConfig, _glfw.glx.handle, "glXChooseFBConfig");
glfw_dlsym(_glfw.glx.GetClientString, _glfw.glx.handle, "glXGetClientString");
glfw_dlsym(_glfw.glx.QueryExtension, _glfw.glx.handle, "glXQueryExtension");
glfw_dlsym(_glfw.glx.QueryVersion, _glfw.glx.handle, "glXQueryVersion");
glfw_dlsym(_glfw.glx.DestroyContext, _glfw.glx.handle, "glXDestroyContext");
glfw_dlsym(_glfw.glx.MakeCurrent, _glfw.glx.handle, "glXMakeCurrent");
glfw_dlsym(_glfw.glx.SwapBuffers, _glfw.glx.handle, "glXSwapBuffers");
glfw_dlsym(_glfw.glx.QueryExtensionsString, _glfw.glx.handle, "glXQueryExtensionsString");
glfw_dlsym(_glfw.glx.CreateNewContext, _glfw.glx.handle, "glXCreateNewContext");
glfw_dlsym(_glfw.glx.CreateWindow, _glfw.glx.handle, "glXCreateWindow");
glfw_dlsym(_glfw.glx.DestroyWindow, _glfw.glx.handle, "glXDestroyWindow");
glfw_dlsym(_glfw.glx.GetProcAddress, _glfw.glx.handle, "glXGetProcAddress");
glfw_dlsym(_glfw.glx.GetProcAddressARB, _glfw.glx.handle, "glXGetProcAddressARB");
glfw_dlsym(_glfw.glx.GetVisualFromFBConfig, _glfw.glx.handle, "glXGetVisualFromFBConfig");
if (!_glfw.glx.GetFBConfigs || !_glfw.glx.GetFBConfigAttrib || !_glfw.glx.GetClientString || !_glfw.glx.QueryExtension || !_glfw.glx.QueryVersion ||
!_glfw.glx.DestroyContext || !_glfw.glx.MakeCurrent || !_glfw.glx.SwapBuffers || !_glfw.glx.QueryExtensionsString || !_glfw.glx.CreateNewContext ||
!_glfw.glx.CreateWindow || !_glfw.glx.DestroyWindow || !_glfw.glx.GetProcAddress || !_glfw.glx.GetProcAddressARB || !_glfw.glx.GetVisualFromFBConfig) {
_glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to load required entry points");
return false;
}
if (!glXQueryExtension(_glfw.x11.display, &_glfw.glx.errorBase, &_glfw.glx.eventBase)) {
_glfwInputError(GLFW_API_UNAVAILABLE, "GLX: GLX extension not found");
return false;
}
if (!glXQueryVersion(_glfw.x11.display, &_glfw.glx.major, &_glfw.glx.minor)) {
_glfwInputError(GLFW_API_UNAVAILABLE, "GLX: Failed to query GLX version");
return false;
}
if (_glfw.glx.major == 1 && _glfw.glx.minor < 3) {
_glfwInputError(GLFW_API_UNAVAILABLE, "GLX: GLX version 1.3 is required");
return false;
}
if (extensionSupportedGLX("GLX_EXT_swap_control")) {
_glfw.glx.SwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)getProcAddressGLX("glXSwapIntervalEXT");
if (_glfw.glx.SwapIntervalEXT) _glfw.glx.EXT_swap_control = true;
}
if (extensionSupportedGLX("GLX_SGI_swap_control")) {
_glfw.glx.SwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)getProcAddressGLX("glXSwapIntervalSGI");
if (_glfw.glx.SwapIntervalSGI) _glfw.glx.SGI_swap_control = true;
}
if (extensionSupportedGLX("GLX_MESA_swap_control")) {
_glfw.glx.SwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC)getProcAddressGLX("glXSwapIntervalMESA");
if (_glfw.glx.SwapIntervalMESA) _glfw.glx.MESA_swap_control = true;
}
if (extensionSupportedGLX("GLX_ARB_multisample")) _glfw.glx.ARB_multisample = true;
if (extensionSupportedGLX("GLX_ARB_framebuffer_sRGB")) _glfw.glx.ARB_framebuffer_sRGB = true;
if (extensionSupportedGLX("GLX_EXT_framebuffer_sRGB")) _glfw.glx.EXT_framebuffer_sRGB = true;
if (extensionSupportedGLX("GLX_ARB_create_context")) {
_glfw.glx.CreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)getProcAddressGLX("glXCreateContextAttribsARB");
if (_glfw.glx.CreateContextAttribsARB) _glfw.glx.ARB_create_context = true;
}
if (extensionSupportedGLX("GLX_ARB_create_context_robustness")) _glfw.glx.ARB_create_context_robustness = true;
if (extensionSupportedGLX("GLX_ARB_create_context_profile")) _glfw.glx.ARB_create_context_profile = true;
if (extensionSupportedGLX("GLX_EXT_create_context_es2_profile")) _glfw.glx.EXT_create_context_es2_profile = true;
if (extensionSupportedGLX("GLX_ARB_create_context_no_error")) _glfw.glx.ARB_create_context_no_error = true;
if (extensionSupportedGLX("GLX_ARB_context_flush_control")) _glfw.glx.ARB_context_flush_control = true;
return true;
}
// Terminate GLX
//
void
_glfwTerminateGLX(void) {
// NOTE: This function must not call any X11 functions, as it is called
// after XCloseDisplay (see _glfwPlatformTerminate for details)
if (_glfw.glx.handle) {
_glfw_dlclose(_glfw.glx.handle);
_glfw.glx.handle = NULL;
}
}
#define setAttrib(a, v) \
{ \
assert(((size_t)index + 1) < sizeof(attribs) / sizeof(attribs[0])); \
attribs[index++] = a; \
attribs[index++] = v; \
}
// Create the OpenGL or OpenGL ES context
//
bool
_glfwCreateContextGLX(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) {
int attribs[40];
GLXFBConfig native = NULL;
GLXContext share = NULL;
if (ctxconfig->share) share = ctxconfig->share->context.glx.handle;
if (!chooseGLXFBConfig(fbconfig, &native)) {
_glfwInputError(GLFW_FORMAT_UNAVAILABLE, "GLX: Failed to find a suitable GLXFBConfig");
return false;
}
if (ctxconfig->client == GLFW_OPENGL_ES_API) {
if (!_glfw.glx.ARB_create_context || !_glfw.glx.ARB_create_context_profile || !_glfw.glx.EXT_create_context_es2_profile) {
_glfwInputError(GLFW_API_UNAVAILABLE, "GLX: OpenGL ES requested but GLX_EXT_create_context_es2_profile is unavailable");
return false;
}
}
if (ctxconfig->forward) {
if (!_glfw.glx.ARB_create_context) {
_glfwInputError(GLFW_VERSION_UNAVAILABLE, "GLX: Forward compatibility requested but GLX_ARB_create_context_profile is unavailable");
return false;
}
}
if (ctxconfig->profile) {
if (!_glfw.glx.ARB_create_context || !_glfw.glx.ARB_create_context_profile) {
_glfwInputError(GLFW_VERSION_UNAVAILABLE, "GLX: An OpenGL profile requested but GLX_ARB_create_context_profile is unavailable");
return false;
}
}
_glfwGrabErrorHandlerX11();
if (_glfw.glx.ARB_create_context) {
int index = 0, mask = 0, flags = 0;
if (ctxconfig->client == GLFW_OPENGL_API) {
if (ctxconfig->forward) flags |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
if (ctxconfig->profile == GLFW_OPENGL_CORE_PROFILE) mask |= GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
else if (ctxconfig->profile == GLFW_OPENGL_COMPAT_PROFILE) mask |= GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
} else mask |= GLX_CONTEXT_ES2_PROFILE_BIT_EXT;
if (ctxconfig->debug) flags |= GLX_CONTEXT_DEBUG_BIT_ARB;
if (ctxconfig->robustness) {
if (_glfw.glx.ARB_create_context_robustness) {
if (ctxconfig->robustness == GLFW_NO_RESET_NOTIFICATION) {
setAttrib(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, GLX_NO_RESET_NOTIFICATION_ARB);
} else if (ctxconfig->robustness == GLFW_LOSE_CONTEXT_ON_RESET) {
setAttrib(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, GLX_LOSE_CONTEXT_ON_RESET_ARB);
}
flags |= GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB;
}
}
if (ctxconfig->release) {
if (_glfw.glx.ARB_context_flush_control) {
if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_NONE) {
setAttrib(GLX_CONTEXT_RELEASE_BEHAVIOR_ARB, GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB);
} else if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_FLUSH) {
setAttrib(GLX_CONTEXT_RELEASE_BEHAVIOR_ARB, GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB);
}
}
}
if (ctxconfig->noerror) {
if (_glfw.glx.ARB_create_context_no_error) setAttrib(GLX_CONTEXT_OPENGL_NO_ERROR_ARB, true);
}
// NOTE: Only request an explicitly versioned context when necessary, as
// explicitly requesting version 1.0 does not always return the
// highest version supported by the driver
if (ctxconfig->major != 1 || ctxconfig->minor != 0) {
setAttrib(GLX_CONTEXT_MAJOR_VERSION_ARB, ctxconfig->major);
setAttrib(GLX_CONTEXT_MINOR_VERSION_ARB, ctxconfig->minor);
}
if (mask) setAttrib(GLX_CONTEXT_PROFILE_MASK_ARB, mask);
if (flags) setAttrib(GLX_CONTEXT_FLAGS_ARB, flags);
setAttrib(None, None);
window->context.glx.handle = _glfw.glx.CreateContextAttribsARB(_glfw.x11.display, native, share, True, attribs);
// HACK: This is a fallback for broken versions of the Mesa
// implementation of GLX_ARB_create_context_profile that fail
// default 1.0 context creation with a GLXBadProfileARB error in
// violation of the extension spec
if (!window->context.glx.handle) {
if (_glfw.x11.errorCode == _glfw.glx.errorBase + GLXBadProfileARB && ctxconfig->client == GLFW_OPENGL_API &&
ctxconfig->profile == GLFW_OPENGL_ANY_PROFILE && ctxconfig->forward == false) {
window->context.glx.handle = createLegacyContextGLX(window, native, share);
}
}
} else {
window->context.glx.handle = createLegacyContextGLX(window, native, share);
}
_glfwReleaseErrorHandlerX11();
if (!window->context.glx.handle) {
_glfwInputErrorX11(GLFW_VERSION_UNAVAILABLE, "GLX: Failed to create context");
return false;
}
window->context.glx.window = glXCreateWindow(_glfw.x11.display, native, window->x11.handle, NULL);
if (!window->context.glx.window) {
_glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to create window");
return false;
}
window->context.makeCurrent = makeContextCurrentGLX;
window->context.swapBuffers = swapBuffersGLX;
window->context.swapInterval = swapIntervalGLX;
window->context.extensionSupported = extensionSupportedGLX;
window->context.getProcAddress = getProcAddressGLX;
window->context.destroy = destroyContextGLX;
return true;
}
#undef setAttrib
// Returns the Visual and depth of the chosen GLXFBConfig
//
bool
_glfwChooseVisualGLX(
const _GLFWwndconfig *wndconfig UNUSED, const _GLFWctxconfig *ctxconfig UNUSED, const _GLFWfbconfig *fbconfig, Visual **visual, int *depth) {
GLXFBConfig native;
XVisualInfo *result;
if (!chooseGLXFBConfig(fbconfig, &native)) {
_glfwInputError(GLFW_FORMAT_UNAVAILABLE, "GLX: Failed to find a suitable GLXFBConfig");
return false;
}
result = glXGetVisualFromFBConfig(_glfw.x11.display, native);
if (!result) {
_glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to retrieve Visual for GLXFBConfig");
return false;
}
*visual = result->visual;
*depth = result->depth;
XFree(result);
return true;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW native API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI GLXContext
glfwGetGLXContext(GLFWwindow *handle) {
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(window != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
if (window->context.client == GLFW_NO_API) {
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL);
return NULL;
}
return window->context.glx.handle;
}
GLFWAPI GLXWindow
glfwGetGLXWindow(GLFWwindow *handle) {
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(window != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(None);
if (window->context.client == GLFW_NO_API) {
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL);
return None;
}
return window->context.glx.window;
}
+176
View File
@@ -0,0 +1,176 @@
//========================================================================
// GLFW 3.4 GLX - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#define GLX_VENDOR 1
#define GLX_RGBA_BIT 0x00000001
#define GLX_WINDOW_BIT 0x00000001
#define GLX_DRAWABLE_TYPE 0x8010
#define GLX_RENDER_TYPE 0x8011
#define GLX_RGBA_TYPE 0x8014
#define GLX_DOUBLEBUFFER 5
#define GLX_STEREO 6
#define GLX_AUX_BUFFERS 7
#define GLX_RED_SIZE 8
#define GLX_GREEN_SIZE 9
#define GLX_BLUE_SIZE 10
#define GLX_ALPHA_SIZE 11
#define GLX_DEPTH_SIZE 12
#define GLX_STENCIL_SIZE 13
#define GLX_ACCUM_RED_SIZE 14
#define GLX_ACCUM_GREEN_SIZE 15
#define GLX_ACCUM_BLUE_SIZE 16
#define GLX_ACCUM_ALPHA_SIZE 17
#define GLX_SAMPLES 0x186a1
#define GLX_VISUAL_ID 0x800b
#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20b2
#define GLX_CONTEXT_DEBUG_BIT_ARB 0x00000001
#define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
#define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
#define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
#define GLX_CONTEXT_FLAGS_ARB 0x2094
#define GLX_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
#define GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
#define GLX_LOSE_CONTEXT_ON_RESET_ARB 0x8252
#define GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
#define GLX_NO_RESET_NOTIFICATION_ARB 0x8261
#define GLX_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097
#define GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0
#define GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098
#define GLX_CONTEXT_OPENGL_NO_ERROR_ARB 0x31b3
typedef XID GLXWindow;
typedef XID GLXDrawable;
typedef struct __GLXFBConfig *GLXFBConfig;
typedef struct __GLXcontext *GLXContext;
typedef void (*__GLXextproc)(void);
typedef int (*PFNGLXGETFBCONFIGATTRIBPROC)(Display *, GLXFBConfig, int, int *);
typedef GLXFBConfig *(*PFNGLXCHOOSEFBCONFIGPROC)(Display *, int, const int *, int *);
typedef const char *(*PFNGLXGETCLIENTSTRINGPROC)(Display *, int);
typedef Bool (*PFNGLXQUERYEXTENSIONPROC)(Display *, int *, int *);
typedef Bool (*PFNGLXQUERYVERSIONPROC)(Display *, int *, int *);
typedef void (*PFNGLXDESTROYCONTEXTPROC)(Display *, GLXContext);
typedef Bool (*PFNGLXMAKECURRENTPROC)(Display *, GLXDrawable, GLXContext);
typedef void (*PFNGLXSWAPBUFFERSPROC)(Display *, GLXDrawable);
typedef const char *(*PFNGLXQUERYEXTENSIONSSTRINGPROC)(Display *, int);
typedef GLXFBConfig *(*PFNGLXGETFBCONFIGSPROC)(Display *, int, int *);
typedef GLXContext (*PFNGLXCREATENEWCONTEXTPROC)(Display *, GLXFBConfig, int, GLXContext, Bool);
typedef __GLXextproc (*PFNGLXGETPROCADDRESSPROC)(const GLubyte *procName);
typedef void (*PFNGLXSWAPINTERVALEXTPROC)(Display *, GLXDrawable, int);
typedef XVisualInfo *(*PFNGLXGETVISUALFROMFBCONFIGPROC)(Display *, GLXFBConfig);
typedef GLXWindow (*PFNGLXCREATEWINDOWPROC)(Display *, GLXFBConfig, Window, const int *);
typedef void (*PFNGLXDESTROYWINDOWPROC)(Display *, GLXWindow);
typedef int (*PFNGLXSWAPINTERVALMESAPROC)(int);
typedef int (*PFNGLXSWAPINTERVALSGIPROC)(int);
typedef GLXContext (*PFNGLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *);
// libGL.so function pointer typedefs
#define glXGetFBConfigs _glfw.glx.GetFBConfigs
#define glXGetFBConfigAttrib _glfw.glx.GetFBConfigAttrib
#define glXChooseFBConfig _glfw.glx.ChooseFBConfig
#define glXGetClientString _glfw.glx.GetClientString
#define glXQueryExtension _glfw.glx.QueryExtension
#define glXQueryVersion _glfw.glx.QueryVersion
#define glXDestroyContext _glfw.glx.DestroyContext
#define glXMakeCurrent _glfw.glx.MakeCurrent
#define glXSwapBuffers _glfw.glx.SwapBuffers
#define glXQueryExtensionsString _glfw.glx.QueryExtensionsString
#define glXCreateNewContext _glfw.glx.CreateNewContext
#define glXGetVisualFromFBConfig _glfw.glx.GetVisualFromFBConfig
#define glXCreateWindow _glfw.glx.CreateWindow
#define glXDestroyWindow _glfw.glx.DestroyWindow
#define _GLFW_PLATFORM_CONTEXT_STATE _GLFWcontextGLX glx;
#define _GLFW_PLATFORM_LIBRARY_CONTEXT_STATE _GLFWlibraryGLX glx;
// GLX-specific per-context data
//
typedef struct _GLFWcontextGLX {
GLXContext handle;
GLXWindow window;
} _GLFWcontextGLX;
// GLX-specific global data
//
typedef struct _GLFWlibraryGLX {
int major, minor;
int eventBase;
int errorBase;
// dlopen handle for libGL.so.1
void *handle;
// GLX 1.3 functions
PFNGLXGETFBCONFIGSPROC GetFBConfigs;
PFNGLXGETFBCONFIGATTRIBPROC GetFBConfigAttrib;
PFNGLXCHOOSEFBCONFIGPROC ChooseFBConfig;
PFNGLXGETCLIENTSTRINGPROC GetClientString;
PFNGLXQUERYEXTENSIONPROC QueryExtension;
PFNGLXQUERYVERSIONPROC QueryVersion;
PFNGLXDESTROYCONTEXTPROC DestroyContext;
PFNGLXMAKECURRENTPROC MakeCurrent;
PFNGLXSWAPBUFFERSPROC SwapBuffers;
PFNGLXQUERYEXTENSIONSSTRINGPROC QueryExtensionsString;
PFNGLXCREATENEWCONTEXTPROC CreateNewContext;
PFNGLXGETVISUALFROMFBCONFIGPROC GetVisualFromFBConfig;
PFNGLXCREATEWINDOWPROC CreateWindow;
PFNGLXDESTROYWINDOWPROC DestroyWindow;
// GLX 1.4 and extension functions
PFNGLXGETPROCADDRESSPROC GetProcAddress;
PFNGLXGETPROCADDRESSPROC GetProcAddressARB;
PFNGLXSWAPINTERVALSGIPROC SwapIntervalSGI;
PFNGLXSWAPINTERVALEXTPROC SwapIntervalEXT;
PFNGLXSWAPINTERVALMESAPROC SwapIntervalMESA;
PFNGLXCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB;
bool SGI_swap_control;
bool EXT_swap_control;
bool MESA_swap_control;
bool ARB_multisample;
bool ARB_framebuffer_sRGB;
bool EXT_framebuffer_sRGB;
bool ARB_create_context;
bool ARB_create_context_profile;
bool ARB_create_context_robustness;
bool EXT_create_context_es2_profile;
bool ARB_create_context_no_error;
bool ARB_context_flush_control;
} _GLFWlibraryGLX;
bool _glfwInitGLX(void);
void _glfwTerminateGLX(void);
bool _glfwCreateContextGLX(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig);
void _glfwDestroyContextGLX(_GLFWwindow *window);
bool _glfwChooseVisualGLX(const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, Visual **visual, int *depth);
+571
View File
@@ -0,0 +1,571 @@
//========================================================================
// GLFW 3.4 XKB - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2018 Kovid Goyal <kovid@kovidgoyal.net>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
/* To test under X11 start IBUS as:
* ibus-daemon -drxR
* Setup the input sources you want with:
* ibus-setup
* Switch to the input source you want to test with:
* ibus engine name
* You can list available engines with:
* ibus list-engine
* Then run kitty as:
* GLFW_IM_MODULE=ibus kitty
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <limits.h>
#include "internal.h"
#include "ibus_glfw.h"
#define debug debug_input
static const char IBUS_SERVICE[] = "org.freedesktop.IBus";
static const char IBUS_PATH[] = "/org/freedesktop/IBus";
static const char IBUS_INTERFACE[] = "org.freedesktop.IBus";
static const char IBUS_INPUT_INTERFACE[] = "org.freedesktop.IBus.InputContext";
enum Capabilities {
IBUS_CAP_PREEDIT_TEXT = 1 << 0,
IBUS_CAP_AUXILIARY_TEXT = 1 << 1,
IBUS_CAP_LOOKUP_TABLE = 1 << 2,
IBUS_CAP_FOCUS = 1 << 3,
IBUS_CAP_PROPERTY = 1 << 4,
IBUS_CAP_SURROUNDING_TEXT = 1 << 5
};
typedef enum {
IBUS_SHIFT_MASK = 1 << 0,
IBUS_LOCK_MASK = 1 << 1,
IBUS_CONTROL_MASK = 1 << 2,
IBUS_MOD1_MASK = 1 << 3,
IBUS_MOD2_MASK = 1 << 4,
IBUS_MOD3_MASK = 1 << 5,
IBUS_MOD4_MASK = 1 << 6,
IBUS_MOD5_MASK = 1 << 7,
IBUS_BUTTON1_MASK = 1 << 8,
IBUS_BUTTON2_MASK = 1 << 9,
IBUS_BUTTON3_MASK = 1 << 10,
IBUS_BUTTON4_MASK = 1 << 11,
IBUS_BUTTON5_MASK = 1 << 12,
/* The next few modifiers are used by XKB, so we skip to the end.
* Bits 15 - 23 are currently unused. Bit 29 is used internally.
*/
/* ibus mask */
IBUS_HANDLED_MASK = 1 << 24,
IBUS_FORWARD_MASK = 1 << 25,
IBUS_IGNORED_MASK = IBUS_FORWARD_MASK,
IBUS_SUPER_MASK = 1 << 26,
IBUS_HYPER_MASK = 1 << 27,
IBUS_META_MASK = 1 << 28,
IBUS_RELEASE_MASK = 1 << 30,
IBUS_MODIFIER_MASK = 0x5f001fff
} IBusModifierType;
static uint32_t
ibus_key_state_from_glfw(unsigned int glfw_modifiers, int action) {
uint32_t ans = action == GLFW_RELEASE ? IBUS_RELEASE_MASK : 0;
#define M(g, i) \
if (glfw_modifiers & GLFW_MOD_##g) ans |= i
M(SHIFT, IBUS_SHIFT_MASK);
M(CAPS_LOCK, IBUS_LOCK_MASK);
M(CONTROL, IBUS_CONTROL_MASK);
M(ALT, IBUS_MOD1_MASK);
M(NUM_LOCK, IBUS_MOD2_MASK);
M(SUPER, IBUS_MOD4_MASK);
/* To do: figure out how to get super/hyper/meta */
#undef M
return ans;
}
static unsigned int
glfw_modifiers_from_ibus_state(uint32_t ibus_key_state) {
unsigned int ans = 0;
#define M(g, i) \
if (ibus_key_state & i) ans |= GLFW_MOD_##g
M(SHIFT, IBUS_SHIFT_MASK);
M(CAPS_LOCK, IBUS_LOCK_MASK);
M(CONTROL, IBUS_CONTROL_MASK);
M(ALT, IBUS_MOD1_MASK);
M(NUM_LOCK, IBUS_MOD2_MASK);
M(SUPER, IBUS_MOD4_MASK);
/* To do: figure out how to get super/hyper/meta */
#undef M
return ans;
}
static bool
test_env_var(const char *name, const char *val) {
const char *q = getenv(name);
return (q && strcmp(q, val) == 0) ? true : false;
}
static size_t
GLFW_MIN(size_t a, size_t b) {
return a < b ? a : b;
}
static const char *
get_ibus_text_from_message(DBusMessage *msg) {
/* The message structure is (from dbus-monitor)
variant struct {
string "IBusText"
array [
]
string "ash "
variant struct {
string "IBusAttrList"
array [
]
array [
]
}
}
*/
const char *text = NULL;
const char *struct_id = NULL;
DBusMessageIter iter, sub1, sub2;
dbus_message_iter_init(msg, &iter);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) return NULL;
dbus_message_iter_recurse(&iter, &sub1);
if (dbus_message_iter_get_arg_type(&sub1) != DBUS_TYPE_STRUCT) return NULL;
dbus_message_iter_recurse(&sub1, &sub2);
if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) return NULL;
dbus_message_iter_get_basic(&sub2, &struct_id);
if (!struct_id || strncmp(struct_id, "IBusText", sizeof("IBusText")) != 0) return NULL;
dbus_message_iter_next(&sub2);
dbus_message_iter_next(&sub2);
if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) return NULL;
dbus_message_iter_get_basic(&sub2, &text);
return text;
}
static void
handle_ibus_forward_key_event(DBusMessage *msg) {
uint32_t keysym, keycode, state;
DBusMessageIter iter;
dbus_message_iter_init(msg, &iter);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_UINT32) return;
dbus_message_iter_get_basic(&iter, &keysym);
dbus_message_iter_next(&iter);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_UINT32) return;
dbus_message_iter_get_basic(&iter, &keycode);
dbus_message_iter_next(&iter);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_UINT32) return;
dbus_message_iter_get_basic(&iter, &state);
int mods = glfw_modifiers_from_ibus_state(state);
debug("IBUS: ForwardKeyEvent: keysym=%x, keycode=%x, state=%x, glfw_mods=%x\n", keysym, keycode, state, mods);
glfw_xkb_forwarded_key_from_ime(keysym, mods);
}
static void
send_text(const char *text, GLFWIMEState ime_state) {
_GLFWwindow *w = _glfwFocusedWindow();
if (w && w->callbacks.keyboard) {
GLFWkeyevent fake_ev = {.action = GLFW_PRESS};
fake_ev.text = text;
fake_ev.ime_state = ime_state;
w->callbacks.keyboard((GLFWwindow *)w, &fake_ev);
}
}
// Connection handling {{{
static DBusHandlerResult
message_handler(DBusConnection *conn UNUSED, DBusMessage *msg, void *user_data) {
// To monitor signals from IBUS, use
//  dbus-monitor --address `ibus address` "type='signal',interface='org.freedesktop.IBus.InputContext'"
_GLFWIBUSData *ibus = (_GLFWIBUSData *)user_data;
(void)ibus;
const char *text;
switch (
glfw_dbus_match_signal(msg, IBUS_INPUT_INTERFACE, "CommitText", "UpdatePreeditText", "HidePreeditText", "ShowPreeditText", "ForwardKeyEvent", NULL)) {
case 0:
text = get_ibus_text_from_message(msg);
debug("IBUS: CommitText: '%s'\n", text ? text : "(nil)");
send_text(text, GLFW_IME_COMMIT_TEXT);
break;
case 1:
text = get_ibus_text_from_message(msg);
debug("IBUS: UpdatePreeditText: '%s'\n", text ? text : "(nil)");
send_text(text, GLFW_IME_PREEDIT_CHANGED);
break;
case 2:
debug("IBUS: HidePreeditText\n");
send_text("", GLFW_IME_PREEDIT_CHANGED);
break;
case 3: debug("IBUS: ShowPreeditText\n"); break;
case 4: handle_ibus_forward_key_event(msg); break;
}
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
static DBusHandlerResult
ibus_on_owner_change(DBusConnection *conn UNUSED, DBusMessage *msg, void *user_data) {
if (dbus_message_is_signal(msg, "org.freedesktop.DBus", "NameOwnerChanged")) {
const char *name;
const char *old_owner;
const char *new_owner;
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &old_owner, DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID)) {
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
if (strcmp(name, "org.freedesktop.IBus") != 0) { return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; }
_GLFWIBUSData *ibus = (_GLFWIBUSData *)user_data;
ibus->name_owner_changed = true;
return DBUS_HANDLER_RESULT_HANDLED;
}
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
static const char *
get_ibus_address_file_name(void) {
const char *addr;
static char ans[PATH_MAX];
static char display[64] = {0};
addr = getenv("IBUS_ADDRESS");
int offset = 0;
if (addr && addr[0]) {
size_t len = GLFW_MIN(strlen(addr), sizeof(ans) - 1);
memcpy(ans, addr, len);
ans[len] = '\0';
return ans;
}
const char *disp_num = NULL;
const char *host = "unix";
// See https://github.com/ibus/ibus/commit/8ce25208c3f4adfd290a032c6aa739d2b7580eb1 for why we need this dance.
const char *de = getenv("WAYLAND_DISPLAY");
if (de && de[0]) {
disp_num = de;
} else {
const char *de = getenv("DISPLAY");
if (!de || !de[0]) de = ":0.0";
strncpy(display, de, sizeof(display) - 1);
char *dnum = strrchr(display, ':');
if (!dnum) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Could not get IBUS address file name as DISPLAY env var has no colon");
return NULL;
}
char *screen_num = strrchr(display, '.');
*dnum = 0;
dnum++;
if (screen_num) *screen_num = 0;
if (*display) host = display;
disp_num = dnum;
}
memset(ans, 0, sizeof(ans));
const char *conf_env = getenv("XDG_CONFIG_HOME");
if (conf_env && conf_env[0]) {
offset = snprintf(ans, sizeof(ans), "%s", conf_env);
} else {
conf_env = getenv("HOME");
if (!conf_env || !conf_env[0]) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Could not get IBUS address file name as no HOME env var is set");
return NULL;
}
offset = snprintf(ans, sizeof(ans), "%s/.config", conf_env);
}
DBusError err;
char *key = dbus_try_get_local_machine_id(&err);
if (!key) {
_glfwInputError(
GLFW_PLATFORM_ERROR,
"Cannot connect to IBUS as could not get DBUS local machine id with error %s: %s",
err.name ? err.name : "",
err.message ? err.message : "");
return NULL;
}
snprintf(ans + offset, sizeof(ans) - offset, "/ibus/bus/%s-%s-%s", key, host, disp_num);
dbus_free(key);
return ans;
}
static bool
read_ibus_address(_GLFWIBUSData *ibus) {
static char buf[1024];
struct stat s;
FILE *addr_file = fopen(ibus->address_file_name, "r");
if (!addr_file) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Failed to open IBUS address file: %s with error: %s", ibus->address_file_name, strerror(errno));
return false;
}
int stat_result = fstat(fileno(addr_file), &s);
bool found = false;
while (fgets(buf, sizeof(buf), addr_file)) {
if (strncmp(buf, "IBUS_ADDRESS=", sizeof("IBUS_ADDRESS=") - 1) == 0) {
size_t sz = strlen(buf);
if (buf[sz - 1] == '\n') buf[sz - 1] = 0;
if (buf[sz - 2] == '\r') buf[sz - 2] = 0;
found = true;
break;
}
}
fclose(addr_file);
addr_file = NULL;
if (stat_result != 0) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Failed to stat IBUS address file: %s with error: %s", ibus->address_file_name, strerror(errno));
return false;
}
ibus->address_file_mtime = s.st_mtime;
if (found) {
free((void *)ibus->address);
ibus->address = _glfw_strdup(buf + sizeof("IBUS_ADDRESS=") - 1);
return true;
}
_glfwInputError(GLFW_PLATFORM_ERROR, "Could not find IBUS_ADDRESS in %s", ibus->address_file_name);
return false;
}
void
input_context_created(DBusMessage *msg, const DBusError *err, void *data) {
if (err) {
_glfwInputError(GLFW_PLATFORM_ERROR, "IBUS: Failed to create input context with error: %s: %s", err->name, err->message);
return;
}
const char *path = NULL;
if (!glfw_dbus_get_args(msg, "Failed to get IBUS context path from reply", DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID)) return;
_GLFWIBUSData *ibus = (_GLFWIBUSData *)data;
free((void *)ibus->input_ctx_path);
ibus->input_ctx_path = _glfw_strdup(path);
if (!ibus->input_ctx_path) return;
ibus->last_cursor_geometry.valid = false;
dbus_bus_add_match(ibus->conn, "type='signal',interface='org.freedesktop.DBus', member='NameOwnerChanged'", NULL);
dbus_connection_add_filter(ibus->conn, ibus_on_owner_change, ibus, free);
dbus_bus_add_match(ibus->conn, "type='signal',interface='org.freedesktop.IBus.InputContext'", NULL);
DBusObjectPathVTable ibus_vtable = {.message_function = message_handler};
dbus_connection_try_register_object_path(ibus->conn, ibus->input_ctx_path, &ibus_vtable, ibus, NULL);
enum Capabilities caps = IBUS_CAP_FOCUS | IBUS_CAP_PREEDIT_TEXT;
if (!glfw_dbus_call_method_no_reply(
ibus->conn, IBUS_SERVICE, ibus->input_ctx_path, IBUS_INPUT_INTERFACE, "SetCapabilities", DBUS_TYPE_UINT32, &caps, DBUS_TYPE_INVALID))
return;
ibus->ok = true;
glfw_ibus_set_focused(ibus, _glfwFocusedWindow() != NULL);
glfw_ibus_set_cursor_geometry(ibus, 0, 0, 0, 0);
debug("Connected to IBUS daemon for IME input management\n");
}
static bool
setup_connection(_GLFWIBUSData *ibus) {
const char *client_name = "GLFW_Application";
const char *address_file_name = get_ibus_address_file_name();
ibus->ok = false;
if (!address_file_name) return false;
free((void *)ibus->address_file_name);
ibus->address_file_name = _glfw_strdup(address_file_name);
if (!read_ibus_address(ibus)) return false;
if (ibus->conn) {
glfw_dbus_close_connection(ibus->conn);
ibus->conn = NULL;
}
debug("Connecting to IBUS daemon @ %s for IME input management\n", ibus->address);
ibus->conn = glfw_dbus_connect_to(ibus->address, "Failed to connect to the IBUS daemon, with error", "ibus", true);
if (!ibus->conn) return false;
free((void *)ibus->input_ctx_path);
ibus->input_ctx_path = NULL;
ibus->last_cursor_geometry.valid = false;
if (!glfw_dbus_call_method_with_reply(
ibus->conn,
IBUS_SERVICE,
IBUS_PATH,
IBUS_INTERFACE,
"CreateInputContext",
DBUS_TIMEOUT_USE_DEFAULT,
input_context_created,
ibus,
DBUS_TYPE_STRING,
&client_name,
DBUS_TYPE_INVALID)) {
return false;
}
return true;
}
void
glfw_connect_to_ibus(_GLFWIBUSData *ibus) {
if (ibus->inited) return;
if (!test_env_var("GLFW_IM_MODULE", "ibus")) return;
ibus->inited = true;
ibus->name_owner_changed = false;
setup_connection(ibus);
}
void
glfw_ibus_terminate(_GLFWIBUSData *ibus) {
if (ibus->conn) {
glfw_dbus_close_connection(ibus->conn);
ibus->conn = NULL;
}
#define F(x) \
if (ibus->x) { \
free((void *)ibus->x); \
ibus->x = NULL; \
}
F(input_ctx_path);
F(address);
F(address_file_name);
#undef F
ibus->ok = false;
}
static bool
check_connection(_GLFWIBUSData *ibus) {
if (!ibus->inited) return false;
if (ibus->conn && dbus_connection_get_is_connected(ibus->conn) && !ibus->name_owner_changed) return ibus->ok;
struct stat s;
ibus->name_owner_changed = false;
if (stat(ibus->address_file_name, &s) != 0 || s.st_mtime != ibus->address_file_mtime) {
if (!read_ibus_address(ibus)) return false;
return setup_connection(ibus);
}
return false;
}
void
glfw_ibus_dispatch(_GLFWIBUSData *ibus) {
if (ibus->conn) glfw_dbus_dispatch(ibus->conn);
}
// }}}
static void
simple_message(_GLFWIBUSData *ibus, const char *method) {
if (check_connection(ibus)) {
glfw_dbus_call_method_no_reply(ibus->conn, IBUS_SERVICE, ibus->input_ctx_path, IBUS_INPUT_INTERFACE, method, DBUS_TYPE_INVALID);
}
}
void
glfw_ibus_set_focused(_GLFWIBUSData *ibus, bool focused) {
simple_message(ibus, focused ? "FocusIn" : "FocusOut");
}
void
glfw_ibus_set_cursor_geometry(_GLFWIBUSData *ibus, int x, int y, int w, int h) {
// Skip duplicate updates (e.g. pre-edit text changes while the anchor
// cell is unchanged) so the IME candidate window is not needlessly repositioned.
_GLFWIBUSCursorGeometry *g = &ibus->last_cursor_geometry;
if (g->valid && g->x == x && g->y == y && g->w == w && g->h == h) return;
if (check_connection(ibus) && glfw_dbus_call_method_no_reply(
ibus->conn,
IBUS_SERVICE,
ibus->input_ctx_path,
IBUS_INPUT_INTERFACE,
"SetCursorLocation",
DBUS_TYPE_INT32,
&x,
DBUS_TYPE_INT32,
&y,
DBUS_TYPE_INT32,
&w,
DBUS_TYPE_INT32,
&h,
DBUS_TYPE_INVALID)) {
*g = (_GLFWIBUSCursorGeometry){.x = x, .y = y, .w = w, .h = h, .valid = true};
}
}
void
key_event_processed(DBusMessage *msg, const DBusError *err, void *data) {
uint32_t handled = 0;
_GLFWIBUSKeyEvent *ev = (_GLFWIBUSKeyEvent *)data;
// Restore key's text from the text embedded in the structure.
ev->glfw_ev.text = ev->__embedded_text;
bool is_release = ev->glfw_ev.action == GLFW_RELEASE;
bool failed = false;
if (err) {
_glfwInputError(GLFW_PLATFORM_ERROR, "IBUS: Failed to process key with error: %s: %s", err->name, err->message);
failed = true;
} else {
glfw_dbus_get_args(msg, "Failed to get IBUS handled key from reply", DBUS_TYPE_BOOLEAN, &handled, DBUS_TYPE_INVALID);
debug("IBUS processed native_key: 0x%x release: %d handled: %u\n", ev->glfw_ev.native_key, is_release, handled);
}
glfw_xkb_key_from_ime(ev, handled ? true : false, failed);
free(ev);
}
bool
ibus_process_key(const _GLFWIBUSKeyEvent *ev_, _GLFWIBUSData *ibus) {
if (!check_connection(ibus)) return false;
_GLFWIBUSKeyEvent *ev = calloc(1, sizeof(_GLFWIBUSKeyEvent));
if (!ev) return false;
memcpy(ev, ev_, sizeof(_GLFWIBUSKeyEvent));
// Put the key's text in a field IN the structure, for proper serialization.
if (ev->glfw_ev.text) strncpy(ev->__embedded_text, ev->glfw_ev.text, sizeof(ev->__embedded_text) - 1);
ev->glfw_ev.text = NULL;
uint32_t state = ibus_key_state_from_glfw(ev->glfw_ev.mods, ev->glfw_ev.action);
if (!glfw_dbus_call_method_with_reply(
ibus->conn,
IBUS_SERVICE,
ibus->input_ctx_path,
IBUS_INPUT_INTERFACE,
"ProcessKeyEvent",
3000,
key_event_processed,
ev,
DBUS_TYPE_UINT32,
&ev->ibus_keysym,
DBUS_TYPE_UINT32,
&ev->ibus_keycode,
DBUS_TYPE_UINT32,
&state,
DBUS_TYPE_INVALID)) {
free(ev);
return false;
}
return true;
}
+60
View File
@@ -0,0 +1,60 @@
//========================================================================
// GLFW 3.4 XKB - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2018 Kovid Goyal <kovid@kovidgoyal.net>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#pragma once
#include "internal.h"
#include "dbus_glfw.h"
#include <xkbcommon/xkbcommon.h>
typedef struct {
int x, y, w, h;
bool valid;
} _GLFWIBUSCursorGeometry;
typedef struct {
bool ok, inited, name_owner_changed;
time_t address_file_mtime;
DBusConnection *conn;
const char *input_ctx_path, *address_file_name, *address;
_GLFWIBUSCursorGeometry last_cursor_geometry;
} _GLFWIBUSData;
typedef struct {
xkb_keycode_t ibus_keycode;
xkb_keysym_t ibus_keysym;
GLFWid window_id;
GLFWkeyevent glfw_ev;
char __embedded_text[64];
} _GLFWIBUSKeyEvent;
void glfw_connect_to_ibus(_GLFWIBUSData *ibus);
void glfw_ibus_terminate(_GLFWIBUSData *ibus);
void glfw_ibus_set_focused(_GLFWIBUSData *ibus, bool focused);
void glfw_ibus_dispatch(_GLFWIBUSData *ibus);
bool ibus_process_key(const _GLFWIBUSKeyEvent *ev_, _GLFWIBUSData *ibus);
void glfw_ibus_set_cursor_geometry(_GLFWIBUSData *ibus, int x, int y, int w, int h);
Vendored
+382
View File
@@ -0,0 +1,382 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2018 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// Please use C89 style variable declarations in this file because VS 2010
//========================================================================
#include "internal.h"
#include "mappings.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
// The global variables below comprise all mutable global data in GLFW
//
// Any other global variable is a bug
// Global state shared between compilation units of GLFW
//
_GLFWlibrary _glfw = {false};
// These are outside of _glfw so they can be used before initialization and
// after termination
//
static _GLFWerror _glfwMainThreadError;
static GLFWerrorfun _glfwErrorCallback;
static _GLFWinitconfig _glfwInitHints = {
.hatButtons = true,
.angleType = GLFW_ANGLE_PLATFORM_TYPE_NONE,
.debugKeyboard = false,
.debugRendering = false,
.ns =
{
.menubar = true, // macOS menu bar
.chdir = true // macOS bundle chdir
},
.wl =
{
.ime = true, // Wayland IME support
},
};
// Terminate the library
//
static void
terminate(void) {
int i;
memset(&_glfw.callbacks, 0, sizeof(_glfw.callbacks));
_glfw_free_clipboard_data(&_glfw.clipboard);
_glfw_free_clipboard_data(&_glfw.primary);
while (_glfw.windowListHead) glfwDestroyWindow((GLFWwindow *)_glfw.windowListHead);
while (_glfw.cursorListHead) glfwDestroyCursor((GLFWcursor *)_glfw.cursorListHead);
for (i = 0; i < _glfw.monitorCount; i++) {
_GLFWmonitor *monitor = _glfw.monitors[i];
if (monitor->originalRamp.size) _glfwPlatformSetGammaRamp(monitor, &monitor->originalRamp);
_glfwFreeMonitor(monitor);
}
free(_glfw.monitors);
_glfw.monitors = NULL;
_glfw.monitorCount = 0;
free(_glfw.mappings);
_glfw.mappings = NULL;
_glfw.mappingCount = 0;
_glfwTerminateVulkan();
_glfwPlatformTerminateJoysticks();
_glfwPlatformTerminate();
_glfw.initialized = false;
while (_glfw.errorListHead) {
_GLFWerror *error = _glfw.errorListHead;
_glfw.errorListHead = error->next;
free(error);
}
_glfwPlatformDestroyTls(&_glfw.contextSlot);
_glfwPlatformDestroyTls(&_glfw.errorSlot);
_glfwPlatformDestroyMutex(&_glfw.errorLock);
memset(&_glfw, 0, sizeof(_glfw));
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
char *
_glfw_strdup(const char *source) {
const size_t length = strlen(source);
char *result = malloc(length + 1);
memcpy(result, source, length);
result[length] = 0;
return result;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW event API //////
//////////////////////////////////////////////////////////////////////////
// Notifies shared code of an error
//
void
_glfwInputError(int code, const char *format, ...) {
_GLFWerror *error;
char description[_GLFW_MESSAGE_SIZE];
if (format) {
va_list vl;
va_start(vl, format);
vsnprintf(description, sizeof(description), format, vl);
va_end(vl);
description[sizeof(description) - 1] = '\0';
} else {
if (code == GLFW_NOT_INITIALIZED) strcpy(description, "The GLFW library is not initialized");
else if (code == GLFW_NO_CURRENT_CONTEXT) strcpy(description, "There is no current context");
else if (code == GLFW_INVALID_ENUM) strcpy(description, "Invalid argument for enum parameter");
else if (code == GLFW_INVALID_VALUE) strcpy(description, "Invalid value for parameter");
else if (code == GLFW_OUT_OF_MEMORY) strcpy(description, "Out of memory");
else if (code == GLFW_API_UNAVAILABLE) strcpy(description, "The requested API is unavailable");
else if (code == GLFW_VERSION_UNAVAILABLE) strcpy(description, "The requested API version is unavailable");
else if (code == GLFW_PLATFORM_ERROR) strcpy(description, "A platform-specific error occurred");
else if (code == GLFW_FORMAT_UNAVAILABLE) strcpy(description, "The requested format is unavailable");
else if (code == GLFW_NO_WINDOW_CONTEXT) strcpy(description, "The specified window has no context");
else if (code == GLFW_FEATURE_UNAVAILABLE) strcpy(description, "The requested feature cannot be implemented for this platform");
else if (code == GLFW_FEATURE_UNIMPLEMENTED) strcpy(description, "The requested feature has not yet been implemented for this platform");
else strcpy(description, "ERROR: UNKNOWN GLFW ERROR");
}
if (_glfw.initialized) {
error = _glfwPlatformGetTls(&_glfw.errorSlot);
if (!error) {
error = calloc(1, sizeof(_GLFWerror));
_glfwPlatformSetTls(&_glfw.errorSlot, error);
_glfwPlatformLockMutex(&_glfw.errorLock);
error->next = _glfw.errorListHead;
_glfw.errorListHead = error;
_glfwPlatformUnlockMutex(&_glfw.errorLock);
}
} else error = &_glfwMainThreadError;
error->code = code;
strcpy(error->description, description);
if (_glfwErrorCallback) _glfwErrorCallback(code, description);
}
void
_glfwDebug(const char *format, ...) {
if (format) {
va_list vl;
fprintf(stderr, "[%.3f] ", monotonic_t_to_s_double(monotonic()));
va_start(vl, format);
vfprintf(stderr, format, vl);
va_end(vl);
fprintf(stderr, "\n");
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW public API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI int
glfwInit(monotonic_t start_time, bool *supports_window_occlusion) {
*supports_window_occlusion = false;
if (_glfw.initialized) return true;
monotonic_start_time = start_time;
memset(&_glfw, 0, sizeof(_glfw));
_glfw.hints.init = _glfwInitHints;
_glfw.ignoreOSKeyboardProcessing = false;
if (!_glfwPlatformInit(supports_window_occlusion)) {
terminate();
return false;
}
if (!_glfwPlatformCreateMutex(&_glfw.errorLock) || !_glfwPlatformCreateTls(&_glfw.errorSlot) || !_glfwPlatformCreateTls(&_glfw.contextSlot)) {
terminate();
return false;
}
_glfwPlatformSetTls(&_glfw.errorSlot, &_glfwMainThreadError);
_glfw.initialized = true;
glfwDefaultWindowHints();
{
int i;
for (i = 0; _glfwDefaultMappings[i]; i++) {
if (!glfwUpdateGamepadMappings(_glfwDefaultMappings[i])) {
terminate();
return false;
}
}
}
return true;
}
GLFWAPI void
glfwTerminate(void) {
if (!_glfw.initialized) return;
terminate();
}
GLFWAPI void
glfwInitHint(int hint, int value) {
switch (hint) {
case GLFW_JOYSTICK_HAT_BUTTONS: _glfwInitHints.hatButtons = value; return;
case GLFW_ANGLE_PLATFORM_TYPE: _glfwInitHints.angleType = value; return;
case GLFW_DEBUG_KEYBOARD: _glfwInitHints.debugKeyboard = value; return;
case GLFW_DEBUG_RENDERING: _glfwInitHints.debugRendering = value; return;
case GLFW_COCOA_CHDIR_RESOURCES: _glfwInitHints.ns.chdir = value; return;
case GLFW_COCOA_MENUBAR: _glfwInitHints.ns.menubar = value; return;
case GLFW_WAYLAND_IME: _glfwInitHints.wl.ime = value; return;
}
_glfwInputError(GLFW_INVALID_ENUM, "Invalid init hint 0x%08X", hint);
}
GLFWAPI void
glfwGetVersion(int *major, int *minor, int *rev) {
if (major != NULL) *major = GLFW_VERSION_MAJOR;
if (minor != NULL) *minor = GLFW_VERSION_MINOR;
if (rev != NULL) *rev = GLFW_VERSION_REVISION;
}
GLFWAPI const char *
glfwGetVersionString(void) {
return _glfwPlatformGetVersionString();
}
GLFWAPI int
glfwGetError(const char **description) {
_GLFWerror *error;
int code = GLFW_NO_ERROR;
if (description) *description = NULL;
if (_glfw.initialized) error = _glfwPlatformGetTls(&_glfw.errorSlot);
else error = &_glfwMainThreadError;
if (error) {
code = error->code;
error->code = GLFW_NO_ERROR;
if (description && code) *description = error->description;
}
return code;
}
GLFWAPI GLFWerrorfun
glfwSetErrorCallback(GLFWerrorfun cbfun) {
_GLFW_SWAP_POINTERS(_glfwErrorCallback, cbfun);
return cbfun;
}
GLFWAPI void
glfwRunMainLoop(GLFWtickcallback callback, void *data) {
_GLFW_REQUIRE_INIT();
_glfwPlatformRunMainLoop(callback, data);
}
GLFWAPI void
glfwStopMainLoop(void) {
_GLFW_REQUIRE_INIT();
_glfwPlatformStopMainLoop();
}
GLFWAPI unsigned long long
glfwAddTimer(monotonic_t interval, bool repeats, GLFWuserdatafun callback, void *callback_data, GLFWuserdatafun free_callback) {
return _glfwPlatformAddTimer(interval, repeats, callback, callback_data, free_callback);
}
GLFWAPI void
glfwUpdateTimer(unsigned long long timer_id, monotonic_t interval, bool enabled) {
_glfwPlatformUpdateTimer(timer_id, interval, enabled);
}
GLFWAPI void
glfwRemoveTimer(unsigned long long timer_id) {
_glfwPlatformRemoveTimer(timer_id);
}
GLFWAPI GLFWapplicationclosefun
glfwSetApplicationCloseCallback(GLFWapplicationclosefun cbfun) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_GLFW_SWAP_POINTERS(_glfw.callbacks.application_close, cbfun);
return cbfun;
}
GLFWAPI GLFWsystemcolorthemechangefun
glfwSetSystemColorThemeChangeCallback(GLFWsystemcolorthemechangefun cbfun) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_GLFW_SWAP_POINTERS(_glfw.callbacks.system_color_theme_change, cbfun);
return cbfun;
}
GLFWAPI GLFWclipboardlostfun
glfwSetClipboardLostCallback(GLFWclipboardlostfun cbfun) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_GLFW_SWAP_POINTERS(_glfw.callbacks.clipboard_lost, cbfun);
return cbfun;
}
GLFWAPI GLFWdrawtextfun
glfwSetDrawTextFunction(GLFWdrawtextfun cbfun) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_GLFW_SWAP_POINTERS(_glfw.callbacks.draw_text, cbfun);
return cbfun;
}
GLFWAPI GLFWcurrentselectionfun
glfwSetCurrentSelectionCallback(GLFWcurrentselectionfun cbfun) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_GLFW_SWAP_POINTERS(_glfw.callbacks.get_current_selection, cbfun);
return cbfun;
}
GLFWAPI GLFWhascurrentselectionfun
glfwSetHasCurrentSelectionCallback(GLFWhascurrentselectionfun cbfun) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_GLFW_SWAP_POINTERS(_glfw.callbacks.has_current_selection, cbfun);
return cbfun;
}
GLFWAPI GLFWimecursorpositionfun
glfwSetIMECursorPositionCallback(GLFWimecursorpositionfun cbfun) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_GLFW_SWAP_POINTERS(_glfw.callbacks.get_ime_cursor_position, cbfun);
return cbfun;
}
GLFWAPI GLFWimetextaroundcursorfun
glfwSetIMETextAroundCursorCallback(GLFWimetextaroundcursorfun cbfun) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_GLFW_SWAP_POINTERS(_glfw.callbacks.get_ime_text_around_cursor, cbfun);
return cbfun;
}
+1608
View File
File diff suppressed because it is too large. Load diff
+909
View File
@@ -0,0 +1,909 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#pragma once
#include "../kitty/monotonic.h"
#if defined(_GLFW_USE_CONFIG_H)
#include "glfw_config.h"
#endif
#define arraysz(x) (sizeof(x) / sizeof(x[0]))
#define MAX(x, y) \
__extension__({ \
__typeof__(x) a = (x); \
__typeof__(y) b = (y); \
a > b ? a : b; \
})
#if defined(GLFW_INCLUDE_GLCOREARB) || defined(GLFW_INCLUDE_ES1) || defined(GLFW_INCLUDE_ES2) || defined(GLFW_INCLUDE_ES3) || defined(GLFW_INCLUDE_ES31) || \
defined(GLFW_INCLUDE_ES32) || defined(GLFW_INCLUDE_NONE) || defined(GLFW_INCLUDE_GLEXT) || defined(GLFW_INCLUDE_GLU) || defined(GLFW_INCLUDE_VULKAN) || \
defined(GLFW_DLL)
#error "You must not define any header option macros when compiling GLFW"
#endif
#define GLFW_INCLUDE_NONE
#include "glfw3.h"
#define EGL_PRESENT_OPAQUE_EXT 0x31df
#define GLFW_MOD_REMAP_SZ 8
#define _GLFW_INSERT_FIRST 0
#define _GLFW_INSERT_LAST 1
#define _GLFW_POLL_PRESENCE 0
#define _GLFW_POLL_AXES 1
#define _GLFW_POLL_BUTTONS 2
#define _GLFW_POLL_ALL (_GLFW_POLL_AXES | _GLFW_POLL_BUTTONS)
#define _GLFW_MESSAGE_SIZE 1024
typedef unsigned long long GLFWid;
typedef struct _GLFWerror _GLFWerror;
typedef struct _GLFWinitconfig _GLFWinitconfig;
typedef struct _GLFWwndconfig _GLFWwndconfig;
typedef struct _GLFWctxconfig _GLFWctxconfig;
typedef struct _GLFWfbconfig _GLFWfbconfig;
typedef struct _GLFWcontext _GLFWcontext;
typedef struct _GLFWwindow _GLFWwindow;
typedef struct _GLFWlibrary _GLFWlibrary;
typedef struct _GLFWmonitor _GLFWmonitor;
typedef struct _GLFWcursor _GLFWcursor;
typedef struct _GLFWmapelement _GLFWmapelement;
typedef struct _GLFWmapping _GLFWmapping;
typedef struct _GLFWjoystick _GLFWjoystick;
typedef struct _GLFWtls _GLFWtls;
typedef struct _GLFWmutex _GLFWmutex;
typedef void (*_GLFWmakecontextcurrentfun)(_GLFWwindow *);
typedef void (*_GLFWswapbuffersfun)(_GLFWwindow *);
typedef void (*_GLFWswapintervalfun)(int);
typedef int (*_GLFWextensionsupportedfun)(const char *);
typedef GLFWglproc (*_GLFWgetprocaddressfun)(const char *);
typedef void (*_GLFWdestroycontextfun)(_GLFWwindow *);
#define GL_VERSION 0x1F02
#define GL_NONE 0
#define GL_COLOR_BUFFER_BIT 0x00004000
#define GL_UNSIGNED_BYTE 0x1401
#define GL_EXTENSIONS 0x1F03
#define GL_NUM_EXTENSIONS 0x821d
#define GL_CONTEXT_FLAGS 0x821e
#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001
#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002
#define GL_CONTEXT_PROFILE_MASK 0x9126
#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002
#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001
#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
#define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252
#define GL_NO_RESET_NOTIFICATION_ARB 0x8261
#define GL_CONTEXT_RELEASE_BEHAVIOR 0x82fb
#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x82fc
#define GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR 0x00000008
#define MAX(x, y) \
__extension__({ \
__typeof__(x) a = (x); \
__typeof__(y) b = (y); \
a > b ? a : b; \
})
#define MIN(x, y) \
__extension__({ \
__typeof__(x) a = (x); \
__typeof__(y) b = (y); \
a < b ? a : b; \
})
typedef int GLint;
typedef unsigned int GLuint;
typedef unsigned int GLenum;
typedef unsigned int GLbitfield;
typedef unsigned char GLubyte;
typedef void(APIENTRY *PFNGLCLEARPROC)(GLbitfield);
typedef const GLubyte *(APIENTRY *PFNGLGETSTRINGPROC)(GLenum);
typedef void(APIENTRY *PFNGLGETINTEGERVPROC)(GLenum, GLint *);
typedef const GLubyte *(APIENTRY *PFNGLGETSTRINGIPROC)(GLenum, GLuint);
#define VK_NULL_HANDLE 0
typedef void *VkInstance;
typedef void *VkPhysicalDevice;
typedef uint64_t VkSurfaceKHR;
typedef uint32_t VkFlags;
typedef uint32_t VkBool32;
typedef enum VkStructureType {
VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR = 1000004000,
VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR = 1000005000,
VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR = 1000006000,
VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR = 1000009000,
VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK = 1000123000,
VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT = 1000217000,
VK_STRUCTURE_TYPE_MAX_ENUM = 0x7FFFFFFF
} VkStructureType;
typedef enum VkResult {
VK_SUCCESS = 0,
VK_NOT_READY = 1,
VK_TIMEOUT = 2,
VK_EVENT_SET = 3,
VK_EVENT_RESET = 4,
VK_INCOMPLETE = 5,
VK_ERROR_OUT_OF_HOST_MEMORY = -1,
VK_ERROR_OUT_OF_DEVICE_MEMORY = -2,
VK_ERROR_INITIALIZATION_FAILED = -3,
VK_ERROR_DEVICE_LOST = -4,
VK_ERROR_MEMORY_MAP_FAILED = -5,
VK_ERROR_LAYER_NOT_PRESENT = -6,
VK_ERROR_EXTENSION_NOT_PRESENT = -7,
VK_ERROR_FEATURE_NOT_PRESENT = -8,
VK_ERROR_INCOMPATIBLE_DRIVER = -9,
VK_ERROR_TOO_MANY_OBJECTS = -10,
VK_ERROR_FORMAT_NOT_SUPPORTED = -11,
VK_ERROR_SURFACE_LOST_KHR = -1000000000,
VK_SUBOPTIMAL_KHR = 1000001003,
VK_ERROR_OUT_OF_DATE_KHR = -1000001004,
VK_ERROR_INCOMPATIBLE_DISPLAY_KHR = -1000003001,
VK_ERROR_NATIVE_WINDOW_IN_USE_KHR = -1000000001,
VK_ERROR_VALIDATION_FAILED_EXT = -1000011001,
VK_RESULT_MAX_ENUM = 0x7FFFFFFF
} VkResult;
typedef struct VkAllocationCallbacks VkAllocationCallbacks;
typedef struct VkExtensionProperties {
char extensionName[256];
uint32_t specVersion;
} VkExtensionProperties;
typedef void(APIENTRY *PFN_vkVoidFunction)(void);
#if defined(_GLFW_VULKAN_STATIC)
PFN_vkVoidFunction vkGetInstanceProcAddr(VkInstance, const char *);
VkResult vkEnumerateInstanceExtensionProperties(const char *, uint32_t *, VkExtensionProperties *);
#else
typedef PFN_vkVoidFunction(APIENTRY *PFN_vkGetInstanceProcAddr)(VkInstance, const char *);
typedef VkResult(APIENTRY *PFN_vkEnumerateInstanceExtensionProperties)(const char *, uint32_t *, VkExtensionProperties *);
#define vkEnumerateInstanceExtensionProperties _glfw.vk.EnumerateInstanceExtensionProperties
#define vkGetInstanceProcAddr _glfw.vk.GetInstanceProcAddr
#endif
#if defined(_GLFW_COCOA)
#include "cocoa_platform.h"
#elif defined(_GLFW_WIN32)
#include "win32_platform.h"
#elif defined(_GLFW_X11)
#include "x11_platform.h"
#elif defined(_GLFW_WAYLAND)
#include "wl_platform.h"
#elif defined(_GLFW_OSMESA)
#include "null_platform.h"
#else
#error "No supported window creation API selected"
#endif
#include "egl_context.h"
#include "osmesa_context.h"
#define remove_i_from_array(array, i, count) \
{ \
(count)--; \
if ((i) < (count)) { memmove((array) + (i), (array) + (i) + 1, sizeof((array)[0]) * ((count) - (i))); /* NOLINT(bugprone-sizeof-expression) */ } \
}
// Constructs a version number string from the public header macros
#define _GLFW_CONCAT_VERSION(m, n, r) #m "." #n "." #r
#define _GLFW_MAKE_VERSION(m, n, r) _GLFW_CONCAT_VERSION(m, n, r)
#define _GLFW_VERSION_NUMBER _GLFW_MAKE_VERSION(GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION)
// Checks for whether the library has been initialized
#define _GLFW_REQUIRE_INIT() \
if (!_glfw.initialized) { \
_glfwInputError(GLFW_NOT_INITIALIZED, NULL); \
return; \
}
#define _GLFW_REQUIRE_INIT_OR_RETURN(x) \
if (!_glfw.initialized) { \
_glfwInputError(GLFW_NOT_INITIALIZED, NULL); \
return x; \
}
// Swaps the provided pointers
#define _GLFW_SWAP_POINTERS(x, y) \
do { \
__typeof__(x) t; \
t = x; \
x = y; \
y = t; \
} while (0)
// Suppress some pedantic warnings
#ifdef __clang__
#define START_ALLOW_CASE_RANGE _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wpedantic\"")
#define END_ALLOW_CASE_RANGE _Pragma("clang diagnostic pop")
#define ALLOW_UNUSED_RESULT _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wunused-result\"")
#define END_ALLOW_UNUSED_RESULT _Pragma("clang diagnostic pop")
#else
#define START_ALLOW_CASE_RANGE _Pragma("GCC diagnostic ignored \"-Wpedantic\"")
#define END_ALLOW_CASE_RANGE _Pragma("GCC diagnostic pop")
#define ALLOW_UNUSED_RESULT _Pragma("GCC diagnostic ignored \"-Wunused-result\"")
#define END_ALLOW_UNUSED_RESULT _Pragma("GCC diagnostic pop")
#endif
// dlsym that works with -Wpedantic
#define glfw_dlsym(dest, handle, name) \
do { *(void **)&(dest) = _glfw_dlsym(handle, name); } while (0)
// Mark function arguments as unused
#define UNUSED __attribute__((unused))
// Per-thread error structure
//
struct _GLFWerror {
_GLFWerror *next;
int code;
char description[_GLFW_MESSAGE_SIZE];
};
// Initialization configuration
//
// Parameters relating to the initialization of the library
//
struct _GLFWinitconfig {
bool hatButtons;
int angleType;
bool debugKeyboard;
bool debugRendering;
struct {
bool menubar;
bool chdir;
} ns;
struct {
bool ime;
} wl;
};
// Window configuration
//
// Parameters relating to the creation of the window but not directly related
// to the framebuffer. This is used to pass window creation parameters from
// shared code to the platform API.
//
struct _GLFWwndconfig {
int width;
int height;
const char *title;
bool resizable;
bool visible;
bool decorated;
bool focused;
bool autoIconify;
bool floating;
bool maximized;
bool centerCursor;
bool focusOnShow;
bool mousePassthrough;
bool scaleToMonitor;
int blur_radius;
struct {
bool retina;
int color_space;
char frameName[256];
} ns;
struct {
char className[256];
char instanceName[256];
} x11;
struct {
char appId[256], windowTag[256];
uint32_t bgcolor;
} wl;
};
// Context configuration
//
// Parameters relating to the creation of the context but not directly related
// to the framebuffer. This is used to pass context creation parameters from
// shared code to the platform API.
//
struct _GLFWctxconfig {
int client;
int source;
int major;
int minor;
bool forward;
bool debug;
bool noerror;
int profile;
int robustness;
int release;
_GLFWwindow *share;
struct {
bool offline;
} nsgl;
};
// Framebuffer configuration
//
// This describes buffers and their sizes. It also contains
// a platform-specific ID used to map back to the backend API object.
//
// It is used to pass framebuffer parameters from shared code to the platform
// API and also to enumerate and select available framebuffer configs.
//
struct _GLFWfbconfig {
int redBits;
int greenBits;
int blueBits;
int alphaBits;
int depthBits;
int stencilBits;
int accumRedBits;
int accumGreenBits;
int accumBlueBits;
int accumAlphaBits;
int auxBuffers;
bool stereo;
int samples;
bool sRGB;
bool doublebuffer;
bool transparent;
uintptr_t handle;
};
// Context structure
//
struct _GLFWcontext {
int client;
int source;
int major, minor, revision;
bool forward, debug, noerror;
int profile;
int robustness;
int release;
PFNGLGETSTRINGIPROC GetStringi;
PFNGLGETINTEGERVPROC GetIntegerv;
PFNGLGETSTRINGPROC GetString;
_GLFWmakecontextcurrentfun makeCurrent;
_GLFWswapbuffersfun swapBuffers;
_GLFWswapintervalfun swapInterval;
_GLFWextensionsupportedfun extensionSupported;
_GLFWgetprocaddressfun getProcAddress;
_GLFWdestroycontextfun destroy;
// This is defined in the context API's context.h
_GLFW_PLATFORM_CONTEXT_STATE
// This is defined in egl_context.h
_GLFWcontextEGL egl;
// This is defined in osmesa_context.h
_GLFWcontextOSMesa osmesa;
};
// Window and context structure
//
struct _GLFWwindow {
struct _GLFWwindow *next;
// Window settings and state
bool resizable;
bool decorated;
bool autoIconify;
bool floating;
bool focusOnShow;
bool mousePassthrough;
bool shouldClose;
void *userPointer;
GLFWid id;
GLFWvidmode videoMode;
_GLFWmonitor *monitor;
_GLFWcursor *cursor;
int minwidth, minheight;
int maxwidth, maxheight;
int numer, denom;
int widthincr, heightincr;
bool stickyKeys;
bool stickyMouseButtons;
bool lockKeyMods;
int cursorMode;
char mouseButtons[GLFW_MOUSE_BUTTON_LAST + 1];
GLFWkeyevent activated_keys[16];
// Virtual cursor position when cursor is disabled
double virtualCursorPosX, virtualCursorPosY;
bool rawMouseMotion;
_GLFWcontext context;
#ifdef _GLFW_WAYLAND
bool swaps_disallowed;
#else
const bool swaps_disallowed;
#endif
struct {
GLFWDragOperationType preferred;
int allowed, source_actions;
} drop_operation;
struct {
GLFWwindowposfun pos;
GLFWwindowsizefun size;
GLFWwindowclosefun close;
GLFWwindowrefreshfun refresh;
GLFWwindowfocusfun focus;
GLFWwindowocclusionfun occlusion;
GLFWwindowiconifyfun iconify;
GLFWwindowmaximizefun maximize;
GLFWframebuffersizefun fbsize;
GLFWwindowcontentscalefun scale;
GLFWmousebuttonfun mouseButton;
GLFWcursorposfun cursorPos;
GLFWcursorenterfun cursorEnter;
GLFWscrollfun scroll;
GLFWtouchfun touch;
GLFWkeyboardfun keyboard;
GLFWliveresizefun liveResize;
GLFWdragsourcefun drag_source;
GLFWdropeventfun drop_event;
} callbacks;
// This is defined in the window API's platform.h
_GLFW_PLATFORM_WINDOW_STATE;
};
// Monitor structure
//
struct _GLFWmonitor {
const char *name, *description;
void *userPointer;
// Physical dimensions in millimeters.
int widthMM, heightMM;
// The window whose video mode is current on this monitor
_GLFWwindow *window;
GLFWvidmode *modes;
int modeCount;
GLFWvidmode currentMode;
GLFWgammaramp originalRamp;
GLFWgammaramp currentRamp;
// This is defined in the window API's platform.h
_GLFW_PLATFORM_MONITOR_STATE;
};
// Cursor structure
//
struct _GLFWcursor {
_GLFWcursor *next;
// This is defined in the window API's platform.h
_GLFW_PLATFORM_CURSOR_STATE;
};
// Gamepad mapping element structure
//
struct _GLFWmapelement {
uint8_t type;
uint8_t index;
int8_t axisScale;
int8_t axisOffset;
};
// Gamepad mapping structure
//
struct _GLFWmapping {
char name[128];
char guid[33];
_GLFWmapelement buttons[15];
_GLFWmapelement axes[6];
};
// Joystick structure
//
struct _GLFWjoystick {
bool present;
float *axes;
int axisCount;
unsigned char *buttons;
int buttonCount;
unsigned char *hats;
int hatCount;
char *name;
void *userPointer;
char guid[33];
_GLFWmapping *mapping;
// This is defined in the joystick API's joystick.h
_GLFW_PLATFORM_JOYSTICK_STATE;
};
// Thread local storage structure
//
struct _GLFWtls {
// This is defined in the platform's thread.h
_GLFW_PLATFORM_TLS_STATE;
};
// Mutex structure
//
struct _GLFWmutex {
// This is defined in the platform's thread.h
_GLFW_PLATFORM_MUTEX_STATE;
};
typedef struct _GLFWClipboardData {
const char **mime_types;
size_t num_mime_types;
GLFWclipboarditerfun get_data;
GLFWClipboardType ctype;
} _GLFWClipboardData;
// Library global data
//
struct _GLFWlibrary {
bool initialized;
struct {
_GLFWinitconfig init;
_GLFWfbconfig framebuffer;
_GLFWwndconfig window;
_GLFWctxconfig context;
int refreshRate;
} hints;
_GLFWClipboardData primary, clipboard;
_GLFWerror *errorListHead;
_GLFWcursor *cursorListHead;
_GLFWwindow *windowListHead;
GLFWid focusedWindowId;
_GLFWmonitor **monitors;
int monitorCount;
bool joysticksInitialized;
_GLFWjoystick joysticks[GLFW_JOYSTICK_LAST + 1];
_GLFWmapping *mappings;
int mappingCount;
_GLFWtls errorSlot;
_GLFWtls contextSlot;
_GLFWmutex errorLock;
bool ignoreOSKeyboardProcessing, keyboard_grabbed;
// remap_modifier: modifierRemap[i] is the GLFW modifier mask that the
// modifier at bit i is presented as, or 0 to leave it alone.
int modifierRemap[GLFW_MOD_REMAP_SZ];
int modifierRemapMask;
struct {
bool available;
void *handle;
char *extensions[2];
#if !defined(_GLFW_VULKAN_STATIC)
PFN_vkEnumerateInstanceExtensionProperties EnumerateInstanceExtensionProperties;
PFN_vkGetInstanceProcAddr GetInstanceProcAddr;
#endif
bool KHR_surface;
#if defined(_GLFW_WIN32)
bool KHR_win32_surface;
#elif defined(_GLFW_COCOA)
bool MVK_macos_surface;
bool EXT_metal_surface;
#elif defined(_GLFW_X11)
bool KHR_xlib_surface;
bool KHR_xcb_surface;
#elif defined(_GLFW_WAYLAND)
bool KHR_wayland_surface;
#endif
} vk;
struct {
GLFWmonitorfun monitor;
GLFWjoystickfun joystick;
GLFWapplicationclosefun application_close;
GLFWclipboardlostfun clipboard_lost;
GLFWsystemcolorthemechangefun system_color_theme_change;
GLFWdrawtextfun draw_text;
GLFWcurrentselectionfun get_current_selection;
GLFWhascurrentselectionfun has_current_selection;
GLFWimecursorpositionfun get_ime_cursor_position;
GLFWimetextaroundcursorfun get_ime_text_around_cursor;
} callbacks;
// This is defined in the window API's platform.h
_GLFW_PLATFORM_LIBRARY_WINDOW_STATE;
// This is defined in the context API's context.h
_GLFW_PLATFORM_LIBRARY_CONTEXT_STATE
// This is defined in the platform's joystick.h
_GLFW_PLATFORM_LIBRARY_JOYSTICK_STATE
// This is defined in egl_context.h
_GLFWlibraryEGL egl;
// This is defined in osmesa_context.h
_GLFWlibraryOSMesa osmesa;
struct {
GLFWDragSourceItem *items;
size_t item_count;
GLFWid window_id, instance_id;
int operations;
bool needs_toplevel_on_wayland;
} drag;
};
// Global state shared between compilation units of GLFW
//
extern _GLFWlibrary _glfw;
typedef struct GeometryRect {
int x, y, width, height;
} GeometryRect;
typedef struct MonitorGeometry {
GeometryRect full, workarea;
} MonitorGeometry;
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
int _glfwPlatformInit(bool *);
void _glfwPlatformTerminate(void);
const char *_glfwPlatformGetVersionString(void);
void _glfwPlatformGetCursorPos(_GLFWwindow *window, double *xpos, double *ypos);
void _glfwPlatformSetCursorPos(_GLFWwindow *window, double xpos, double ypos);
void _glfwPlatformSetCursorMode(_GLFWwindow *window, int mode);
void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window, bool enabled);
bool _glfwPlatformRawMouseMotionSupported(void);
int _glfwPlatformCreateCursor(_GLFWcursor *cursor, const GLFWimage *image, int xhot, int yhot, int count);
int _glfwPlatformCreateStandardCursor(_GLFWcursor *cursor, GLFWCursorShape shape);
void _glfwPlatformDestroyCursor(_GLFWcursor *cursor);
void _glfwPlatformSetCursor(_GLFWwindow *window, _GLFWcursor *cursor);
const char *_glfwPlatformGetNativeKeyName(int native_key);
int _glfwPlatformGetNativeKeyForKey(uint32_t key);
void _glfwPlatformFreeMonitor(_GLFWmonitor *monitor);
void _glfwPlatformGetMonitorPos(_GLFWmonitor *monitor, int *xpos, int *ypos);
void _glfwPlatformGetMonitorContentScale(_GLFWmonitor *monitor, float *xscale, float *yscale);
void _glfwPlatformGetMonitorWorkarea(_GLFWmonitor *monitor, int *xpos, int *ypos, int *width, int *height);
GLFWvidmode *_glfwPlatformGetVideoModes(_GLFWmonitor *monitor, int *count);
bool _glfwPlatformGetVideoMode(_GLFWmonitor *monitor, GLFWvidmode *mode);
bool _glfwPlatformGetGammaRamp(_GLFWmonitor *monitor, GLFWgammaramp *ramp);
void _glfwPlatformSetGammaRamp(_GLFWmonitor *monitor, const GLFWgammaramp *ramp);
void _glfwPlatformSetClipboard(GLFWClipboardType t);
void _glfwPlatformGetClipboard(GLFWClipboardType clipboard_type, const char *mime_type, GLFWclipboardwritedatafun write_data, void *object);
bool _glfwPlatformInitJoysticks(void);
void _glfwPlatformTerminateJoysticks(void);
int _glfwPlatformPollJoystick(_GLFWjoystick *js, int mode);
void _glfwPlatformUpdateGamepadGUID(char *guid);
int _glfwPlatformCreateWindow(
_GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, const GLFWLayerShellConfig *lsc);
void _glfwPlatformDestroyWindow(_GLFWwindow *window);
void _glfwPlatformSetWindowTitle(_GLFWwindow *window, const char *title);
void _glfwPlatformSetWindowIcon(_GLFWwindow *window, int count, const GLFWimage *images);
bool _glfwPlatformSetLayerShellConfig(_GLFWwindow *window, const GLFWLayerShellConfig *value);
const GLFWLayerShellConfig *_glfwPlatformGetLayerShellConfig(_GLFWwindow *window);
void _glfwPlatformGetWindowPos(_GLFWwindow *window, int *xpos, int *ypos);
void _glfwPlatformSetWindowPos(_GLFWwindow *window, int xpos, int ypos);
void _glfwPlatformGetWindowSize(_GLFWwindow *window, int *width, int *height);
void _glfwPlatformSetWindowSize(_GLFWwindow *window, int width, int height);
void _glfwPlatformSetWindowSizeLimits(_GLFWwindow *window, int minwidth, int minheight, int maxwidth, int maxheight);
void _glfwPlatformSetWindowAspectRatio(_GLFWwindow *window, int numer, int denom);
void _glfwPlatformSetWindowSizeIncrements(_GLFWwindow *window, int widthincr, int heightincr);
void _glfwPlatformGetFramebufferSize(_GLFWwindow *window, int *width, int *height);
void _glfwInputLiveResize(_GLFWwindow *window, bool started);
void _glfwPlatformGetWindowFrameSize(_GLFWwindow *window, int *left, int *top, int *right, int *bottom);
void _glfwPlatformGetWindowContentScale(_GLFWwindow *window, float *xscale, float *yscale);
monotonic_t _glfwPlatformGetDoubleClickInterval(_GLFWwindow *window);
void _glfwPlatformGetKeyboardRepeatDelay(monotonic_t *delay, monotonic_t *interval);
void _glfwPlatformIconifyWindow(_GLFWwindow *window);
void _glfwPlatformRestoreWindow(_GLFWwindow *window);
void _glfwPlatformMaximizeWindow(_GLFWwindow *window);
void _glfwPlatformShowWindow(_GLFWwindow *window, bool move_to_active_screen);
void _glfwPlatformHideWindow(_GLFWwindow *window);
void _glfwPlatformRequestWindowAttention(_GLFWwindow *window);
int _glfwPlatformWindowBell(_GLFWwindow *window);
void _glfwPlatformFocusWindow(_GLFWwindow *window);
void _glfwPlatformSetWindowMonitor(_GLFWwindow *window, _GLFWmonitor *monitor, int xpos, int ypos, int width, int height, int refreshRate);
bool _glfwPlatformToggleFullscreen(_GLFWwindow *w, unsigned int flags);
bool _glfwPlatformIsFullscreen(_GLFWwindow *w, unsigned int flags);
int _glfwPlatformWindowFocused(_GLFWwindow *window);
int _glfwPlatformWindowOccluded(_GLFWwindow *window);
int _glfwPlatformWindowIconified(_GLFWwindow *window);
int _glfwPlatformWindowVisible(_GLFWwindow *window);
int _glfwPlatformWindowMaximized(_GLFWwindow *window);
int _glfwPlatformWindowHovered(_GLFWwindow *window);
int _glfwPlatformFramebufferTransparent(_GLFWwindow *window);
float _glfwPlatformGetWindowOpacity(_GLFWwindow *window);
void _glfwPlatformSetWindowResizable(_GLFWwindow *window, bool enabled);
void _glfwPlatformSetWindowDecorated(_GLFWwindow *window, bool enabled);
void _glfwPlatformSetWindowFloating(_GLFWwindow *window, bool enabled);
void _glfwPlatformSetWindowMousePassthrough(_GLFWwindow *window, bool enabled);
void _glfwPlatformSetWindowOpacity(_GLFWwindow *window, float opacity);
void _glfwPlatformUpdateIMEState(_GLFWwindow *w, const GLFWIMEUpdateEvent *ev);
void _glfwPlatformChangeCursorTheme(void);
void _glfwPlatformTitlebarSettingsChanged(void);
void _glfwPlatformPollEvents(void);
void _glfwPlatformWaitEvents(void);
void _glfwPlatformWaitEventsTimeout(monotonic_t timeout);
void _glfwPlatformPostEmptyEvent(void);
EGLenum _glfwPlatformGetEGLPlatform(EGLint **attribs);
EGLNativeDisplayType _glfwPlatformGetEGLNativeDisplay(void);
EGLNativeWindowType _glfwPlatformGetEGLNativeWindow(_GLFWwindow *window);
void _glfwPlatformGetRequiredInstanceExtensions(char **extensions);
int _glfwPlatformGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice device, uint32_t queuefamily);
VkResult _glfwPlatformCreateWindowSurface(VkInstance instance, _GLFWwindow *window, const VkAllocationCallbacks *allocator, VkSurfaceKHR *surface);
bool _glfwPlatformCreateTls(_GLFWtls *tls);
void _glfwPlatformDestroyTls(_GLFWtls *tls);
void *_glfwPlatformGetTls(_GLFWtls *tls);
void _glfwPlatformSetTls(_GLFWtls *tls, void *value);
bool _glfwPlatformCreateMutex(_GLFWmutex *mutex);
void _glfwPlatformDestroyMutex(_GLFWmutex *mutex);
void _glfwPlatformLockMutex(_GLFWmutex *mutex);
void _glfwPlatformUnlockMutex(_GLFWmutex *mutex);
//////////////////////////////////////////////////////////////////////////
////// GLFW event API //////
//////////////////////////////////////////////////////////////////////////
void _glfwInputWindowFocus(_GLFWwindow *window, bool focused);
void _glfwInputWindowOcclusion(_GLFWwindow *window, bool occluded);
void _glfwInputWindowPos(_GLFWwindow *window, int xpos, int ypos);
void _glfwInputWindowSize(_GLFWwindow *window, int width, int height);
void _glfwInputFramebufferSize(_GLFWwindow *window, int width, int height);
void _glfwInputWindowContentScale(_GLFWwindow *window, float xscale, float yscale);
void _glfwInputWindowIconify(_GLFWwindow *window, bool iconified);
void _glfwInputWindowMaximize(_GLFWwindow *window, bool maximized);
void _glfwInputWindowDamage(_GLFWwindow *window);
void _glfwInputWindowCloseRequest(_GLFWwindow *window);
void _glfwInputWindowMonitor(_GLFWwindow *window, _GLFWmonitor *monitor);
void _glfwInputKeyboard(_GLFWwindow *window, GLFWkeyevent *ev);
void _glfwInputClipboardLost(GLFWClipboardType which);
void _glfwInputScroll(_GLFWwindow *window, const GLFWScrollEvent *ev);
void _glfwInputTouch(_GLFWwindow *window, const GLFWTouchEvent *ev);
void _glfwInputMouseClick(_GLFWwindow *window, int button, int action, int mods);
void _glfwInputCursorPos(_GLFWwindow *window, double xpos, double ypos);
void _glfwInputCursorEnter(_GLFWwindow *window, bool entered);
// Platform functions for drop data reading
void _glfwPlatformRequestDropUpdate(_GLFWwindow *window);
size_t _glfwInputDropEvent(_GLFWwindow *window, GLFWDropEventType type, double xpos, double ypos, const char **mimes, size_t num_mimes, bool from_self);
ssize_t _glfwPlatformReadAvailableDropData(GLFWwindow *w, GLFWDropEvent *ev, char *buffer, size_t sz);
void _glfwPlatformEndDrop(GLFWwindow *w, GLFWDragOperationType op);
int _glfwPlatformRequestDropData(_GLFWwindow *window, const char *mime);
// Platform functions for drag source
int _glfwPlatformStartDrag(_GLFWwindow *window, const GLFWimage *thumbnail);
void _glfwPlatformCancelDrag(_GLFWwindow *window);
void _glfwFreeDragSourceData(void);
void _glfwPlatformFreeDragSourceData(void);
void _glfwInputDragSourceRequest(_GLFWwindow *window, GLFWDragEvent *ev);
int _glfwPlatformDragDataReady(const char *mime_type, const char *data, size_t sz, int type);
int _glfwPlatformChangeDragImage(const GLFWimage *thumbnail);
void _glfwInputColorScheme(GLFWColorScheme, bool);
void _glfwPlatformInputColorScheme(GLFWColorScheme);
void _glfwInputJoystick(_GLFWjoystick *js, int event);
void _glfwInputJoystickAxis(_GLFWjoystick *js, int axis, float value);
void _glfwInputJoystickButton(_GLFWjoystick *js, int button, char value);
void _glfwInputJoystickHat(_GLFWjoystick *js, int hat, char value);
void _glfwInputMonitor(_GLFWmonitor *monitor, int action, int placement);
void _glfwInputMonitorWindow(_GLFWmonitor *monitor, _GLFWwindow *window);
#if defined(__GNUC__) || defined(__clang__)
void _glfwInputError(int code, const char *format, ...) __attribute__((format(printf, 2, 3)));
void _glfwDebug(const char *format, ...) __attribute__((format(printf, 1, 2)));
#else
void _glfwInputError(int code, const char *format, ...);
void _glfwDebug(const char *format, ...);
#endif
#ifdef DEBUG_EVENT_LOOP
#define EVDBG(...) _glfwDebug(__VA_ARGS__)
#else
#define EVDBG(...)
#endif
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
bool _glfwStringInExtensionString(const char *string, const char *extensions);
bool _glfwRefreshContextAttribs(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig);
bool _glfwIsValidContextConfig(const _GLFWctxconfig *ctxconfig);
const GLFWvidmode *_glfwChooseVideoMode(_GLFWmonitor *monitor, const GLFWvidmode *desired);
int _glfwCompareVideoModes(const GLFWvidmode *first, const GLFWvidmode *second);
_GLFWmonitor *_glfwAllocMonitor(const char *name, int widthMM, int heightMM);
void _glfwFreeMonitor(_GLFWmonitor *monitor);
void _glfwAllocGammaArrays(GLFWgammaramp *ramp, unsigned int size);
void _glfwFreeGammaArrays(GLFWgammaramp *ramp);
void _glfwSplitBPP(int bpp, int *red, int *green, int *blue);
_GLFWjoystick *_glfwAllocJoystick(const char *name, const char *guid, int axisCount, int buttonCount, int hatCount);
void _glfwFreeJoystick(_GLFWjoystick *js);
const char *_glfwGetKeyName(int key);
void _glfwCenterCursorInContentArea(_GLFWwindow *window);
bool _glfwInitVulkan(int mode);
void _glfwTerminateVulkan(void);
const char *_glfwGetVulkanResultString(VkResult result);
_GLFWwindow *_glfwFocusedWindow(void);
_GLFWwindow *_glfwWindowForId(GLFWid id);
void _glfwPlatformRunMainLoop(GLFWtickcallback, void *);
void _glfwPlatformStopMainLoop(void);
unsigned long long _glfwPlatformAddTimer(monotonic_t interval, bool repeats, GLFWuserdatafun callback, void *callback_data, GLFWuserdatafun free_callback);
void _glfwPlatformUpdateTimer(unsigned long long timer_id, monotonic_t interval, bool enabled);
void _glfwPlatformRemoveTimer(unsigned long long timer_id);
int _glfwPlatformSetWindowBlur(_GLFWwindow *handle, int value);
MonitorGeometry _glfwPlatformGetMonitorGeometry(_GLFWmonitor *monitor);
bool _glfwPlatformGrabKeyboard(bool grab);
void glfw_handle_scroll_event_for_momentum(_GLFWwindow *w, const GLFWScrollEvent *ev, bool stopped, bool is_finger_based);
#define glfw_cancel_momentum_scroll() glfw_handle_scroll_event_for_momentum(NULL, NULL, false, false)
#ifdef _GLFW_X11
#define momentum_scroll_gesture_detection_timeout_ms 50
#else
#define momentum_scroll_gesture_detection_timeout_ms 0
#endif
bool glfw_is_momentum_scroll_enabled(void);
char *_glfw_strdup(const char *source);
void _glfw_free_clipboard_data(_GLFWClipboardData *cd);
#define debug_rendering(...) \
if (_glfw.hints.init.debugRendering) { timed_debug_print(__VA_ARGS__); }
#define debug_input(...) \
if (_glfw.hints.init.debugKeyboard) { timed_debug_print(__VA_ARGS__); }
#define safe_close(fd) \
do { \
errno = 0; \
close(fd); \
} while (errno == EINTR)
int _glfwApplyModifierRemap(int mods);
+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="blur">
<copyright><![CDATA[
SPDX-FileCopyrightText: 2015 Martin Gräßlin
SPDX-FileCopyrightText: 2015 Marco Martin
SPDX-License-Identifier: LGPL-2.1-or-later
]]></copyright>
<interface name="org_kde_kwin_blur_manager" version="1">
<request name="create">
<arg name="id" type="new_id" interface="org_kde_kwin_blur"/>
<arg name="surface" type="object" interface="wl_surface"/>
</request>
<request name="unset">
<arg name="surface" type="object" interface="wl_surface"/>
</request>
</interface>
<interface name="org_kde_kwin_blur" version="1">
<request name="commit">
</request>
<request name="set_region">
<arg name="region" type="object" interface="wl_region" allow-null="true"/>
</request>
<request name="release" type="destructor">
<description summary="release the blur object"/>
</request>
</interface>
</protocol>
+638
View File
@@ -0,0 +1,638 @@
/*
* linux_cursor_settings.c
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "linux_desktop_settings.h"
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <math.h>
#define DESKTOP_SERVICE "org.freedesktop.portal.Desktop"
#define DESKTOP_PATH "/org/freedesktop/portal/desktop"
#define DESKTOP_INTERFACE "org.freedesktop.portal.Settings"
#define GNOME_DESKTOP_NAMESPACE "org.gnome.desktop.interface"
#define GNOME_WM_NAMESPACE "org.gnome.desktop.wm.preferences"
#define FDO_DESKTOP_NAMESPACE "org.freedesktop.appearance"
static const char *supported_namespaces[3] = {FDO_DESKTOP_NAMESPACE, GNOME_DESKTOP_NAMESPACE, GNOME_WM_NAMESPACE};
#define FDO_APPEARANCE_KEY "color-scheme"
static char theme_name[128] = {0};
static char interface_font[256];
static char titlebar_font[256];
static bool titlebar_uses_system_font = true;
static double titlebar_text_scale = 1.;
static GLFWTitlebarAction titlebar_actions[TITLEBAR_GESTURE_COUNT] = {TITLEBAR_ACTION_MAXIMIZE, TITLEBAR_ACTION_NONE, TITLEBAR_ACTION_MENU};
GLFWTitlebarAction
glfw_current_titlebar_action(GLFWTitlebarGesture gesture) {
return gesture < arraysz(titlebar_actions) ? titlebar_actions[gesture] : TITLEBAR_ACTION_NONE;
}
static GLFWTitlebarButtonLayout button_layout = {.right = {TITLEBAR_BUTTON_MINIMIZE, TITLEBAR_BUTTON_MAXIMIZE, TITLEBAR_BUTTON_CLOSE}, .right_count = 3};
const GLFWTitlebarButtonLayout *
glfw_current_titlebar_button_layout(void) {
return &button_layout;
}
static char current_titlebar_family[256];
static GLFWTitlebarFont current_titlebar_font = {.point_size = 11, .text_scale = 1, .bold = true};
static bool
is_one_of(const char *word, const char **names) {
for (; *names; names++)
if (strcasecmp(word, *names) == 0) return true;
return false;
}
static char *
rstrip_font_description(char *buf, char *end) {
while (end > buf && (end[-1] == ' ' || end[-1] == ',')) *--end = 0;
return end;
}
static char *
last_word(char *buf, char *end) {
while (end > buf && end[-1] != ' ') end--;
return end;
}
static void
parse_font_description(const char *description, bool default_bold, char *family, size_t family_sz, GLFWTitlebarFont *ans) {
// Parses the subset of Pango font descriptions used in practice:
// "[FAMILY-LIST] [STYLE-OPTIONS] [SIZE[px]]"
static const char *bold_weights[] = {
"semi-bold",
"semibold",
"demi-bold",
"demibold",
"bold",
"ultra-bold",
"ultrabold",
"extra-bold",
"extrabold",
"heavy",
"ultra-heavy",
"ultraheavy",
"black",
"ultra-black",
"ultrablack",
"extra-black",
"extrablack",
NULL};
static const char *normal_weights[] = {
"thin",
"ultra-light",
"ultralight",
"extra-light",
"extralight",
"light",
"semi-light",
"semilight",
"demi-light",
"demilight",
"book",
"regular",
"normal",
"medium",
"roman",
NULL};
static const char *italic_styles[] = {"italic", "oblique", NULL};
static const char *ignored_styles[] = {
"ultra-condensed",
"extra-condensed",
"condensed",
"semi-condensed",
"semi-expanded",
"expanded",
"extra-expanded",
"ultra-expanded",
"small-caps",
NULL};
char buf[256];
snprintf(buf, sizeof(buf), "%s", description ? description : "");
ans->point_size = 11;
ans->bold = default_bold;
ans->italic = false;
char *end = rstrip_font_description(buf, buf + strlen(buf));
char *word = last_word(buf, end);
if (*word) {
char *num_end;
double size = strtod(word, &num_end);
const bool is_px = strcmp(num_end, "px") == 0;
if (num_end != word && (!*num_end || is_px)) {
if (is_px) size *= 72. / 96.;
if (isfinite(size) && size >= 1 && size <= 200) ans->point_size = size;
*word = 0;
end = rstrip_font_description(buf, word);
}
}
while ((word = last_word(buf, end)) > buf) {
if (is_one_of(word, bold_weights)) ans->bold = true;
else if (is_one_of(word, normal_weights)) ans->bold = false;
else if (is_one_of(word, italic_styles)) ans->italic = true;
else if (!is_one_of(word, ignored_styles)) break;
*word = 0;
end = rstrip_font_description(buf, word);
}
// Only the first family of a family list is used
char *comma = strchr(buf, ',');
if (comma) {
*comma = 0;
rstrip_font_description(buf, comma);
}
snprintf(family, family_sz, "%s", buf);
ans->family = family[0] ? family : NULL;
}
const GLFWTitlebarFont *
glfw_current_titlebar_font(void) {
return &current_titlebar_font;
}
unsigned
glfw_current_titlebar_height(void) {
const double scale = current_titlebar_font.text_scale;
const double text_height = current_titlebar_font.point_size * scale * 96. / 72.;
return (unsigned)ceil(fmax(38. * fmax(1, scale), text_height + 18));
}
static bool titlebar_settings_dirty = false;
static unsigned long long titlebar_redraw_timer = 0;
static void
redraw_titlebars(void) {
titlebar_settings_dirty = false;
const bool use_system_font = titlebar_uses_system_font || !titlebar_font[0];
// GNOME uses a bold version of the interface font for titles
parse_font_description(
use_system_font ? interface_font : titlebar_font, use_system_font, current_titlebar_family, sizeof(current_titlebar_family), &current_titlebar_font);
current_titlebar_font.text_scale = titlebar_text_scale;
#ifndef _GLFW_X11
_glfwPlatformTitlebarSettingsChanged();
#endif
}
static void
redraw_titlebars_if_dirty(void) {
if (titlebar_settings_dirty) redraw_titlebars();
}
static void
on_titlebar_redraw_timer(unsigned long long timer_id UNUSED, void *data UNUSED) {
titlebar_redraw_timer = 0;
redraw_titlebars_if_dirty();
}
static void
schedule_titlebar_redraw(void) {
// The portal sends one SettingChanged signal per key, so coalesce a burst
// of changes, such as a font and scale change, into a single redraw.
if (!titlebar_settings_dirty || titlebar_redraw_timer) return;
titlebar_redraw_timer = _glfwPlatformAddTimer(ms_to_monotonic_t(10ll), false, on_titlebar_redraw_timer, NULL, NULL);
if (!titlebar_redraw_timer) redraw_titlebars();
}
static bool
parse_button_layout(const char *value, GLFWTitlebarButtonLayout *out) {
if (!value || strlen(value) >= 256) return false;
char copy[256];
snprintf(copy, sizeof(copy), "%s", value);
// Same semantics as GTK: buttons before the colon are on the left, after it
// on the right, no colon means all buttons are on the left.
char *colon = strchr(copy, ':');
if (colon) *colon = 0;
memset(out, 0, sizeof(*out));
bool seen[TITLEBAR_BUTTON_COUNT] = {false};
for (int side = 0; side < 2; side++) {
char *token = side ? (colon ? colon + 1 : NULL) : copy;
while (token && *token) {
char *next = strchr(token, ',');
if (next) *next++ = 0;
while (*token == ' ') token++;
char *end = token + strlen(token);
while (end > token && end[-1] == ' ') *--end = 0;
const GLFWTitlebarButton id = strcmp(token, "close") == 0 ? TITLEBAR_BUTTON_CLOSE
: strcmp(token, "maximize") == 0 ? TITLEBAR_BUTTON_MAXIMIZE
: strcmp(token, "minimize") == 0 ? TITLEBAR_BUTTON_MINIMIZE
: TITLEBAR_BUTTON_NONE;
if (id && !seen[id]) {
seen[id] = true;
if (side) out->right[out->right_count++] = id;
else out->left[out->left_count++] = id;
}
token = next;
}
}
return true;
}
static bool
read_string_setting(DBusMessageIter *value, char *dest, size_t capacity) {
if (dbus_message_iter_get_arg_type(value) != DBUS_TYPE_STRING) return false;
const char *text;
dbus_message_iter_get_basic(value, &text);
if (!text || !text[0] || strlen(text) >= capacity || strcmp(dest, text) == 0) return false;
snprintf(dest, capacity, "%s", text);
return true;
}
static void
process_wm_setting(const char *key, DBusMessageIter *value) {
bool changed = false;
if (strcmp(key, "titlebar-font") == 0) changed = read_string_setting(value, titlebar_font, sizeof(titlebar_font));
else if (strcmp(key, "titlebar-uses-system-font") == 0 && dbus_message_iter_get_arg_type(value) == DBUS_TYPE_BOOLEAN) {
dbus_bool_t flag;
dbus_message_iter_get_basic(value, &flag);
changed = titlebar_uses_system_font != (flag != 0);
titlebar_uses_system_font = flag != 0;
} else if (strcmp(key, "button-layout") == 0 && dbus_message_iter_get_arg_type(value) == DBUS_TYPE_STRING) {
const char *text;
dbus_message_iter_get_basic(value, &text);
GLFWTitlebarButtonLayout parsed;
if (parse_button_layout(text, &parsed) && memcmp(&parsed, &button_layout, sizeof(parsed)) != 0) {
button_layout = parsed;
changed = true;
}
}
static const char *action_keys[TITLEBAR_GESTURE_COUNT] = {
[TITLEBAR_GESTURE_DOUBLE_CLICK] = "action-double-click-titlebar",
[TITLEBAR_GESTURE_MIDDLE_CLICK] = "action-middle-click-titlebar",
[TITLEBAR_GESTURE_RIGHT_CLICK] = "action-right-click-titlebar",
};
for (unsigned i = 0; i < arraysz(action_keys); i++) {
if (strcmp(key, action_keys[i]) == 0 && dbus_message_iter_get_arg_type(value) == DBUS_TYPE_STRING) {
const char *name;
dbus_message_iter_get_basic(value, &name);
// xdg-shell has no lower/shade or one-axis maximize request.
GLFWTitlebarAction action = strcmp(name, "menu") == 0 ? TITLEBAR_ACTION_MENU
: strcmp(name, "toggle-maximize") == 0 ? TITLEBAR_ACTION_MAXIMIZE
: strcmp(name, "minimize") == 0 ? TITLEBAR_ACTION_MINIMIZE
: TITLEBAR_ACTION_NONE;
changed |= action != titlebar_actions[i];
titlebar_actions[i] = action;
break;
}
}
titlebar_settings_dirty |= changed;
}
static int theme_size = -1;
static GLFWColorScheme appearance = GLFW_COLOR_SCHEME_NO_PREFERENCE;
static bool cursor_theme_changed = false, appearance_initialized = false;
static bool desktop_settings_pending = false, desktop_settings_received = false;
static void
set_queried_appearance(uint32_t value) {
if (value < 3 && appearance != (GLFWColorScheme)value) {
appearance = value;
redraw_titlebars();
}
}
#define HANDLER(name_) \
static void name_(DBusMessage *msg, const DBusError *err, void *data) { \
(void)data; \
if (err) { \
_glfwInputError(GLFW_PLATFORM_ERROR, "%s: failed with error: %s: %s", #name_, err->name, err->message); \
return; \
}
HANDLER(get_color_scheme_legacy)
DBusMessageIter iter, variant_iter, value_iter;
if (!dbus_message_iter_init(msg, &iter) || dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Read for color-scheme did not return a variant");
return;
}
dbus_message_iter_recurse(&iter, &variant_iter);
// The deprecated Read method wraps the value in a second variant
if (dbus_message_iter_get_arg_type(&variant_iter) != DBUS_TYPE_VARIANT) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Read for color-scheme did not return a nested variant");
return;
}
dbus_message_iter_recurse(&variant_iter, &value_iter);
if (dbus_message_iter_get_arg_type(&value_iter) != DBUS_TYPE_UINT32) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Read for color-scheme did not return a uint32");
return;
}
uint32_t val;
dbus_message_iter_get_basic(&value_iter, &val);
set_queried_appearance(val);
}
static void
get_color_scheme(DBusMessage *msg, const DBusError *err, void *data) {
(void)data;
if (err) {
if (strcmp("org.freedesktop.DBus.Error.UnknownMethod", err->name) == 0) {
DBusConnection *session_bus = glfw_dbus_session_bus();
if (session_bus) {
const char *namespace = FDO_DESKTOP_NAMESPACE, *key = FDO_APPEARANCE_KEY;
glfw_dbus_call_blocking_method(
session_bus,
DESKTOP_SERVICE,
DESKTOP_PATH,
DESKTOP_INTERFACE,
"Read",
DBUS_TIMEOUT_USE_DEFAULT,
get_color_scheme_legacy,
NULL,
DBUS_TYPE_STRING,
&namespace,
DBUS_TYPE_STRING,
&key,
DBUS_TYPE_INVALID);
}
return;
} else {
_glfwInputError(GLFW_PLATFORM_ERROR, "%s: failed with error: %s: %s", "get_color_scheme", err->name, err->message);
return;
}
}
uint32_t val;
DBusMessageIter iter, variant_iter;
if (!dbus_message_iter_init(msg, &iter) || dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
_glfwInputError(GLFW_PLATFORM_ERROR, "ReadOne for color-scheme did not return a variant");
return;
}
dbus_message_iter_recurse(&iter, &variant_iter);
int type = dbus_message_iter_get_arg_type(&variant_iter);
if (type != DBUS_TYPE_UINT32) {
_glfwInputError(GLFW_PLATFORM_ERROR, "ReadOne for color-scheme did not return a uint32");
return;
}
dbus_message_iter_get_basic(&variant_iter, &val);
set_queried_appearance(val);
}
static void
wait_for_desktop_settings(monotonic_t timeout) {
const monotonic_t deadline = monotonic() + timeout;
for (monotonic_t now = monotonic(); desktop_settings_pending && now < deadline; now = monotonic()) {
if (!glfw_dbus_session_bus_read_write_dispatch(MAX(1, (int)monotonic_t_to_ms_ceil(deadline - now)))) break;
}
}
GLFWColorScheme
glfw_current_system_color_theme(bool query_if_unintialized) {
if (!appearance_initialized && query_if_unintialized) {
// The ReadAll request sent at startup includes color-scheme, so wait for
// its reply instead of making a second, blocking, request to the portal.
if (desktop_settings_pending) wait_for_desktop_settings(ms_to_monotonic_t(1000ll));
// If ReadAll succeeded without a color-scheme the portal does not provide one
const bool needs_query = !appearance_initialized && !desktop_settings_received;
appearance_initialized = true;
DBusConnection *session_bus = needs_query ? glfw_dbus_session_bus() : NULL;
if (session_bus) {
const char *namespace = FDO_DESKTOP_NAMESPACE, *key = FDO_APPEARANCE_KEY;
glfw_dbus_call_blocking_method(
session_bus,
DESKTOP_SERVICE,
DESKTOP_PATH,
DESKTOP_INTERFACE,
"ReadOne",
DBUS_TIMEOUT_USE_DEFAULT,
get_color_scheme,
NULL,
DBUS_TYPE_STRING,
&namespace,
DBUS_TYPE_STRING,
&key,
DBUS_TYPE_INVALID);
}
}
return appearance;
}
static void
process_fdo_setting(const char *key, DBusMessageIter *value) {
if (strcmp(key, FDO_APPEARANCE_KEY) == 0) {
if (dbus_message_iter_get_arg_type(value) == DBUS_TYPE_UINT32) {
uint32_t val;
dbus_message_iter_get_basic(value, &val);
if (val > 2) val = 0;
if (!appearance_initialized) {
appearance_initialized = true;
if (val != appearance) {
appearance = val;
_glfwInputColorScheme(appearance, true);
}
}
}
}
}
static void
process_gnome_setting(const char *key, DBusMessageIter *value) {
if (strcmp(key, "cursor-size") == 0) {
if (dbus_message_iter_get_arg_type(value) == DBUS_TYPE_INT32) {
int32_t sz;
dbus_message_iter_get_basic(value, &sz);
if (sz > 0 && sz != theme_size) {
theme_size = sz;
cursor_theme_changed = true;
}
}
} else if (strcmp(key, "font-name") == 0) {
if (read_string_setting(value, interface_font, sizeof(interface_font))) titlebar_settings_dirty = true;
} else if (strcmp(key, "text-scaling-factor") == 0 && dbus_message_iter_get_arg_type(value) == DBUS_TYPE_DOUBLE) {
double factor;
dbus_message_iter_get_basic(value, &factor);
if (isfinite(factor) && factor >= .5 && factor <= 4 && factor != titlebar_text_scale) {
titlebar_text_scale = factor;
titlebar_settings_dirty = true;
}
} else if (strcmp(key, "cursor-theme") == 0) {
if (dbus_message_iter_get_arg_type(value) == DBUS_TYPE_STRING) {
const char *name;
dbus_message_iter_get_basic(value, &name);
if (name && strncmp(theme_name, name, sizeof(theme_name) - 1) != 0) {
strncpy(theme_name, name, sizeof(theme_name) - 1);
cursor_theme_changed = true;
}
}
}
}
static void
process_settings_dict(DBusMessageIter *array_iter, void(process_setting)(const char *, DBusMessageIter *)) {
DBusMessageIter item_iter, value_iter;
while (dbus_message_iter_get_arg_type(array_iter) == DBUS_TYPE_DICT_ENTRY) {
dbus_message_iter_recurse(array_iter, &item_iter);
if (dbus_message_iter_get_arg_type(&item_iter) == DBUS_TYPE_STRING) {
const char *key;
dbus_message_iter_get_basic(&item_iter, &key);
if (dbus_message_iter_next(&item_iter) && dbus_message_iter_get_arg_type(&item_iter) == DBUS_TYPE_VARIANT) {
dbus_message_iter_recurse(&item_iter, &value_iter);
process_setting(key, &value_iter);
}
}
if (!dbus_message_iter_next(array_iter)) break;
}
}
HANDLER(process_desktop_settings)
cursor_theme_changed = false;
DBusMessageIter root, array, item, settings;
dbus_message_iter_init(msg, &root);
#define die(...) \
{ \
_glfwInputError(GLFW_PLATFORM_ERROR, __VA_ARGS__); \
return; \
}
if (dbus_message_iter_get_arg_type(&root) != DBUS_TYPE_ARRAY) die("Reply to request for desktop settings is not an array");
desktop_settings_received = true;
dbus_message_iter_recurse(&root, &array);
while (dbus_message_iter_get_arg_type(&array) == DBUS_TYPE_DICT_ENTRY) {
dbus_message_iter_recurse(&array, &item);
if (dbus_message_iter_get_arg_type(&item) == DBUS_TYPE_STRING) {
const char *namespace;
dbus_message_iter_get_basic(&item, &namespace);
if (dbus_message_iter_next(&item) && dbus_message_iter_get_arg_type(&item) == DBUS_TYPE_ARRAY) {
dbus_message_iter_recurse(&item, &settings);
if (strcmp(namespace, FDO_DESKTOP_NAMESPACE) == 0) {
process_settings_dict(&settings, process_fdo_setting);
} else if (strcmp(namespace, GNOME_DESKTOP_NAMESPACE) == 0) {
process_settings_dict(&settings, process_gnome_setting);
} else if (strcmp(namespace, GNOME_WM_NAMESPACE) == 0) {
process_settings_dict(&settings, process_wm_setting);
}
}
}
if (!dbus_message_iter_next(&array)) break;
}
#undef die
redraw_titlebars_if_dirty();
#ifndef _GLFW_X11
if (cursor_theme_changed) _glfwPlatformChangeCursorTheme();
#endif
}
#undef HANDLER
static void
on_desktop_settings_reply(DBusMessage *msg, const DBusError *err, void *data) {
desktop_settings_pending = false;
process_desktop_settings(msg, err, data);
}
static bool
read_desktop_settings(DBusConnection *session_bus) {
RAII_MSG(msg, dbus_message_new_method_call(DESKTOP_SERVICE, DESKTOP_PATH, DESKTOP_INTERFACE, "ReadAll"));
if (!msg) return false;
DBusMessageIter iter, array_iter;
dbus_message_iter_init_append(msg, &iter);
if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &array_iter)) { return false; }
for (unsigned i = 0; i < arraysz(supported_namespaces); ++i) {
if (!dbus_message_iter_append_basic(&array_iter, DBUS_TYPE_STRING, &supported_namespaces[i])) return false;
}
if (!dbus_message_iter_close_container(&iter, &array_iter)) { return false; }
desktop_settings_pending = call_method_with_msg(session_bus, msg, DBUS_TIMEOUT_USE_DEFAULT, on_desktop_settings_reply, NULL, false);
return desktop_settings_pending;
}
void
glfw_wait_for_desktop_settings(monotonic_t timeout) {
// Wait for the reply to the asynchronous ReadAll request sent at startup,
// dispatching only the session bus. Only done once, for the first window.
static bool waited = false;
if (waited || !desktop_settings_pending) return;
waited = true;
wait_for_desktop_settings(timeout);
if (desktop_settings_pending) debug_rendering("Timed out waiting for desktop settings from the portal\n");
}
void
glfw_current_cursor_theme(const char **theme, int *size) {
*theme = theme_name[0] ? theme_name : NULL;
*size = (theme_size > 0 && theme_size < 2048) ? theme_size : 32;
}
static void
get_cursor_theme_from_env(void) {
const char *q = getenv("XCURSOR_THEME");
if (q) strncpy(theme_name, q, sizeof(theme_name) - 1);
const char *env = getenv("XCURSOR_SIZE");
theme_size = 32;
if (env) {
const int retval = atoi(env);
if (retval > 0 && retval < 2048) theme_size = retval;
}
}
static void
on_color_scheme_change(DBusMessage *message) {
DBusMessageIter iter[2];
dbus_message_iter_init(message, &iter[0]);
int current_type;
while ((current_type = dbus_message_iter_get_arg_type(&iter[0])) != DBUS_TYPE_INVALID) {
if (current_type == DBUS_TYPE_VARIANT) {
dbus_message_iter_recurse(&iter[0], &iter[1]);
if (dbus_message_iter_get_arg_type(&iter[1]) == DBUS_TYPE_UINT32) {
uint32_t val = 0;
dbus_message_iter_get_basic(&iter[1], &val);
if (val > 2) val = 0;
if (val != appearance) {
appearance = val;
appearance_initialized = true;
_glfwInputColorScheme(appearance, false);
}
}
break;
}
dbus_message_iter_next(&iter[0]);
}
}
static DBusHandlerResult
setting_changed(DBusConnection *conn UNUSED, DBusMessage *msg, void *user_data UNUSED) {
/* printf("session_bus settings_changed invoked interface: %s member: %s\n", dbus_message_get_interface(msg), dbus_message_get_member(msg)); */
if (dbus_message_is_signal(msg, DESKTOP_INTERFACE, "SettingChanged")) {
const char *namespace = NULL, *key = NULL;
if (glfw_dbus_get_args(
msg,
"Failed to get namespace and key from SettingChanged notification signal",
DBUS_TYPE_STRING,
&namespace,
DBUS_TYPE_STRING,
&key,
DBUS_TYPE_INVALID)) {
if (strcmp(namespace, FDO_DESKTOP_NAMESPACE) == 0) {
if (strcmp(key, FDO_APPEARANCE_KEY) == 0) { on_color_scheme_change(msg); }
} else if (strcmp(namespace, GNOME_DESKTOP_NAMESPACE) == 0 || strcmp(namespace, GNOME_WM_NAMESPACE) == 0) {
DBusMessageIter iter, value;
if (dbus_message_iter_init(msg, &iter) && dbus_message_iter_next(&iter) && dbus_message_iter_next(&iter) &&
dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_VARIANT) {
dbus_message_iter_recurse(&iter, &value);
if (strcmp(namespace, GNOME_WM_NAMESPACE) == 0) process_wm_setting(key, &value);
else {
cursor_theme_changed = false;
process_gnome_setting(key, &value);
#ifndef _GLFW_X11
if (cursor_theme_changed) _glfwPlatformChangeCursorTheme();
#endif
}
schedule_titlebar_redraw();
}
}
}
}
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
void
glfw_initialize_desktop_settings(void) {
get_cursor_theme_from_env();
DBusConnection *session_bus = glfw_dbus_session_bus();
if (session_bus) {
if (!read_desktop_settings(session_bus))
_glfwInputError(GLFW_PLATFORM_ERROR, "WARNING: Failed to read desktop settings, using defaults, make sure you have the desktop portal running.");
dbus_bus_add_match(session_bus, "type='signal',interface='" DESKTOP_INTERFACE "',member='SettingChanged'", NULL);
dbus_connection_add_filter(session_bus, setting_changed, NULL, NULL);
}
}
+30
View File
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "dbus_glfw.h"
#include "internal.h"
void glfw_initialize_desktop_settings(void);
void glfw_wait_for_desktop_settings(monotonic_t timeout);
void glfw_current_cursor_theme(const char **theme, int *size);
GLFWColorScheme glfw_current_system_color_theme(bool);
typedef enum { TITLEBAR_BUTTON_NONE, TITLEBAR_BUTTON_CLOSE, TITLEBAR_BUTTON_MAXIMIZE, TITLEBAR_BUTTON_MINIMIZE, TITLEBAR_BUTTON_COUNT } GLFWTitlebarButton;
typedef struct {
GLFWTitlebarButton left[TITLEBAR_BUTTON_COUNT - 1], right[TITLEBAR_BUTTON_COUNT - 1];
unsigned left_count, right_count;
} GLFWTitlebarButtonLayout;
typedef enum { TITLEBAR_ACTION_NONE, TITLEBAR_ACTION_MENU, TITLEBAR_ACTION_MAXIMIZE, TITLEBAR_ACTION_MINIMIZE } GLFWTitlebarAction;
typedef enum { TITLEBAR_GESTURE_DOUBLE_CLICK, TITLEBAR_GESTURE_MIDDLE_CLICK, TITLEBAR_GESTURE_RIGHT_CLICK, TITLEBAR_GESTURE_COUNT } GLFWTitlebarGesture;
GLFWTitlebarAction glfw_current_titlebar_action(GLFWTitlebarGesture gesture);
const GLFWTitlebarButtonLayout *glfw_current_titlebar_button_layout(void);
unsigned glfw_current_titlebar_height(void);
const GLFWTitlebarFont *glfw_current_titlebar_font(void);
+381
View File
@@ -0,0 +1,381 @@
//========================================================================
// GLFW 3.4 Linux - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#define _POSIX_C_SOURCE 200809L
#include "internal.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#ifndef SYN_DROPPED // < v2.6.39 kernel headers
// Workaround for CentOS-6, which is supported till 2020-11-30, but still on v2.6.32
#define SYN_DROPPED 3
#endif
// Apply an EV_KEY event to the specified joystick
//
static void
handleKeyEvent(_GLFWjoystick *js, int code, int value) {
_glfwInputJoystickButton(js, js->linjs.keyMap[code - BTN_MISC], value ? GLFW_PRESS : GLFW_RELEASE);
}
// Apply an EV_ABS event to the specified joystick
//
static void
handleAbsEvent(_GLFWjoystick *js, int code, int value) {
const int index = js->linjs.absMap[code];
if (code >= ABS_HAT0X && code <= ABS_HAT3Y) {
static const char stateMap[3][3] = {
{GLFW_HAT_CENTERED, GLFW_HAT_UP, GLFW_HAT_DOWN},
{GLFW_HAT_LEFT, GLFW_HAT_LEFT_UP, GLFW_HAT_LEFT_DOWN},
{GLFW_HAT_RIGHT, GLFW_HAT_RIGHT_UP, GLFW_HAT_RIGHT_DOWN},
};
const int hat = (code - ABS_HAT0X) / 2;
const int axis = (code - ABS_HAT0X) % 2;
int *state = js->linjs.hats[hat];
// NOTE: Looking at several input drivers, it seems all hat events use
// -1 for left / up, 0 for centered and 1 for right / down
if (value == 0) state[axis] = 0;
else if (value < 0) state[axis] = 1;
else if (value > 0) state[axis] = 2;
_glfwInputJoystickHat(js, index, stateMap[state[0]][state[1]]);
} else {
const struct input_absinfo *info = &js->linjs.absInfo[code];
float normalized = value;
const int range = info->maximum - info->minimum;
if (range) {
// Normalize to 0.0 -> 1.0
normalized = (normalized - info->minimum) / range;
// Normalize to -1.0 -> 1.0
normalized = normalized * 2.0f - 1.0f;
}
_glfwInputJoystickAxis(js, index, normalized);
}
}
// Poll state of absolute axes
//
static void
pollAbsState(_GLFWjoystick *js) {
for (int code = 0; code < ABS_CNT; code++) {
if (js->linjs.absMap[code] < 0) continue;
struct input_absinfo *info = &js->linjs.absInfo[code];
if (ioctl(js->linjs.fd, EVIOCGABS(code), info) < 0) continue;
handleAbsEvent(js, code, info->value);
}
}
#define isBitSet(bit, arr) (arr[(bit) / 8] & (1 << ((bit) % 8)))
// Attempt to open the specified joystick device
//
static bool
openJoystickDevice(const char *path) {
for (int jid = 0; jid <= GLFW_JOYSTICK_LAST; jid++) {
if (!_glfw.joysticks[jid].present) continue;
if (strcmp(_glfw.joysticks[jid].linjs.path, path) == 0) return false;
}
_GLFWjoystickLinux linjs = {0};
linjs.fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
if (linjs.fd == -1) return false;
char evBits[(EV_CNT + 7) / 8] = {0};
char keyBits[(KEY_CNT + 7) / 8] = {0};
char absBits[(ABS_CNT + 7) / 8] = {0};
struct input_id id;
if (ioctl(linjs.fd, (int32_t)EVIOCGBIT(0, sizeof(evBits)), evBits) < 0 || ioctl(linjs.fd, (int32_t)EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits) < 0 ||
ioctl(linjs.fd, (int32_t)EVIOCGBIT(EV_ABS, sizeof(absBits)), absBits) < 0 || ioctl(linjs.fd, (int32_t)EVIOCGID, &id) < 0) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Linux: Failed to query input device: %s", strerror(errno));
close(linjs.fd);
return false;
}
// Ensure this device supports the events expected of a joystick
if (!isBitSet(EV_KEY, evBits) || !isBitSet(EV_ABS, evBits)) {
close(linjs.fd);
return false;
}
char name[256] = "";
if (ioctl(linjs.fd, (int32_t)EVIOCGNAME(sizeof(name)), name) < 0) strncpy(name, "Unknown", sizeof(name));
char guid[33] = "";
// Generate a joystick GUID that matches the SDL 2.0.5+ one
if (id.vendor && id.product && id.version) {
sprintf(
guid,
"%02x%02x0000%02x%02x0000%02x%02x0000%02x%02x0000",
id.bustype & 0xff,
id.bustype >> 8,
id.vendor & 0xff,
id.vendor >> 8,
id.product & 0xff,
id.product >> 8,
id.version & 0xff,
id.version >> 8);
} else {
sprintf(
guid,
"%02x%02x0000%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x00",
id.bustype & 0xff,
id.bustype >> 8,
name[0],
name[1],
name[2],
name[3],
name[4],
name[5],
name[6],
name[7],
name[8],
name[9],
name[10]);
}
int axisCount = 0, buttonCount = 0, hatCount = 0;
for (int code = BTN_MISC; code < KEY_CNT; code++) {
if (!isBitSet(code, keyBits)) continue;
linjs.keyMap[code - BTN_MISC] = buttonCount;
buttonCount++;
}
for (int code = 0; code < ABS_CNT; code++) {
linjs.absMap[code] = -1;
if (!isBitSet(code, absBits)) continue;
if (code >= ABS_HAT0X && code <= ABS_HAT3Y) {
linjs.absMap[code] = hatCount;
hatCount++;
// Skip the Y axis
code++;
} else {
if (ioctl(linjs.fd, EVIOCGABS(code), &linjs.absInfo[code]) < 0) continue;
linjs.absMap[code] = axisCount;
axisCount++;
}
}
_GLFWjoystick *js = _glfwAllocJoystick(name, guid, axisCount, buttonCount, hatCount);
if (!js) {
close(linjs.fd);
return false;
}
strncpy(linjs.path, path, sizeof(linjs.path) - 1);
memcpy(&js->linjs, &linjs, sizeof(linjs));
pollAbsState(js);
_glfwInputJoystick(js, GLFW_CONNECTED);
return true;
}
#undef isBitSet
// Frees all resources associated with the specified joystick
//
static void
closeJoystick(_GLFWjoystick *js) {
close(js->linjs.fd);
_glfwFreeJoystick(js);
_glfwInputJoystick(js, GLFW_DISCONNECTED);
}
// Lexically compare joysticks by name; used by qsort
//
static int
compareJoysticks(const void *fp, const void *sp) {
const _GLFWjoystick *fj = fp;
const _GLFWjoystick *sj = sp;
return strcmp(fj->linjs.path, sj->linjs.path);
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
void
_glfwDetectJoystickConnectionLinux(void) {
if (_glfw.linjs.inotify <= 0) return;
ssize_t offset = 0;
char buffer[16384];
const ssize_t size = read(_glfw.linjs.inotify, buffer, sizeof(buffer));
while (size > offset) {
regmatch_t match;
const struct inotify_event *e = (struct inotify_event *)(buffer + offset);
offset += sizeof(struct inotify_event) + e->len;
if (regexec(&_glfw.linjs.regex, e->name, 1, &match, 0) != 0) continue;
char path[PATH_MAX];
snprintf(path, sizeof(path), "/dev/input/%s", e->name);
if (e->mask & (IN_CREATE | IN_ATTRIB)) openJoystickDevice(path);
else if (e->mask & IN_DELETE) {
for (int jid = 0; jid <= GLFW_JOYSTICK_LAST; jid++) {
if (strcmp(_glfw.joysticks[jid].linjs.path, path) == 0) {
closeJoystick(_glfw.joysticks + jid);
break;
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
bool
_glfwPlatformInitJoysticks(void) {
const char *dirname = "/dev/input";
_glfw.linjs.inotify = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (_glfw.linjs.inotify > 0) {
// HACK: Register for IN_ATTRIB to get notified when udev is done
// This works well in practice but the true way is libudev
_glfw.linjs.watch = inotify_add_watch(_glfw.linjs.inotify, dirname, IN_CREATE | IN_ATTRIB | IN_DELETE);
}
// Continue without device connection notifications if inotify fails
if (regcomp(&_glfw.linjs.regex, "^event[0-9]\\+$", 0) != 0) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Linux: Failed to compile regex");
return false;
}
int count = 0;
DIR *dir = opendir(dirname);
if (dir) {
struct dirent *entry;
while ((entry = readdir(dir))) {
regmatch_t match;
if (regexec(&_glfw.linjs.regex, entry->d_name, 1, &match, 0) != 0) continue;
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", dirname, entry->d_name);
if (openJoystickDevice(path)) count++;
}
closedir(dir);
}
// Continue with no joysticks if enumeration fails
qsort(_glfw.joysticks, count, sizeof(_glfw.joysticks[0]), compareJoysticks);
return true;
}
void
_glfwPlatformTerminateJoysticks(void) {
int jid;
for (jid = 0; jid <= GLFW_JOYSTICK_LAST; jid++) {
_GLFWjoystick *js = _glfw.joysticks + jid;
if (js->present) closeJoystick(js);
}
if (_glfw.linjs.inotify > 0) {
if (_glfw.linjs.watch > 0) inotify_rm_watch(_glfw.linjs.inotify, _glfw.linjs.watch);
close(_glfw.linjs.inotify);
regfree(&_glfw.linjs.regex);
}
}
int
_glfwPlatformPollJoystick(_GLFWjoystick *js, int mode UNUSED) {
// Read all queued events (non-blocking)
for (;;) {
struct input_event e;
errno = 0;
if (read(js->linjs.fd, &e, sizeof(e)) < 0) {
// Reset the joystick slot if the device was disconnected
if (errno == ENODEV) closeJoystick(js);
break;
}
if (e.type == EV_SYN) {
if (e.code == SYN_DROPPED) _glfw.linjs.dropped = true;
else if (e.code == SYN_REPORT) {
_glfw.linjs.dropped = false;
pollAbsState(js);
}
}
if (_glfw.linjs.dropped) continue;
if (e.type == EV_KEY) handleKeyEvent(js, e.code, e.value);
else if (e.type == EV_ABS) handleAbsEvent(js, e.code, e.value);
}
return js->present;
}
void
_glfwPlatformUpdateGamepadGUID(char *guid UNUSED) {}
+56
View File
@@ -0,0 +1,56 @@
//========================================================================
// GLFW 3.4 Linux - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2014 Jonas Ådahl <jadahl@gmail.com>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <linux/input.h>
#include <linux/limits.h>
#include <regex.h>
#define _GLFW_PLATFORM_JOYSTICK_STATE _GLFWjoystickLinux linjs
#define _GLFW_PLATFORM_LIBRARY_JOYSTICK_STATE _GLFWlibraryLinux linjs;
#define _GLFW_PLATFORM_MAPPING_NAME "Linux"
// Linux-specific joystick data
//
typedef struct _GLFWjoystickLinux {
int fd;
char path[PATH_MAX];
int keyMap[KEY_CNT - BTN_MISC];
int absMap[ABS_CNT];
struct input_absinfo absInfo[ABS_CNT];
int hats[4][2];
} _GLFWjoystickLinux;
// Linux-specific joystick API data
//
typedef struct _GLFWlibraryLinux {
int inotify;
int watch;
regex_t regex;
bool dropped;
} _GLFWlibraryLinux;
void _glfwDetectJoystickConnectionLinux(void);
+204
View File
@@ -0,0 +1,204 @@
/*
* linux_notify.c
* Copyright (C) 2019 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#define _POSIX_C_SOURCE 200809L
#include "internal.h"
#include "linux_notify.h"
#include <stdlib.h>
#include <string.h>
#define NOTIFICATIONS_SERVICE "org.freedesktop.Notifications"
#define NOTIFICATIONS_PATH "/org/freedesktop/Notifications"
#define NOTIFICATIONS_IFACE "org.freedesktop.Notifications"
static inline void
cleanup_free(void *p) {
free(*(void **)p);
}
#define RAII_ALLOC(type, name, initializer) __attribute__((cleanup(cleanup_free))) type *name = initializer
typedef struct {
notification_id_type next_id;
GLFWDBusnotificationcreatedfun callback;
void *data;
} NotificationCreatedData;
static GLFWDBusnotificationactivatedfun activated_handler = NULL;
void
glfw_dbus_set_user_notification_activated_handler(GLFWDBusnotificationactivatedfun handler) {
activated_handler = handler;
}
void
notification_created(DBusMessage *msg, const DBusError *err, void *data) {
if (err) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Notify: Failed to create notification error: %s: %s", err->name, err->message);
if (data) free(data);
return;
}
uint32_t id;
if (!glfw_dbus_get_args(msg, "Failed to get Notification uid", DBUS_TYPE_UINT32, &id, DBUS_TYPE_INVALID)) return;
NotificationCreatedData *ncd = (NotificationCreatedData *)data;
if (ncd) {
if (ncd->callback) ncd->callback(ncd->next_id, id, ncd->data);
free(ncd);
}
}
static DBusHandlerResult
message_handler(DBusConnection *conn UNUSED, DBusMessage *msg, void *user_data UNUSED) {
/* printf("session_bus message_handler invoked interface: %s member: %s\n", dbus_message_get_interface(msg), dbus_message_get_member(msg)); */
if (dbus_message_is_signal(msg, NOTIFICATIONS_IFACE, "ActionInvoked")) {
uint32_t id;
const char *action = NULL;
if (glfw_dbus_get_args(
msg, "Failed to get args from ActionInvoked notification signal", DBUS_TYPE_UINT32, &id, DBUS_TYPE_STRING, &action, DBUS_TYPE_INVALID)) {
if (activated_handler) {
activated_handler(id, 2, action);
return DBUS_HANDLER_RESULT_HANDLED;
}
}
}
if (dbus_message_is_signal(msg, NOTIFICATIONS_IFACE, "ActivationToken")) {
uint32_t id;
const char *token = NULL;
if (glfw_dbus_get_args(
msg, "Failed to get args from ActivationToken notification signal", DBUS_TYPE_UINT32, &id, DBUS_TYPE_STRING, &token, DBUS_TYPE_INVALID)) {
if (activated_handler) {
activated_handler(id, 1, token);
return DBUS_HANDLER_RESULT_HANDLED;
}
}
}
if (dbus_message_is_signal(msg, NOTIFICATIONS_IFACE, "NotificationClosed")) {
uint32_t id;
if (glfw_dbus_get_args(msg, "Failed to get args from NotificationClosed notification signal", DBUS_TYPE_UINT32, &id, DBUS_TYPE_INVALID)) {
if (activated_handler) {
activated_handler(id, 0, "");
return DBUS_HANDLER_RESULT_HANDLED;
}
}
}
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
static bool
cancel_user_notification(DBusConnection *session_bus, uint32_t *id) {
return glfw_dbus_call_method_no_reply(
session_bus, NOTIFICATIONS_SERVICE, NOTIFICATIONS_PATH, NOTIFICATIONS_IFACE, "CloseNotification", DBUS_TYPE_UINT32, id, DBUS_TYPE_INVALID);
}
static void
got_capabilities(DBusMessage *msg, const DBusError *err, void *data UNUSED) {
if (err) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Notify: Failed to get server capabilities error: %s: %s", err->name, err->message);
return;
}
#define check_call(func, err, ...) \
if (!func(__VA_ARGS__)) { \
_glfwInputError(GLFW_PLATFORM_ERROR, "Notify: GetCapabilities: %s", err); \
return; \
}
DBusMessageIter iter, array_iter;
check_call(dbus_message_iter_init, "message has no parameters", msg, &iter);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY || dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRING) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Notify: GetCapabilities: %s", "reply is not an array of strings");
return;
}
dbus_message_iter_recurse(&iter, &array_iter);
char buf[2048] = {0}, *p = buf, *end = buf + sizeof(buf);
while (dbus_message_iter_get_arg_type(&array_iter) == DBUS_TYPE_STRING) {
const char *str;
dbus_message_iter_get_basic(&array_iter, &str);
size_t len = strlen(str);
if (len && p + len + 2 < end) {
p = stpcpy(p, str);
*(p++) = '\n';
}
dbus_message_iter_next(&array_iter);
}
if (activated_handler) activated_handler(0, -1, buf);
#undef check_call
}
static bool
get_capabilities(DBusConnection *session_bus) {
return glfw_dbus_call_method_with_reply(
session_bus, NOTIFICATIONS_SERVICE, NOTIFICATIONS_PATH, NOTIFICATIONS_IFACE, "GetCapabilities", 1000, got_capabilities, NULL, DBUS_TYPE_INVALID);
}
notification_id_type
glfw_dbus_send_user_notification(const GLFWDBUSNotificationData *n, GLFWDBusnotificationcreatedfun callback, void *user_data) {
DBusConnection *session_bus = glfw_dbus_session_bus();
if (!session_bus) return 0;
if (n->timeout == -9999 && n->urgency == 255) return cancel_user_notification(session_bus, user_data) ? 1 : 0;
if (n->timeout == -99999 && n->urgency == 255) return get_capabilities(session_bus) ? 1 : 0;
static DBusConnection *added_signal_match = NULL;
if (added_signal_match != session_bus) {
dbus_bus_add_match(session_bus, "type='signal',interface='" NOTIFICATIONS_IFACE "',member='ActionInvoked'", NULL);
dbus_bus_add_match(session_bus, "type='signal',interface='" NOTIFICATIONS_IFACE "',member='NotificationClosed'", NULL);
dbus_bus_add_match(session_bus, "type='signal',interface='" NOTIFICATIONS_IFACE "',member='ActivationToken'", NULL);
dbus_connection_add_filter(session_bus, message_handler, NULL, NULL);
added_signal_match = session_bus;
}
RAII_ALLOC(NotificationCreatedData, data, malloc(sizeof(NotificationCreatedData)));
if (!data) return 0;
static notification_id_type notification_id = 0;
data->next_id = ++notification_id;
data->callback = callback;
data->data = user_data;
if (!data->next_id) data->next_id = ++notification_id;
RAII_MSG(msg, dbus_message_new_method_call(NOTIFICATIONS_SERVICE, NOTIFICATIONS_PATH, NOTIFICATIONS_IFACE, "Notify"));
if (!msg) { return 0; }
DBusMessageIter args, array, variant, dict;
dbus_message_iter_init_append(msg, &args);
#define check_call(func, ...) \
if (!func(__VA_ARGS__)) { \
_glfwInputError(GLFW_PLATFORM_ERROR, "%s", "Out of memory allocating DBUS message for notification\n"); \
return 0; \
}
#define APPEND(to, type, val) check_call(dbus_message_iter_append_basic, &to, type, &val);
APPEND(args, DBUS_TYPE_STRING, n->app_name)
APPEND(args, DBUS_TYPE_UINT32, n->replaces)
APPEND(args, DBUS_TYPE_STRING, n->icon)
APPEND(args, DBUS_TYPE_STRING, n->summary)
APPEND(args, DBUS_TYPE_STRING, n->body)
check_call(dbus_message_iter_open_container, &args, DBUS_TYPE_ARRAY, "s", &array);
if (n->actions) {
for (size_t i = 0; i < n->num_actions; i++) { APPEND(array, DBUS_TYPE_STRING, n->actions[i]); }
}
check_call(dbus_message_iter_close_container, &args, &array);
check_call(dbus_message_iter_open_container, &args, DBUS_TYPE_ARRAY, "{sv}", &array);
#define append_sv_dictionary_entry(k, val_type, val) \
{ \
check_call(dbus_message_iter_open_container, &array, DBUS_TYPE_DICT_ENTRY, NULL, &dict); \
static const char *key = k; \
APPEND(dict, DBUS_TYPE_STRING, key); \
check_call(dbus_message_iter_open_container, &dict, DBUS_TYPE_VARIANT, val_type##_AS_STRING, &variant); \
APPEND(variant, val_type, val); \
check_call(dbus_message_iter_close_container, &dict, &variant); \
check_call(dbus_message_iter_close_container, &array, &dict); \
}
append_sv_dictionary_entry("urgency", DBUS_TYPE_BYTE, n->urgency);
if (n->category && n->category[0]) append_sv_dictionary_entry("category", DBUS_TYPE_STRING, n->category);
if (n->muted) append_sv_dictionary_entry("suppress-sound", DBUS_TYPE_BOOLEAN, n->muted);
if (n->desktop_entry && n->desktop_entry[0]) append_sv_dictionary_entry("desktop-entry", DBUS_TYPE_STRING, n->desktop_entry);
check_call(dbus_message_iter_close_container, &args, &array);
APPEND(args, DBUS_TYPE_INT32, n->timeout)
#undef check_call
#undef APPEND
if (!call_method_with_msg(session_bus, msg, 5000, notification_created, data, false)) return 0;
notification_id_type ans = data->next_id;
data = NULL;
return ans;
}
+17
View File
@@ -0,0 +1,17 @@
/*
* Copyright (C) 2019 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "dbus_glfw.h"
#include "internal.h"
typedef unsigned long long notification_id_type;
typedef void (*GLFWDBusnotificationcreatedfun)(notification_id_type, uint32_t, void *);
typedef void (*GLFWDBusnotificationactivatedfun)(uint32_t, int, const char *);
notification_id_type glfw_dbus_send_user_notification(const GLFWDBUSNotificationData *n, GLFWDBusnotificationcreatedfun, void *);
void glfw_dbus_set_user_notification_activated_handler(GLFWDBusnotificationactivatedfun handler);
+290
View File
@@ -0,0 +1,290 @@
/*
* linux_session_monitor.c
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
// Monitors the state of the desktop session using the Inhibit desktop portal, so that the application can save its state
// before the user is logged out. When the session is about to end, the portal changes the state to Query End and the
// application must acknowledge it within a second. The callback is run before acknowledging, so that the application can save
// its state before the session proceeds to the Ending state.
//
// Creating the monitor is a portal request: the CreateMonitor method returns a request object and the result is reported later by
// the Response signal of that object. Signals are accepted only from the portal that replied to CreateMonitor and only for the
// monitor session created by it, so that other clients on the session bus cannot fake a session ending.
//
// The monitor session ends if the portal exits, for example, because it crashed, so the monitor is created again when that happens.
// This is done only if the monitor was created successfully, so that a portal that crashes when creating it is not restarted in a
// loop by DBUS activation.
#include "linux_session_monitor.h"
#include <stdio.h>
#include <string.h>
#define PORTAL_SERVICE "org.freedesktop.portal.Desktop"
#define PORTAL_PATH "/org/freedesktop/portal/desktop"
#define INHIBIT_INTERFACE "org.freedesktop.portal.Inhibit"
#define REQUEST_INTERFACE "org.freedesktop.portal.Request"
// Object paths include the unique name of the connection, so a fixed token is unique, as there is only one monitor per connection
#define HANDLE_TOKEN "glfw_session_monitor"
static GLFWDBussessionstatefun session_state_callback = NULL;
static uint32_t current_session_state = GLFW_SESSION_STATE_RUNNING;
static bool monitoring = false;
// Whether the portal reported that the monitor was created
static bool established = false;
// The unique name of the portal that replied to CreateMonitor, empty until it replies
static char portal_name[256];
static char request_path[512], session_path[512];
static bool
portal_object_path(DBusConnection *conn, const char *kind, char *buf, size_t sz) {
// The portal creates objects at PORTAL_PATH/kind/SENDER/TOKEN where SENDER is the unique name of the connection without
// the leading colon and with dots replaced by underscores
const char *unique_name = dbus_bus_get_unique_name(conn);
if (!unique_name || unique_name[0] != ':') return false;
const int prefix_len = snprintf(buf, sz, PORTAL_PATH "/%s/", kind);
if (prefix_len < 0 || (size_t)prefix_len >= sz) return false;
const int n = snprintf(buf + prefix_len, sz - prefix_len, "%s/" HANDLE_TOKEN, unique_name + 1);
if (n < 0 || (size_t)n >= sz - prefix_len) return false;
for (char *p = buf + prefix_len; *p && *p != '/'; p++) {
if (*p == '.') *p = '_';
}
return true;
}
static bool
add_response_match(DBusConnection *conn) {
char rule[sizeof(request_path) + 128];
const int n = snprintf(rule, sizeof(rule), "type='signal',interface='" REQUEST_INTERFACE "',member='Response',path='%s'", request_path);
if (n < 0 || (size_t)n >= sizeof(rule)) return false;
dbus_bus_add_match(conn, rule, NULL);
return true;
}
static bool
is_from_portal(DBusMessage *msg) {
const char *sender = dbus_message_get_sender(msg);
return portal_name[0] && sender && strcmp(sender, portal_name) == 0;
}
static bool
read_session_state(DBusMessageIter *dict, uint32_t *state) {
DBusMessageIter entry, value;
while (dbus_message_iter_get_arg_type(dict) == DBUS_TYPE_DICT_ENTRY) {
dbus_message_iter_recurse(dict, &entry);
if (dbus_message_iter_get_arg_type(&entry) == DBUS_TYPE_STRING) {
const char *key;
dbus_message_iter_get_basic(&entry, &key);
if (strcmp(key, "session-state") == 0 && dbus_message_iter_next(&entry) && dbus_message_iter_get_arg_type(&entry) == DBUS_TYPE_VARIANT) {
dbus_message_iter_recurse(&entry, &value);
if (dbus_message_iter_get_arg_type(&value) != DBUS_TYPE_UINT32) return false;
dbus_message_iter_get_basic(&value, state);
return true;
}
}
if (!dbus_message_iter_next(dict)) break;
}
// The state dictionary does not have a valid session state
return false;
}
static void
on_state_changed(DBusConnection *conn, DBusMessage *msg) {
DBusMessageIter iter, dict;
const char *session_handle = NULL;
if (!dbus_message_iter_init(msg, &iter) || dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_OBJECT_PATH) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: StateChanged signal does not have a session handle");
return;
}
dbus_message_iter_get_basic(&iter, &session_handle);
if (strcmp(session_handle, session_path) != 0) return;
if (!dbus_message_iter_next(&iter) || dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: StateChanged signal does not have a state dictionary");
return;
}
dbus_message_iter_recurse(&iter, &dict);
uint32_t state;
if (!read_session_state(&dict, &state)) return;
// The signal is also sent when only the screensaver state changes
const bool changed = state != current_session_state;
current_session_state = state;
if (changed && session_state_callback) session_state_callback(state);
if (state == GLFW_SESSION_STATE_QUERY_END) {
if (!glfw_dbus_call_method_no_reply(
conn, PORTAL_SERVICE, PORTAL_PATH, INHIBIT_INTERFACE, "QueryEndResponse", DBUS_TYPE_OBJECT_PATH, &session_handle, DBUS_TYPE_INVALID))
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: Failed to respond to the session ending");
}
}
static void
on_monitor_response(DBusMessage *msg) {
DBusMessageIter iter;
uint32_t response;
if (!dbus_message_iter_init(msg, &iter) || dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_UINT32) {
monitoring = false;
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: The response to CreateMonitor does not have a response code");
return;
}
dbus_message_iter_get_basic(&iter, &response);
if (response != 0) {
monitoring = false;
_glfwInputError(
GLFW_PLATFORM_ERROR,
"Inhibit portal: Failed to monitor the session state, make sure your desktop portal supports version 3 of the Inhibit "
"portal. Response code: %u",
response);
return;
}
established = true;
// Use the session handle from the results, in case the portal ignored session_handle_token
DBusMessageIter results, entry, value;
if (!dbus_message_iter_next(&iter) || dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY) return;
dbus_message_iter_recurse(&iter, &results);
for (; dbus_message_iter_get_arg_type(&results) == DBUS_TYPE_DICT_ENTRY; dbus_message_iter_next(&results)) {
const char *key, *handle;
dbus_message_iter_recurse(&results, &entry);
if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_STRING) continue;
dbus_message_iter_get_basic(&entry, &key);
if (strcmp(key, "session_handle") != 0 || !dbus_message_iter_next(&entry) || dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_VARIANT) continue;
dbus_message_iter_recurse(&entry, &value);
const int type = dbus_message_iter_get_arg_type(&value);
if (type != DBUS_TYPE_STRING && type != DBUS_TYPE_OBJECT_PATH) continue;
dbus_message_iter_get_basic(&value, &handle);
if (strlen(handle) < sizeof(session_path)) memcpy(session_path, handle, strlen(handle) + 1);
break;
}
}
static bool start_monitoring(DBusConnection *session_bus);
static void
on_name_owner_changed(DBusConnection *conn, DBusMessage *msg) {
const char *name, *old_owner, *new_owner;
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &old_owner, DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID)) return;
if (strcmp(name, PORTAL_SERVICE) != 0 || !portal_name[0] || strcmp(old_owner, portal_name) != 0) return;
// The portal that created the monitor has exited, which ends the monitor session
const bool restart = monitoring && established;
monitoring = false;
established = false;
portal_name[0] = 0;
if (restart) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: The desktop portal exited, monitoring the session state again");
start_monitoring(conn);
}
}
static DBusHandlerResult
message_filter(DBusConnection *conn, DBusMessage *msg, void *user_data UNUSED) {
if (dbus_message_is_signal(msg, DBUS_INTERFACE_DBUS, "NameOwnerChanged") && dbus_message_has_sender(msg, DBUS_SERVICE_DBUS)) {
on_name_owner_changed(conn, msg);
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
if (!monitoring || !is_from_portal(msg)) return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
if (dbus_message_is_signal(msg, INHIBIT_INTERFACE, "StateChanged")) on_state_changed(conn, msg);
else if (dbus_message_is_signal(msg, REQUEST_INTERFACE, "Response") && dbus_message_has_path(msg, request_path)) on_monitor_response(msg);
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
static void
monitor_created(DBusMessage *msg, const DBusError *err, void *data UNUSED) {
if (err) {
monitoring = false;
_glfwInputError(
GLFW_PLATFORM_ERROR,
"Inhibit portal: Failed to monitor the session state, make sure you have the desktop portal running. Error: %s: %s",
err->name,
err->message);
return;
}
const char *sender = dbus_message_get_sender(msg), *handle = NULL;
if (!sender || strlen(sender) >= sizeof(portal_name) || !dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &handle, DBUS_TYPE_INVALID)) {
monitoring = false;
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: Invalid reply to CreateMonitor");
return;
}
memcpy(portal_name, sender, strlen(sender) + 1);
if (strcmp(handle, request_path) != 0) {
// Portals that ignore handle_token use a different request path, its Response signal could be missed if it was sent before
// the match below is added
if (strlen(handle) >= sizeof(request_path)) {
monitoring = false;
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: The request path returned by CreateMonitor is too long");
return;
}
memcpy(request_path, handle, strlen(handle) + 1);
if (!add_response_match(glfw_dbus_session_bus())) {
monitoring = false;
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: Failed to watch for the response to CreateMonitor");
}
}
}
static bool
append_string_option(DBusMessageIter *options, const char *key, const char *value) {
DBusMessageIter entry, variant;
if (!dbus_message_iter_open_container(options, DBUS_TYPE_DICT_ENTRY, NULL, &entry)) return false;
if (!dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &key)) return false;
if (!dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT, "s", &variant)) return false;
if (!dbus_message_iter_append_basic(&variant, DBUS_TYPE_STRING, &value)) return false;
if (!dbus_message_iter_close_container(&entry, &variant)) return false;
return dbus_message_iter_close_container(options, &entry);
}
static bool
create_monitor(DBusConnection *session_bus) {
RAII_MSG(msg, dbus_message_new_method_call(PORTAL_SERVICE, PORTAL_PATH, INHIBIT_INTERFACE, "CreateMonitor"));
if (!msg) return false;
DBusMessageIter iter, options;
const char *window = "";
dbus_message_iter_init_append(msg, &iter);
if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &window)) return false;
if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &options)) return false;
// Some versions of xdg-desktop-portal abort if the session handle token is missing
if (!append_string_option(&options, "handle_token", HANDLE_TOKEN)) return false;
if (!append_string_option(&options, "session_handle_token", HANDLE_TOKEN)) return false;
if (!dbus_message_iter_close_container(&iter, &options)) return false;
return call_method_with_msg(session_bus, msg, DBUS_TIMEOUT_USE_DEFAULT, monitor_created, NULL, false);
}
static bool
start_monitoring(DBusConnection *session_bus) {
static bool filter_added = false;
if (!portal_object_path(session_bus, "request", request_path, sizeof(request_path)) ||
!portal_object_path(session_bus, "session", session_path, sizeof(session_path))) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: Failed to get the unique name of the DBUS connection");
return false;
}
if (!filter_added) {
// Added before calling CreateMonitor, so that the Response signal cannot be missed
if (!add_response_match(session_bus)) return false;
dbus_bus_add_match(session_bus, "type='signal',interface='" INHIBIT_INTERFACE "',member='StateChanged'", NULL);
dbus_bus_add_match(
session_bus,
"type='signal',sender='" DBUS_SERVICE_DBUS "',interface='" DBUS_INTERFACE_DBUS "',member='NameOwnerChanged',arg0='" PORTAL_SERVICE "'",
NULL);
if (!dbus_connection_add_filter(session_bus, message_filter, NULL, NULL)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: Failed to add a DBUS message filter");
return false;
}
filter_added = true;
}
portal_name[0] = 0;
established = false;
// Reset without running the callback, so that state the application saved for a logout that was in progress when the portal
// exited is not discarded
current_session_state = GLFW_SESSION_STATE_RUNNING;
monitoring = create_monitor(session_bus);
if (!monitoring) _glfwInputError(GLFW_PLATFORM_ERROR, "Inhibit portal: Failed to call CreateMonitor");
return monitoring;
}
bool
glfw_dbus_monitor_session_state(GLFWDBussessionstatefun callback) {
session_state_callback = callback;
if (monitoring) return true;
DBusConnection *session_bus = glfw_dbus_session_bus();
if (!session_bus) return false;
return start_monitoring(session_bus);
}
+18
View File
@@ -0,0 +1,18 @@
/*
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "dbus_glfw.h"
#include "internal.h"
// The session states reported by the Inhibit desktop portal
#define GLFW_SESSION_STATE_RUNNING 1
#define GLFW_SESSION_STATE_QUERY_END 2
#define GLFW_SESSION_STATE_ENDING 3
typedef void (*GLFWDBussessionstatefun)(uint32_t);
bool glfw_dbus_monitor_session_state(GLFWDBussessionstatefun callback);
+56
View File
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2019 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "internal.h"
#include "../kitty/monotonic.h"
#ifndef GLFW_LOOP_BACKEND
#define GLFW_LOOP_BACKEND x11
#endif
static bool keep_going = false;
void
_glfwPlatformStopMainLoop(void) {
if (keep_going) {
keep_going = false;
_glfwPlatformPostEmptyEvent();
}
}
void
_glfwPlatformRunMainLoop(GLFWtickcallback tick_callback, void *data) {
keep_going = 1;
EventLoopData *eld = &_glfw.GLFW_LOOP_BACKEND.eventLoopData;
while (keep_going) {
_glfwPlatformWaitEvents();
EVDBG("--------- loop tick, wakeups_happened: %d ----------", eld->wakeup_data_read);
if (eld->wakeup_data_read) {
eld->wakeup_data_read = false;
tick_callback(data);
}
}
EVDBG("main loop exiting");
}
unsigned long long
_glfwPlatformAddTimer(monotonic_t interval, bool repeats, GLFWuserdatafreefun callback, void *callback_data, GLFWuserdatafreefun free_callback) {
return addTimer(&_glfw.GLFW_LOOP_BACKEND.eventLoopData, "user timer", interval, 1, repeats, callback, callback_data, free_callback);
}
void
_glfwPlatformRemoveTimer(unsigned long long timer_id) {
removeTimer(&_glfw.GLFW_LOOP_BACKEND.eventLoopData, timer_id);
}
void
_glfwPlatformUpdateTimer(unsigned long long timer_id, monotonic_t interval, bool enabled) {
changeTimerInterval(&_glfw.GLFW_LOOP_BACKEND.eventLoopData, timer_id, interval);
toggleTimer(&_glfw.GLFW_LOOP_BACKEND.eventLoopData, timer_id, enabled);
}
+1236
View File
File diff suppressed because it is too large. Load diff
+53
View File
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#ifdef HAS_MEMFD_CREATE
#include <unistd.h>
#include <sys/syscall.h>
static inline int
glfw_memfd_create(const char *name, unsigned int flags) {
return (int)syscall(__NR_memfd_create, name, flags);
}
#ifndef F_LINUX_SPECIFIC_BASE
#define F_LINUX_SPECIFIC_BASE 1024
#endif
#ifndef F_ADD_SEALS
#define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
#define F_GET_SEALS (F_LINUX_SPECIFIC_BASE + 10)
#define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
#define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */
#define F_SEAL_GROW 0x0004 /* prevent file from growing */
#define F_SEAL_WRITE 0x0008 /* prevent writes */
#endif
#ifndef MFD_CLOEXEC
#define MFD_CLOEXEC 0x0001U
#define MFD_ALLOW_SEALING 0x0002U
#endif
#else
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
static inline int
createTmpfileCloexec(char *tmpname) {
int fd;
fd = mkostemp(tmpname, O_CLOEXEC);
if (fd >= 0) unlink(tmpname);
return fd;
}
#endif
+283
View File
@@ -0,0 +1,283 @@
/*
* momentum-scroll.c
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "internal.h"
#include <math.h>
typedef struct ScrollSample {
double dx, dy;
monotonic_t timestamp;
} ScrollSample;
#define DEQUE_DATA_TYPE ScrollSample
#define DEQUE_NAME ScrollSamples
#include "../kitty/fixed_size_deque.h"
typedef enum ScrollerState { NONE, PHYSICAL_EVENT_IN_PROGRESS, MOMENTUM_IN_PROGRESS } ScrollerState;
typedef struct MomentumScroller {
double friction, // Deceleration inverse factor (0-1, higher = longer coast)
min_velocity, // Minimum velocity before stopping
max_velocity, // Maximum velocity to prevent runaway scrolling
velocity_scale; // Scale factor for initial velocity
monotonic_t timer_interval; // animation speed
GLFWid timer_id, window_id;
ScrollSamples samples;
ScrollerState state;
double scale;
struct {
double x, y;
} velocity;
int keyboard_modifiers;
struct {
monotonic_t start, duration;
struct {
double x, y;
} displacement;
} physical_event;
} MomentumScroller;
#define DEFAULTS \
{ \
.friction = 0.96, \
.min_velocity = 0.5, \
.max_velocity = 100, \
.timer_interval = 10, \
}
static const MomentumScroller defaults = DEFAULTS;
static MomentumScroller s = DEFAULTS;
#undef DEFAULTS
GLFWAPI void
glfwConfigureMomentumScroller(double friction, double min_velocity, double max_velocity, unsigned timer_interval_ms) {
s.timer_interval = timer_interval_ms ? ms_to_monotonic_t(timer_interval_ms) : defaults.timer_interval;
s.friction = friction < 0 ? defaults.friction : MAX(0, MIN(friction, 1));
#define S(w) s.w = w >= 0 ? w : defaults.w
S(min_velocity);
S(max_velocity);
#undef S
}
static void
cancel_existing_scroll(bool reset_velocity) {
if (s.timer_id) {
glfwRemoveTimer(s.timer_id);
s.timer_id = 0;
}
if (s.state == MOMENTUM_IN_PROGRESS) {
_GLFWwindow *w = _glfwWindowForId(s.window_id);
if (w) _glfwInputScroll(w, &(GLFWScrollEvent){.momentum_type = GLFW_MOMENTUM_PHASE_CANCELED, .keyboard_modifiers = s.keyboard_modifiers});
}
s.window_id = 0;
s.keyboard_modifiers = 0;
deque_clear(&s.samples);
s.state = NONE;
if (reset_velocity) {
s.velocity.x = 0;
s.velocity.y = 0;
}
}
static void
add_sample(double dx, double dy, monotonic_t now) {
deque_push_back(&s.samples, (ScrollSample){dx, dy, now}, NULL);
}
static void
last_sample_delta(double *dx, double *dy) {
const ScrollSample *ss;
if ((ss = deque_peek_back(&s.samples))) {
*dx = ss->dx;
*dy = ss->dy;
} else {
*dx = 0;
*dy = 0;
}
}
static void
trim_old_samples(monotonic_t now) {
const ScrollSample *ss;
while ((ss = deque_peek_front(&s.samples)) && (now - ss->timestamp) > ms_to_monotonic_t(150)) deque_pop_front(&s.samples, NULL);
}
static void
add_velocity(double x, double y) {
if (x == 0 || x * s.velocity.x >= 0) s.velocity.x += x;
else s.velocity.x = x;
if (y == 0 || y * s.velocity.y >= 0) s.velocity.y += y;
else s.velocity.y = y;
s.velocity.x = MAX(-s.max_velocity, MIN(s.velocity.x, s.max_velocity));
s.velocity.y = MAX(-s.max_velocity, MIN(s.velocity.y, s.max_velocity));
}
static void
set_velocity_from_samples(monotonic_t now) {
s.timer_interval = ms_to_monotonic_t(8);
trim_old_samples(now);
ScrollSample ss;
switch (deque_size(&s.samples)) {
case 0: return;
case 1:
deque_pop_front(&s.samples, &ss);
add_velocity(ss.dx, ss.dy);
return;
}
// Use weighted average - more recent samples have higher weight
double total_dx = 0.0, total_dy = 0.0, total_weight = 0.0;
monotonic_t first_time = deque_peek_front(&s.samples)->timestamp;
monotonic_t last_time = deque_peek_back(&s.samples)->timestamp;
double time_span = MAX(1, last_time - first_time);
for (size_t i = 0; i < deque_size(&s.samples); i++) {
const ScrollSample *ss = deque_at(&s.samples, i);
double weight = 1.0 + (ss->timestamp - first_time) / time_span;
total_dx += ss->dx * weight;
total_dy += ss->dy * weight;
total_weight += weight;
}
deque_clear(&s.samples);
if (total_weight <= 0) return;
double dy = total_dy / total_weight, dx = total_dx / total_weight;
add_velocity(dx, dy);
if (false) timed_debug_print("momentum scroll: event velocity: %.1f final velocity: %.1f\n", dy, s.velocity.y);
}
static void
send_momentum_event(bool is_start) {
_GLFWwindow *w = _glfwWindowForId(s.window_id);
if (!w || w != _glfwFocusedWindow()) {
cancel_existing_scroll(true);
return;
}
s.velocity.x *= s.friction;
s.velocity.y *= s.friction;
if (fabs(s.velocity.x) < s.min_velocity) s.velocity.x = 0;
if (fabs(s.velocity.y) < s.min_velocity) s.velocity.y = 0;
GLFWMomentumType m = is_start ? GLFW_MOMENTUM_PHASE_BEGAN : GLFW_MOMENTUM_PHASE_ACTIVE;
if (s.velocity.x == 0 && s.velocity.y == 0 && !is_start) {
m = GLFW_MOMENTUM_PHASE_ENDED;
if (s.timer_id) glfwRemoveTimer(s.timer_id);
s.timer_id = 0;
s.state = NONE;
}
GLFWScrollEvent e = {
.offset_type = GLFW_SCROLL_OFFEST_HIGHRES,
.momentum_type = m,
.unscaled.x = s.velocity.x,
.unscaled.y = s.velocity.y,
.x_offset = s.scale * s.velocity.x,
.y_offset = s.scale * s.velocity.y,
.keyboard_modifiers = s.keyboard_modifiers};
_glfwInputScroll(w, &e);
}
static void
momentum_timer_fired(unsigned long long timer_id UNUSED, void *data UNUSED) {
send_momentum_event(false);
}
static void
start_momentum_scroll(monotonic_t now) {
set_velocity_from_samples(now);
send_momentum_event(true);
s.timer_id = glfwAddTimer(s.timer_interval, true, momentum_timer_fired, NULL, NULL);
}
static bool
is_suitable_for_momentum(void) {
return (MAX(fabs(s.physical_event.displacement.x), fabs(s.physical_event.displacement.y)) > 10 && s.physical_event.duration > ms_to_monotonic_t(2));
}
bool
glfw_is_momentum_scroll_enabled(void) {
return s.friction > 0;
}
static void
handle_scroll_event(_GLFWwindow *w, const GLFWScrollEvent *ev, bool stopped, bool is_finger_based, monotonic_t now, bool is_synthetic_momentum_start_event) {
if (!w) {
cancel_existing_scroll(true);
return;
}
if (!is_finger_based || ev->offset_type != GLFW_SCROLL_OFFEST_HIGHRES || !glfw_is_momentum_scroll_enabled()) {
if (ev->x_offset != 0 || ev->y_offset != 0) _glfwInputScroll(w, ev);
return;
}
if (s.state == PHYSICAL_EVENT_IN_PROGRESS) {
s.physical_event.displacement.x += ev->unscaled.x;
s.physical_event.displacement.y += ev->unscaled.y;
if (stopped) {
s.physical_event.duration = now - s.physical_event.start;
s.physical_event.start = 0;
}
} else {
memset(&s.physical_event, 0, sizeof(s.physical_event));
s.physical_event.start = now;
}
if (ev->unscaled.y != 0) s.scale = ev->y_offset / ev->unscaled.y;
else if (ev->unscaled.x != 0) s.scale = ev->x_offset / ev->unscaled.x;
if (s.window_id && s.window_id != w->id) cancel_existing_scroll(true);
if (s.state != PHYSICAL_EVENT_IN_PROGRESS) cancel_existing_scroll(false);
if (!is_synthetic_momentum_start_event) {
// Check for change in direction
double ldx, ldy;
last_sample_delta(&ldx, &ldy);
if (ldx * ev->x_offset < 0 || ldy * ev->y_offset < 0) cancel_existing_scroll(true);
}
s.window_id = w->id;
s.keyboard_modifiers = ev->keyboard_modifiers;
if (ev->offset_type == GLFW_SCROLL_OFFEST_HIGHRES) {
if (!is_synthetic_momentum_start_event) add_sample(ev->unscaled.x, ev->unscaled.y, now);
if (stopped) s.state = is_suitable_for_momentum() ? MOMENTUM_IN_PROGRESS : NONE;
else s.state = PHYSICAL_EVENT_IN_PROGRESS;
} else {
s.state = stopped ? NONE : PHYSICAL_EVENT_IN_PROGRESS;
}
if (s.state == MOMENTUM_IN_PROGRESS) start_momentum_scroll(now);
else _glfwInputScroll(w, ev);
}
void
glfw_handle_scroll_event_for_momentum(_GLFWwindow *w, const GLFWScrollEvent *ev, bool stopped, bool is_finger_based) {
const bool is_synthetic_momentum_start_event = stopped && momentum_scroll_gesture_detection_timeout_ms;
monotonic_t now = monotonic();
if (is_synthetic_momentum_start_event) now -= ms_to_monotonic_t(momentum_scroll_gesture_detection_timeout_ms);
handle_scroll_event(w, ev, stopped, is_finger_based, now, is_synthetic_momentum_start_event);
}
// Scrolls window by a finger driven movement, such as a drag on a touchscreen,
// through the same momentum scroller that touchpad scrolling uses. dx and dy are
// in logical pixels, with the same sign as GLFWScrollEvent offsets, which is the
// direction the finger moved, so a finger displacement can be passed as is. Pass
// stopped=true when the finger lifts, the scroll then coasts if the finger was
// moving fast enough. timestamp is when the movement happened, on the clock of
// monotonic(), or zero for now. If momentum scrolling is disabled, this sends
// plain high resolution scroll events.
GLFWAPI void
glfwFeedMomentumScroller(GLFWwindow *handle, double dx, double dy, int keyboard_modifiers, bool stopped, monotonic_t timestamp) {
_GLFWwindow *w = (_GLFWwindow *)handle;
if (!w) return;
float xscale = 1, yscale = 1;
_glfwPlatformGetWindowContentScale(w, &xscale, &yscale);
const GLFWScrollEvent ev = {
.offset_type = GLFW_SCROLL_OFFEST_HIGHRES,
.unscaled = {.x = dx, .y = dy},
.x_offset = dx * (xscale > 0 ? xscale : 1),
.y_offset = dy * (yscale > 0 ? yscale : 1),
.keyboard_modifiers = keyboard_modifiers,
};
handle_scroll_event(w, &ev, stopped, true, timestamp > 0 ? timestamp : monotonic(), false);
}
// Stops any momentum scroll that is coasting
GLFWAPI void
glfwCancelMomentumScroll(void) {
glfw_cancel_momentum_scroll();
}
+488
View File
@@ -0,0 +1,488 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// Please use C89 style variable declarations in this file because VS 2010
//========================================================================
#include "internal.h"
#include <assert.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
// Lexically compare video modes, used by qsort
//
static int
compareVideoModes(const void *fp, const void *sp) {
const GLFWvidmode *fm = fp;
const GLFWvidmode *sm = sp;
const int fbpp = fm->redBits + fm->greenBits + fm->blueBits;
const int sbpp = sm->redBits + sm->greenBits + sm->blueBits;
const int farea = fm->width * fm->height;
const int sarea = sm->width * sm->height;
// First sort on color bits per pixel
if (fbpp != sbpp) return fbpp - sbpp;
// Then sort on screen area
if (farea != sarea) return farea - sarea;
// Then sort on width
if (fm->width != sm->width) return fm->width - sm->width;
// Lastly sort on refresh rate
return fm->refreshRate - sm->refreshRate;
}
// Retrieves the available modes for the specified monitor
//
static bool
refreshVideoModes(_GLFWmonitor *monitor) {
int modeCount;
GLFWvidmode *modes;
if (monitor->modes) return true;
modes = _glfwPlatformGetVideoModes(monitor, &modeCount);
if (!modes) return false;
qsort(modes, modeCount, sizeof(modes[0]), compareVideoModes);
free(monitor->modes);
monitor->modes = modes;
monitor->modeCount = modeCount;
return true;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW event API //////
//////////////////////////////////////////////////////////////////////////
// Notifies shared code of a monitor connection or disconnection
//
void
_glfwInputMonitor(_GLFWmonitor *monitor, int action, int placement) {
if (action == GLFW_CONNECTED) {
_glfw.monitorCount++;
_glfw.monitors = realloc(_glfw.monitors, sizeof(_GLFWmonitor *) * _glfw.monitorCount);
if (placement == _GLFW_INSERT_FIRST) {
memmove(_glfw.monitors + 1, _glfw.monitors, ((size_t)_glfw.monitorCount - 1) * sizeof(_GLFWmonitor *));
_glfw.monitors[0] = monitor;
} else _glfw.monitors[_glfw.monitorCount - 1] = monitor;
} else if (action == GLFW_DISCONNECTED) {
int i;
_GLFWwindow *window;
for (window = _glfw.windowListHead; window; window = window->next) {
if (window->monitor == monitor) {
int width, height, xoff, yoff;
_glfwPlatformGetWindowSize(window, &width, &height);
_glfwPlatformSetWindowMonitor(window, NULL, 0, 0, width, height, 0);
_glfwPlatformGetWindowFrameSize(window, &xoff, &yoff, NULL, NULL);
_glfwPlatformSetWindowPos(window, xoff, yoff);
}
}
for (i = 0; i < _glfw.monitorCount; i++) {
if (_glfw.monitors[i] == monitor) {
remove_i_from_array(_glfw.monitors, i, _glfw.monitorCount);
break;
}
}
}
if (_glfw.callbacks.monitor) _glfw.callbacks.monitor((GLFWmonitor *)monitor, action);
if (action == GLFW_DISCONNECTED) _glfwFreeMonitor(monitor);
}
// Notifies shared code that a full screen window has acquired or released
// a monitor
//
void
_glfwInputMonitorWindow(_GLFWmonitor *monitor, _GLFWwindow *window) {
monitor->window = window;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Allocates and returns a monitor object with the specified name and dimensions
//
_GLFWmonitor *
_glfwAllocMonitor(const char *name, int widthMM, int heightMM) {
_GLFWmonitor *monitor = calloc(1, sizeof(_GLFWmonitor));
monitor->widthMM = widthMM;
monitor->heightMM = heightMM;
if (name) monitor->name = _glfw_strdup(name);
return monitor;
}
// Frees a monitor object and any data associated with it
//
void
_glfwFreeMonitor(_GLFWmonitor *monitor) {
if (monitor == NULL) return;
_glfwPlatformFreeMonitor(monitor);
_glfwFreeGammaArrays(&monitor->originalRamp);
_glfwFreeGammaArrays(&monitor->currentRamp);
free(monitor->modes);
free((void *)monitor->name);
free((void *)monitor->description);
free(monitor);
}
// Allocates red, green and blue value arrays of the specified size
//
void
_glfwAllocGammaArrays(GLFWgammaramp *ramp, unsigned int size) {
ramp->red = calloc(size, sizeof(unsigned short));
ramp->green = calloc(size, sizeof(unsigned short));
ramp->blue = calloc(size, sizeof(unsigned short));
ramp->size = size;
}
// Frees the red, green and blue value arrays and clears the struct
//
void
_glfwFreeGammaArrays(GLFWgammaramp *ramp) {
free(ramp->red);
free(ramp->green);
free(ramp->blue);
memset(ramp, 0, sizeof(GLFWgammaramp));
}
// Chooses the video mode most closely matching the desired one
//
const GLFWvidmode *
_glfwChooseVideoMode(_GLFWmonitor *monitor, const GLFWvidmode *desired) {
int i;
unsigned int sizeDiff, leastSizeDiff = UINT_MAX;
unsigned int rateDiff, leastRateDiff = UINT_MAX;
unsigned int colorDiff, leastColorDiff = UINT_MAX;
const GLFWvidmode *current;
const GLFWvidmode *closest = NULL;
if (!refreshVideoModes(monitor)) return NULL;
for (i = 0; i < monitor->modeCount; i++) {
current = monitor->modes + i;
colorDiff = 0;
if (desired->redBits != GLFW_DONT_CARE) colorDiff += abs(current->redBits - desired->redBits);
if (desired->greenBits != GLFW_DONT_CARE) colorDiff += abs(current->greenBits - desired->greenBits);
if (desired->blueBits != GLFW_DONT_CARE) colorDiff += abs(current->blueBits - desired->blueBits);
sizeDiff = abs(
(current->width - desired->width) * (current->width - desired->width) + (current->height - desired->height) * (current->height - desired->height));
if (desired->refreshRate != GLFW_DONT_CARE) rateDiff = abs(current->refreshRate - desired->refreshRate);
else rateDiff = UINT_MAX - current->refreshRate;
if ((colorDiff < leastColorDiff) || (colorDiff == leastColorDiff && sizeDiff < leastSizeDiff) ||
(colorDiff == leastColorDiff && sizeDiff == leastSizeDiff && rateDiff < leastRateDiff)) {
closest = current;
leastSizeDiff = sizeDiff;
leastRateDiff = rateDiff;
leastColorDiff = colorDiff;
}
}
return closest;
}
// Performs lexical comparison between two @ref GLFWvidmode structures
//
int
_glfwCompareVideoModes(const GLFWvidmode *fm, const GLFWvidmode *sm) {
return compareVideoModes(fm, sm);
}
// Splits a color depth into red, green and blue bit depths
//
void
_glfwSplitBPP(int bpp, int *red, int *green, int *blue) {
int delta;
// We assume that by 32 the user really meant 24
if (bpp == 32) bpp = 24;
// Convert "bits per pixel" to red, green & blue sizes
*red = *green = *blue = bpp / 3;
delta = bpp - (*red * 3);
if (delta >= 1) *green = *green + 1;
if (delta == 2) *red = *red + 1;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW public API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI GLFWmonitor **
glfwGetMonitors(int *count) {
assert(count != NULL);
*count = 0;
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
*count = _glfw.monitorCount;
return (GLFWmonitor **)_glfw.monitors;
}
GLFWAPI GLFWmonitor *
glfwGetPrimaryMonitor(void) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
if (!_glfw.monitorCount) return NULL;
return (GLFWmonitor *)_glfw.monitors[0];
}
GLFWAPI void
glfwGetMonitorPos(GLFWmonitor *handle, int *xpos, int *ypos) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
if (xpos) *xpos = 0;
if (ypos) *ypos = 0;
_GLFW_REQUIRE_INIT();
_glfwPlatformGetMonitorPos(monitor, xpos, ypos);
}
GLFWAPI void
glfwGetMonitorWorkarea(GLFWmonitor *handle, int *xpos, int *ypos, int *width, int *height) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
if (xpos) *xpos = 0;
if (ypos) *ypos = 0;
if (width) *width = 0;
if (height) *height = 0;
_GLFW_REQUIRE_INIT();
_glfwPlatformGetMonitorWorkarea(monitor, xpos, ypos, width, height);
}
GLFWAPI void
glfwGetMonitorPhysicalSize(GLFWmonitor *handle, int *widthMM, int *heightMM) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
if (widthMM) *widthMM = 0;
if (heightMM) *heightMM = 0;
_GLFW_REQUIRE_INIT();
if (widthMM) *widthMM = monitor->widthMM;
if (heightMM) *heightMM = monitor->heightMM;
}
GLFWAPI void
glfwGetMonitorContentScale(GLFWmonitor *handle, float *xscale, float *yscale) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
if (xscale) *xscale = 0.f;
if (yscale) *yscale = 0.f;
_GLFW_REQUIRE_INIT();
_glfwPlatformGetMonitorContentScale(monitor, xscale, yscale);
}
GLFWAPI const char *
glfwGetMonitorName(GLFWmonitor *handle) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
return monitor->name ? monitor->name : "";
}
GLFWAPI const char *
glfwGetMonitorDescription(GLFWmonitor *handle) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
return monitor->description ? monitor->description : "";
}
GLFWAPI void
glfwSetMonitorUserPointer(GLFWmonitor *handle, void *pointer) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT();
monitor->userPointer = pointer;
}
GLFWAPI void *
glfwGetMonitorUserPointer(GLFWmonitor *handle) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
return monitor->userPointer;
}
GLFWAPI GLFWmonitorfun
glfwSetMonitorCallback(GLFWmonitorfun cbfun) {
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_GLFW_SWAP_POINTERS(_glfw.callbacks.monitor, cbfun);
return cbfun;
}
GLFWAPI const GLFWvidmode *
glfwGetVideoModes(GLFWmonitor *handle, int *count) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
assert(count != NULL);
*count = 0;
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
if (!refreshVideoModes(monitor)) return NULL;
*count = monitor->modeCount;
return monitor->modes;
}
GLFWAPI const GLFWvidmode *
glfwGetVideoMode(GLFWmonitor *handle) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
if (!_glfwPlatformGetVideoMode(monitor, &monitor->currentMode)) return NULL;
return &monitor->currentMode;
}
GLFWAPI void
glfwSetGamma(GLFWmonitor *handle, float gamma) {
unsigned int i;
unsigned short *values;
GLFWgammaramp ramp;
const GLFWgammaramp *original;
assert(handle != NULL);
assert(gamma > 0.f);
assert(gamma <= FLT_MAX);
_GLFW_REQUIRE_INIT();
if (gamma != gamma || gamma <= 0.f || gamma > FLT_MAX) {
_glfwInputError(GLFW_INVALID_VALUE, "Invalid gamma value %f", gamma);
return;
}
original = glfwGetGammaRamp(handle);
if (!original) return;
values = calloc(original->size, sizeof(unsigned short));
for (i = 0; i < original->size; i++) {
float value;
// Calculate intensity
value = i / (float)(original->size - 1);
// Apply gamma curve
value = powf(value, 1.f / gamma) * 65535.f + 0.5f;
// Clamp to value range
value = fminf(value, 65535.f);
values[i] = (unsigned short)value;
}
ramp.red = values;
ramp.green = values;
ramp.blue = values;
ramp.size = original->size;
glfwSetGammaRamp(handle, &ramp);
free(values);
}
GLFWAPI const GLFWgammaramp *
glfwGetGammaRamp(GLFWmonitor *handle) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
_glfwFreeGammaArrays(&monitor->currentRamp);
if (!_glfwPlatformGetGammaRamp(monitor, &monitor->currentRamp)) return NULL;
return &monitor->currentRamp;
}
GLFWAPI void
glfwSetGammaRamp(GLFWmonitor *handle, const GLFWgammaramp *ramp) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
assert(ramp != NULL);
assert(ramp->size > 0);
assert(ramp->red != NULL);
assert(ramp->green != NULL);
assert(ramp->blue != NULL);
if (ramp->size <= 0) {
_glfwInputError(GLFW_INVALID_VALUE, "Invalid gamma ramp size %i", ramp->size);
return;
}
_GLFW_REQUIRE_INIT();
if (!monitor->originalRamp.size) {
if (!_glfwPlatformGetGammaRamp(monitor, &monitor->originalRamp)) return;
}
_glfwPlatformSetGammaRamp(monitor, ramp);
}
+10
View File
@@ -0,0 +1,10 @@
/*
* monotonic.c
* Copyright (C) 2019 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#define _POSIX_C_SOURCE 200809L
#define MONOTONIC_IMPLEMENTATION
#include "../kitty/monotonic.h"
+51
View File
@@ -0,0 +1,51 @@
//========================================================================
// GLFW 3.4 macOS - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2009-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#define _GLFW_PLATFORM_CONTEXT_STATE _GLFWcontextNSGL nsgl;
#define _GLFW_PLATFORM_LIBRARY_CONTEXT_STATE _GLFWlibraryNSGL nsgl;
// NSGL-specific per-context data
//
typedef struct _GLFWcontextNSGL {
id pixelFormat;
id object;
} _GLFWcontextNSGL;
// NSGL-specific global data
//
typedef struct _GLFWlibraryNSGL {
// dlopen handle for OpenGL.framework (for glfwGetProcAddress)
CFBundleRef framework;
} _GLFWlibraryNSGL;
bool _glfwInitNSGL(void);
void _glfwTerminateNSGL(void);
bool _glfwCreateContextNSGL(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig);
void _glfwDestroyContextNSGL(_GLFWwindow *window);
+333
View File
@@ -0,0 +1,333 @@
//========================================================================
// GLFW 3.4 macOS - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2009-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include <assert.h>
static void
makeContextCurrentNSGL(_GLFWwindow *window) {
if (window) [window->context.nsgl.object makeCurrentContext];
else [NSOpenGLContext clearCurrentContext];
_glfwPlatformSetTls(&_glfw.contextSlot, window);
}
static void
swapBuffersNSGL(_GLFWwindow *window) {
// ARP appears to be unnecessary, but this is future-proof
[window->context.nsgl.object flushBuffer];
}
static void
swapIntervalNSGL(int interval UNUSED) {
// As of Mojave this does not work so we use CVDisplayLink instead
_glfwInputError(GLFW_API_UNAVAILABLE, "NSGL: Swap intervals do not work on macOS");
}
static int
extensionSupportedNSGL(const char *extension UNUSED) {
// There are no NSGL extensions
return false;
}
static GLFWglproc
getProcAddressNSGL(const char *procname) {
CFStringRef symbolName = CFStringCreateWithCString(kCFAllocatorDefault, procname, kCFStringEncodingASCII);
GLFWglproc symbol;
*(void **)&symbol = CFBundleGetFunctionPointerForName(_glfw.nsgl.framework, symbolName);
CFRelease(symbolName);
return symbol;
}
static void
destroyContextNSGL(_GLFWwindow *window) {
[window->context.nsgl.pixelFormat release];
window->context.nsgl.pixelFormat = nil;
[window->context.nsgl.object release];
window->context.nsgl.object = nil;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Initialize OpenGL support
//
bool
_glfwInitNSGL(void) {
if (_glfw.nsgl.framework) return true;
_glfw.nsgl.framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
if (_glfw.nsgl.framework == NULL) {
_glfwInputError(GLFW_API_UNAVAILABLE, "NSGL: Failed to locate OpenGL framework");
return false;
}
return true;
}
// We use a globally shared context across all OS Windows so that
// if all OS Windows are closed the context does not have to be recreated
// with all associated data lost. On Apple kitty can remain running with no
// OS Windows.
static NSOpenGLContext *globally_shared_context = nil;
// Terminate OpenGL support
//
void
_glfwTerminateNSGL(void) {
if (globally_shared_context != nil) {
[globally_shared_context release];
globally_shared_context = nil;
}
}
// Create the OpenGL context
//
bool
_glfwCreateContextNSGL(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) {
if (ctxconfig->client == GLFW_OPENGL_ES_API) {
_glfwInputError(GLFW_API_UNAVAILABLE, "NSGL: OpenGL ES is not available on macOS");
return false;
}
if (ctxconfig->major > 2) {
if (ctxconfig->major == 3 && ctxconfig->minor < 2) {
_glfwInputError(GLFW_VERSION_UNAVAILABLE, "NSGL: The targeted version of macOS does not support OpenGL 3.0 or 3.1 but may support 3.2 and above");
return false;
}
}
// Context robustness modes (GL_KHR_robustness) are not yet supported by
// macOS but are not a hard constraint, so ignore and continue
// Context release behaviors (GL_KHR_context_flush_control) are not yet
// supported by macOS but are not a hard constraint, so ignore and continue
// Debug contexts (GL_KHR_debug) are not yet supported by macOS but are not
// a hard constraint, so ignore and continue
// No-error contexts (GL_KHR_no_error) are not yet supported by macOS but
// are not a hard constraint, so ignore and continue
#define addAttrib(a) \
{ \
assert((size_t)index < sizeof(attribs) / sizeof(attribs[0])); \
attribs[index++] = a; \
}
#define setAttrib(a, v) \
{ \
addAttrib(a); \
addAttrib(v); \
}
NSOpenGLPixelFormatAttribute attribs[40];
int index = 0;
addAttrib(NSOpenGLPFAAccelerated);
addAttrib(NSOpenGLPFAClosestPolicy);
if (ctxconfig->nsgl.offline) {
addAttrib(NSOpenGLPFAAllowOfflineRenderers);
// NOTE: This replaces the NSSupportsAutomaticGraphicsSwitching key in
// Info.plist for unbundled applications
// HACK: This assumes that NSOpenGLPixelFormat will remain
// a straightforward wrapper of its CGL counterpart
addAttrib(kCGLPFASupportsAutomaticGraphicsSwitching);
}
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000
if (ctxconfig->major >= 4) {
setAttrib(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion4_1Core);
} else
#endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/
if (ctxconfig->major >= 3) { setAttrib(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core); }
if (ctxconfig->major <= 2) {
if (fbconfig->auxBuffers != GLFW_DONT_CARE) setAttrib(NSOpenGLPFAAuxBuffers, fbconfig->auxBuffers);
if (fbconfig->accumRedBits != GLFW_DONT_CARE && fbconfig->accumGreenBits != GLFW_DONT_CARE && fbconfig->accumBlueBits != GLFW_DONT_CARE &&
fbconfig->accumAlphaBits != GLFW_DONT_CARE) {
const int accumBits = fbconfig->accumRedBits + fbconfig->accumGreenBits + fbconfig->accumBlueBits + fbconfig->accumAlphaBits;
setAttrib(NSOpenGLPFAAccumSize, accumBits);
}
}
if (fbconfig->redBits != GLFW_DONT_CARE && fbconfig->greenBits != GLFW_DONT_CARE && fbconfig->blueBits != GLFW_DONT_CARE) {
int colorBits = fbconfig->redBits + fbconfig->greenBits + fbconfig->blueBits;
// macOS needs non-zero color size, so set reasonable values
if (colorBits == 0) colorBits = 24;
else if (colorBits < 15) colorBits = 15;
setAttrib(NSOpenGLPFAColorSize, colorBits);
}
if (fbconfig->alphaBits != GLFW_DONT_CARE) setAttrib(NSOpenGLPFAAlphaSize, fbconfig->alphaBits);
if (fbconfig->depthBits != GLFW_DONT_CARE) setAttrib(NSOpenGLPFADepthSize, fbconfig->depthBits);
if (fbconfig->stencilBits != GLFW_DONT_CARE) setAttrib(NSOpenGLPFAStencilSize, fbconfig->stencilBits);
if (fbconfig->stereo) {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
_glfwInputError(GLFW_FORMAT_UNAVAILABLE, "NSGL: Stereo rendering is deprecated");
return false;
#else
addAttrib(NSOpenGLPFAStereo);
#endif
}
if (fbconfig->doublebuffer) addAttrib(NSOpenGLPFADoubleBuffer);
if (fbconfig->samples != GLFW_DONT_CARE) {
if (fbconfig->samples == 0) {
setAttrib(NSOpenGLPFASampleBuffers, 0);
} else {
setAttrib(NSOpenGLPFASampleBuffers, 1);
setAttrib(NSOpenGLPFASamples, fbconfig->samples);
}
}
// NOTE: All NSOpenGLPixelFormats on the relevant cards support sRGB
// framebuffer, so there's no need (and no way) to request it
addAttrib(0);
#undef addAttrib
#undef setAttrib
window->context.nsgl.pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
if (window->context.nsgl.pixelFormat == nil) {
_glfwInputError(GLFW_FORMAT_UNAVAILABLE, "NSGL: Failed to find a suitable pixel format");
return false;
}
NSOpenGLContext *share = globally_shared_context;
if (ctxconfig->share) share = ctxconfig->share->context.nsgl.object;
window->context.nsgl.object = [[NSOpenGLContext alloc] initWithFormat:window->context.nsgl.pixelFormat shareContext:share];
if (window->context.nsgl.object == nil) {
_glfwInputError(GLFW_VERSION_UNAVAILABLE, "NSGL: Failed to create OpenGL context");
return false;
}
if (globally_shared_context == nil) { globally_shared_context = [window->context.nsgl.object retain]; }
if (fbconfig->transparent) {
GLint opaque = 0;
[window->context.nsgl.object setValues:&opaque forParameter:NSOpenGLContextParameterSurfaceOpacity];
}
[window->ns.view setWantsBestResolutionOpenGLSurface:window->ns.retina];
GLint interval = 0;
[window->context.nsgl.object setValues:&interval forParameter:NSOpenGLContextParameterSwapInterval];
[window->context.nsgl.object setView:window->ns.view];
window->context.makeCurrent = makeContextCurrentNSGL;
window->context.swapBuffers = swapBuffersNSGL;
window->context.swapInterval = swapIntervalNSGL;
window->context.extensionSupported = extensionSupportedNSGL;
window->context.getProcAddress = getProcAddressNSGL;
window->context.destroy = destroyContextNSGL;
return true;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW native API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI id
glfwGetNSGLContext(GLFWwindow *handle) {
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(window != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(nil);
if (window->context.client == GLFW_NO_API) {
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL);
return nil;
}
return window->context.nsgl.object;
}
GLFWAPI bool
glfwCocoaRecreateGLDrawable(GLFWwindow *w) {
_GLFWwindow *window = (_GLFWwindow *)w;
if (window->context.client == GLFW_NO_API) return false;
@try {
// Save current state
NSOpenGLPixelFormat *pixelFormat = window->context.nsgl.pixelFormat;
NSOpenGLContext *oldContext = window->context.nsgl.object;
// Create a new context sharing resources with the old one
NSOpenGLContext *newContext = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:oldContext];
if (newContext == nil) return false;
// Copy settings from old context
GLint opacity = 0;
[oldContext getValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity];
[newContext setValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity];
GLint interval = 0;
[newContext setValues:&interval forParameter:NSOpenGLContextParameterSwapInterval];
// Detach old context
[NSOpenGLContext clearCurrentContext];
[oldContext clearDrawable];
// Attach new context to the view
[window->ns.view setWantsBestResolutionOpenGLSurface:window->ns.retina];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[newContext setView:window->ns.view];
#pragma clang diagnostic pop
[newContext makeCurrentContext];
[newContext update];
// Replace context
window->context.nsgl.object = newContext;
[oldContext release];
} @catch (NSException *e) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Failed to recreate NSGL context: %s (%s)", [[e name] UTF8String], [[e reason] UTF8String]);
return false;
}
return true;
}
+55
View File
@@ -0,0 +1,55 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2016 Google Inc.
// Copyright (c) 2016-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include <stdlib.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
int
_glfwPlatformInit(void) {
_glfwPollMonitorsNull();
return true;
}
void
_glfwPlatformTerminate(void) {
free(_glfw.null.clipboardString);
_glfwTerminateOSMesa();
}
const char *
_glfwPlatformGetVersionString(void) {
return _GLFW_VERSION_NUMBER " null OSMesa";
}
+50
View File
@@ -0,0 +1,50 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2016-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
bool
_glfwPlatformInitJoysticks(void) {
return true;
}
void
_glfwPlatformTerminateJoysticks(void) {}
int
_glfwPlatformPollJoystick(_GLFWjoystick *js UNUSED, int mode UNUSED) {
return false;
}
void
_glfwPlatformUpdateGamepadGUID(char *guid UNUSED) {}
+30
View File
@@ -0,0 +1,30 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2006-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#define _GLFW_PLATFORM_JOYSTICK_STATE int nulljs
#define _GLFW_PLATFORM_LIBRARY_JOYSTICK_STATE int nulljs;
#define _GLFW_PLATFORM_MAPPING_NAME ""
+141
View File
@@ -0,0 +1,141 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2016 Google Inc.
// Copyright (c) 2016-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>
// The sole (fake) video mode of our (sole) fake monitor
//
static GLFWvidmode
getVideoMode(void) {
GLFWvidmode mode;
mode.width = 1920;
mode.height = 1080;
mode.redBits = 8;
mode.greenBits = 8;
mode.blueBits = 8;
mode.refreshRate = 60;
return mode;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
void
_glfwPollMonitorsNull(void) {
const float dpi = 141.f;
const GLFWvidmode mode = getVideoMode();
_GLFWmonitor *monitor = _glfwAllocMonitor("Null SuperNoop 0", (int)(mode.width * 25.4f / dpi), (int)(mode.height * 25.4f / dpi));
_glfwInputMonitor(monitor, GLFW_CONNECTED, _GLFW_INSERT_FIRST);
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
void
_glfwPlatformFreeMonitor(_GLFWmonitor *monitor) {
_glfwFreeGammaArrays(&monitor->null.ramp);
}
void
_glfwPlatformGetMonitorPos(_GLFWmonitor *monitor UNUSED, int *xpos, int *ypos) {
if (xpos) *xpos = 0;
if (ypos) *ypos = 0;
}
void
_glfwPlatformGetMonitorContentScale(_GLFWmonitor *monitor UNUSED, float *xscale, float *yscale) {
if (xscale) *xscale = 1.f;
if (yscale) *yscale = 1.f;
}
void
_glfwPlatformGetMonitorWorkarea(_GLFWmonitor *monitor UNUSED, int *xpos, int *ypos, int *width, int *height) {
const GLFWvidmode mode = getVideoMode();
if (xpos) *xpos = 0;
if (ypos) *ypos = 10;
if (width) *width = mode.width;
if (height) *height = mode.height - 10;
}
GLFWvidmode *
_glfwPlatformGetVideoModes(_GLFWmonitor *monitor UNUSED, int *found) {
GLFWvidmode *mode = calloc(1, sizeof(GLFWvidmode));
*mode = getVideoMode();
*found = 1;
return mode;
}
void
_glfwPlatformGetVideoMode(_GLFWmonitor *monitor UNUSED, GLFWvidmode *mode) {
*mode = getVideoMode();
}
bool
_glfwPlatformGetGammaRamp(_GLFWmonitor *monitor, GLFWgammaramp *ramp) {
if (!monitor->null.ramp.size) {
_glfwAllocGammaArrays(&monitor->null.ramp, 256);
for (unsigned int i = 0; i < monitor->null.ramp.size; i++) {
const float gamma = 2.2f;
float value;
value = i / (float)(monitor->null.ramp.size - 1);
value = powf(value, 1.f / gamma) * 65535.f + 0.5f;
value = _glfw_fminf(value, 65535.f);
monitor->null.ramp.red[i] = (unsigned short)value;
monitor->null.ramp.green[i] = (unsigned short)value;
monitor->null.ramp.blue[i] = (unsigned short)value;
}
}
_glfwAllocGammaArrays(ramp, monitor->null.ramp.size);
memcpy(ramp->red, monitor->null.ramp.red, sizeof(short) * ramp->size);
memcpy(ramp->green, monitor->null.ramp.green, sizeof(short) * ramp->size);
memcpy(ramp->blue, monitor->null.ramp.blue, sizeof(short) * ramp->size);
return true;
}
void
_glfwPlatformSetGammaRamp(_GLFWmonitor *monitor, const GLFWgammaramp *ramp) {
if (monitor->null.ramp.size != ramp->size) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Null: Gamma ramp size must match current ramp size");
return;
}
memcpy(monitor->null.ramp.red, ramp->red, sizeof(short) * ramp->size);
memcpy(monitor->null.ramp.green, ramp->green, sizeof(short) * ramp->size);
memcpy(monitor->null.ramp.blue, ramp->blue, sizeof(short) * ramp->size);
}
+85
View File
@@ -0,0 +1,85 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2016 Google Inc.
// Copyright (c) 2016-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <dlfcn.h>
#define _GLFW_PLATFORM_WINDOW_STATE _GLFWwindowNull null
#define _GLFW_PLATFORM_LIBRARY_WINDOW_STATE _GLFWlibraryNull null
#define _GLFW_PLATFORM_MONITOR_STATE _GLFWmonitorNull null
#define _GLFW_PLATFORM_CONTEXT_STATE
#define _GLFW_PLATFORM_CURSOR_STATE
#define _GLFW_PLATFORM_LIBRARY_CONTEXT_STATE
#include "posix_time.h"
#include "posix_thread.h"
#include "null_joystick.h"
#if defined(_GLFW_WIN32)
#define _glfw_dlopen(name) LoadLibraryA(name)
#define _glfw_dlclose(handle) FreeLibrary((HMODULE)handle)
#define _glfw_dlsym(handle, name) GetProcAddress((HMODULE)handle, name)
#else
#define _glfw_dlopen(name) dlopen(name, RTLD_LAZY | RTLD_LOCAL)
#define _glfw_dlclose(handle) dlclose(handle)
#define _glfw_dlsym(handle, name) dlsym(handle, name)
#endif
// Null-specific per-window data
//
typedef struct _GLFWwindowNull {
int xpos;
int ypos;
int width;
int height;
char *title;
bool visible;
bool iconified;
bool maximized;
bool resizable;
bool decorated;
bool floating;
bool transparent;
float opacity;
} _GLFWwindowNull;
// Null-specific per-monitor data
//
typedef struct _GLFWmonitorNull {
GLFWgammaramp ramp;
} _GLFWmonitorNull;
// Null-specific global data
//
typedef struct _GLFWlibraryNull {
int xcursor;
int ycursor;
char *clipboardString;
_GLFWwindow *focusedWindow;
} _GLFWlibraryNull;
void _glfwPollMonitorsNull(void);
+584
View File
@@ -0,0 +1,584 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2016 Google Inc.
// Copyright (c) 2016-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include "../kitty/monotonic.h"
#include <errno.h>
#include <stdlib.h>
static void
applySizeLimits(_GLFWwindow *window, int *width, int *height) {
if (window->numer != GLFW_DONT_CARE && window->denom != GLFW_DONT_CARE) {
const float ratio = (float)window->numer / (float)window->denom;
*height = (int)(*width / ratio);
}
if (window->minwidth != GLFW_DONT_CARE && *width < window->minwidth) *width = window->minwidth;
else if (window->maxwidth != GLFW_DONT_CARE && *width > window->maxwidth) *width = window->maxwidth;
if (window->minheight != GLFW_DONT_CARE && *height < window->minheight) *height = window->minheight;
else if (window->maxheight != GLFW_DONT_CARE && *height > window->maxheight) *height = window->maxheight;
}
static void
fitToMonitor(_GLFWwindow *window) {
GLFWvidmode mode;
_glfwPlatformGetVideoMode(window->monitor, &mode);
_glfwPlatformGetMonitorPos(window->monitor, &window->null.xpos, &window->null.ypos);
window->null.width = mode.width;
window->null.height = mode.height;
}
static void
acquireMonitor(_GLFWwindow *window) {
_glfwInputMonitorWindow(window->monitor, window);
}
static void
releaseMonitor(_GLFWwindow *window) {
if (window->monitor->window != window) return;
_glfwInputMonitorWindow(window->monitor, NULL);
}
static int
createNativeWindow(_GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWfbconfig *fbconfig) {
if (window->monitor) fitToMonitor(window);
else {
window->null.xpos = 17;
window->null.ypos = 17;
window->null.width = wndconfig->width;
window->null.height = wndconfig->height;
}
window->null.visible = wndconfig->visible;
window->null.decorated = wndconfig->decorated;
window->null.maximized = wndconfig->maximized;
window->null.floating = wndconfig->floating;
window->null.transparent = fbconfig->transparent;
window->null.opacity = 1.f;
return true;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
int
_glfwPlatformCreateWindow(_GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) {
if (!createNativeWindow(window, wndconfig, fbconfig)) return false;
if (ctxconfig->client != GLFW_NO_API) {
if (ctxconfig->source == GLFW_NATIVE_CONTEXT_API || ctxconfig->source == GLFW_OSMESA_CONTEXT_API) {
if (!_glfwInitOSMesa()) return false;
if (!_glfwCreateContextOSMesa(window, ctxconfig, fbconfig)) return false;
} else {
_glfwInputError(GLFW_API_UNAVAILABLE, "Null: EGL not available");
return false;
}
}
if (window->monitor) {
_glfwPlatformShowWindow(window);
_glfwPlatformFocusWindow(window);
acquireMonitor(window);
}
return true;
}
void
_glfwPlatformDestroyWindow(_GLFWwindow *window) {
if (window->monitor) releaseMonitor(window);
if (_glfw.null.focusedWindow == window) _glfw.null.focusedWindow = NULL;
if (window->context.destroy) window->context.destroy(window);
}
void
_glfwPlatformSetWindowTitle(_GLFWwindow *window UNUSED, const char *title UNUSED) {}
void
_glfwPlatformSetWindowIcon(_GLFWwindow *window UNUSED, int count UNUSED, const GLFWimage *images UNUSED) {}
void
_glfwPlatformSetWindowMonitor(_GLFWwindow *window, _GLFWmonitor *monitor, int xpos, int ypos, int width, int height, int refreshRate UNUSED) {
if (window->monitor == monitor) {
if (!monitor) {
_glfwPlatformSetWindowPos(window, xpos, ypos);
_glfwPlatformSetWindowSize(window, width, height);
}
return;
}
if (window->monitor) releaseMonitor(window);
_glfwInputWindowMonitor(window, monitor);
if (window->monitor) {
window->null.visible = true;
acquireMonitor(window);
fitToMonitor(window);
} else {
_glfwPlatformSetWindowPos(window, xpos, ypos);
_glfwPlatformSetWindowSize(window, width, height);
}
}
void
_glfwPlatformGetWindowPos(_GLFWwindow *window, int *xpos, int *ypos) {
if (xpos) *xpos = window->null.xpos;
if (ypos) *ypos = window->null.ypos;
}
void
_glfwPlatformSetWindowPos(_GLFWwindow *window, int xpos, int ypos) {
if (window->monitor) return;
if (window->null.xpos != xpos || window->null.ypos != ypos) {
window->null.xpos = xpos;
window->null.ypos = ypos;
_glfwInputWindowPos(window, xpos, ypos);
}
}
void
_glfwPlatformGetWindowSize(_GLFWwindow *window, int *width, int *height) {
if (width) *width = window->null.width;
if (height) *height = window->null.height;
}
void
_glfwPlatformSetWindowSize(_GLFWwindow *window, int width, int height) {
if (window->monitor) return;
if (window->null.width != width || window->null.height != height) {
window->null.width = width;
window->null.height = height;
_glfwInputWindowSize(window, width, height);
_glfwInputFramebufferSize(window, width, height);
}
}
void
_glfwPlatformSetWindowSizeLimits(_GLFWwindow *window, int minwidth UNUSED, int minheight UNUSED, int maxwidth UNUSED, int maxheight UNUSED) {
int width = window->null.width;
int height = window->null.height;
applySizeLimits(window, &width, &height);
_glfwPlatformSetWindowSize(window, width, height);
}
void
_glfwPlatformSetWindowAspectRatio(_GLFWwindow *window, int n UNUSED, int d UNUSED) {
int width = window->null.width;
int height = window->null.height;
applySizeLimits(window, &width, &height);
_glfwPlatformSetWindowSize(window, width, height);
}
void
_glfwPlatformSetWindowSizeIncrements(_GLFWwindow *window UNUSED, int widthincr UNUSED, int heightincr UNUSED) {}
void
_glfwPlatformGetFramebufferSize(_GLFWwindow *window, int *width, int *height) {
if (width) *width = window->null.width;
if (height) *height = window->null.height;
}
void
_glfwPlatformGetWindowFrameSize(_GLFWwindow *window, int *left, int *top, int *right, int *bottom) {
if (window->null.decorated && !window->monitor) {
if (left) *left = 1;
if (top) *top = 10;
if (right) *right = 1;
if (bottom) *bottom = 1;
} else {
if (left) *left = 0;
if (top) *top = 0;
if (right) *right = 0;
if (bottom) *bottom = 0;
}
}
void
_glfwPlatformGetWindowContentScale(_GLFWwindow *window UNUSED, float *xscale, float *yscale) {
if (xscale) *xscale = 1.f;
if (yscale) *yscale = 1.f;
}
monotonic_t
_glfwPlatformGetDoubleClickInterval(_GLFWwindow *window UNUSED) {
return ms_to_monotonic_t(500ll);
}
void
_glfwPlatformGetKeyboardRepeatDelay(monotonic_t *delay, monotonic_t *interval) {
if (delay) *delay = ms_to_monotonic_t(500ll);
if (interval) *interval = ms_to_monotonic_t(30ll);
}
void
_glfwPlatformIconifyWindow(_GLFWwindow *window) {
if (_glfw.null.focusedWindow == window) {
_glfw.null.focusedWindow = NULL;
_glfwInputWindowFocus(window, false);
}
if (!window->null.iconified) {
window->null.iconified = true;
_glfwInputWindowIconify(window, true);
if (window->monitor) releaseMonitor(window);
}
}
void
_glfwPlatformRestoreWindow(_GLFWwindow *window) {
if (window->null.iconified) {
window->null.iconified = false;
_glfwInputWindowIconify(window, false);
if (window->monitor) acquireMonitor(window);
} else if (window->null.maximized) {
window->null.maximized = false;
_glfwInputWindowMaximize(window, false);
}
}
void
_glfwPlatformMaximizeWindow(_GLFWwindow *window) {
if (!window->null.maximized) {
window->null.maximized = true;
_glfwInputWindowMaximize(window, true);
}
}
int
_glfwPlatformWindowMaximized(_GLFWwindow *window) {
return window->null.maximized;
}
int
_glfwPlatformWindowHovered(_GLFWwindow *window) {
return _glfw.null.xcursor >= window->null.xpos && _glfw.null.ycursor >= window->null.ypos &&
_glfw.null.xcursor <= window->null.xpos + window->null.width - 1 && _glfw.null.ycursor <= window->null.ypos + window->null.height - 1;
}
int
_glfwPlatformFramebufferTransparent(_GLFWwindow *window) {
return window->null.transparent;
}
void
_glfwPlatformSetWindowResizable(_GLFWwindow *window, bool enabled) {
window->null.resizable = enabled;
}
void
_glfwPlatformSetWindowDecorated(_GLFWwindow *window, bool enabled) {
window->null.decorated = enabled;
}
void
_glfwPlatformSetWindowFloating(_GLFWwindow *window, bool enabled) {
window->null.floating = enabled;
}
void
_glfwPlatformSetWindowMousePassthrough(_GLFWwindow *window UNUSED, bool enabled UNUSED) {}
float
_glfwPlatformGetWindowOpacity(_GLFWwindow *window) {
return window->null.opacity;
}
void
_glfwPlatformSetWindowOpacity(_GLFWwindow *window, float opacity) {
window->null.opacity = opacity;
}
void
_glfwPlatformSetRawMouseMotion(_GLFWwindow *window UNUSED, bool enabled UNUSED) {}
bool
_glfwPlatformRawMouseMotionSupported(void) {
return true;
}
void
_glfwPlatformShowWindow(_GLFWwindow *window) {
window->null.visible = true;
}
void
_glfwPlatformRequestWindowAttention(_GLFWwindow *window UNUSED) {}
int
_glfwPlatformWindowBell(_GLFWwindow *window UNUSED) {
return false;
}
void
_glfwPlatformHideWindow(_GLFWwindow *window) {
if (_glfw.null.focusedWindow == window) {
_glfw.null.focusedWindow = NULL;
_glfwInputWindowFocus(window, false);
}
window->null.visible = false;
}
void
_glfwPlatformFocusWindow(_GLFWwindow *window) {
if (_glfw.null.focusedWindow == window) return;
if (!window->null.visible) return;
_GLFWwindow *previous = _glfw.null.focusedWindow;
_glfw.null.focusedWindow = window;
if (previous) {
_glfwInputWindowFocus(previous, false);
if (previous->monitor && previous->autoIconify) _glfwPlatformIconifyWindow(previous);
}
_glfwInputWindowFocus(window, true);
}
int
_glfwPlatformWindowFocused(_GLFWwindow *window) {
return _glfw.null.focusedWindow == window;
}
int
_glfwPlatformWindowOccluded(_GLFWwindow *window UNUSED) {
return false;
}
int
_glfwPlatformWindowIconified(_GLFWwindow *window) {
return window->null.iconified;
}
int
_glfwPlatformWindowVisible(_GLFWwindow *window) {
return window->null.visible;
}
void
_glfwPlatformPollEvents(void) {}
void
_glfwPlatformWaitEvents(void) {}
void
_glfwPlatformWaitEventsTimeout(monotonic_t timeout UNUSED) {}
void
_glfwPlatformPostEmptyEvent(void) {}
void
_glfwPlatformGetCursorPos(_GLFWwindow *window, double *xpos, double *ypos) {
if (xpos) *xpos = _glfw.null.xcursor - window->null.xpos;
if (ypos) *ypos = _glfw.null.ycursor - window->null.ypos;
}
void
_glfwPlatformSetCursorPos(_GLFWwindow *window, double x, double y) {
_glfw.null.xcursor = window->null.xpos + (int)x;
_glfw.null.ycursor = window->null.ypos + (int)y;
}
void
_glfwPlatformSetCursorMode(_GLFWwindow *window UNUSED, int mode UNUSED) {}
int
_glfwPlatformCreateCursor(_GLFWcursor *cursor UNUSED, const GLFWimage *image UNUSED, int xhot UNUSED, int yhot UNUSED, int count UNUSED) {
return true;
}
int
_glfwPlatformCreateStandardCursor(_GLFWcursor *cursor UNUSED, int shape UNUSED) {
return true;
}
void
_glfwPlatformDestroyCursor(_GLFWcursor *cursor UNUSED) {}
void
_glfwPlatformSetCursor(_GLFWwindow *window UNUSED, _GLFWcursor *cursor UNUSED) {}
void
_glfwPlatformCancelDrag(_GLFWwindow *window UNUSED) {
// No-op for null platform
}
int
_glfwPlatformStartDrag(_GLFWwindow *window, const GLFWimage *thumbnail) {
(void)window;
(void)thumbnail;
return ENOTSUP;
}
void
_glfwPlatformFreeDragSourceData(void) {}
int
_glfwPlatformDragDataReady(const char *mime_type UNUSED, const char *data UNUSED, size_t sz UNUSED, int type UNUSED) {
return 0;
}
int
_glfwPlatformChangeDragImage(const GLFWimage *thumbnail) {
(void)thumbnail;
return 0;
}
const char **
_glfwPlatformGetDropMimeTypes(GLFWDropData *drop UNUSED, int *count) {
if (count) *count = 0;
return NULL;
}
ssize_t
_glfwPlatformReadDropData(GLFWDropData *drop UNUSED, const char *mime UNUSED, void *buffer UNUSED, size_t capacity UNUSED, monotonic_t timeout UNUSED) {
return -ENOENT;
}
void
_glfwPlatformFinishDrop(GLFWDropData *drop, GLFWDragOperationType operation UNUSED, bool success UNUSED) {
if (!drop) return;
// Free the heap-allocated drop data structure
free(drop);
}
void
_glfwPlatformSetClipboardString(const char *string) {
char *copy = _glfw_strdup(string);
free(_glfw.null.clipboardString);
_glfw.null.clipboardString = copy;
}
const char *
_glfwPlatformGetClipboardString(void) {
return _glfw.null.clipboardString;
}
const char *
_glfwPlatformGetNativeKeyName(int native_key) {
switch (scancode) {
case GLFW_KEY_APOSTROPHE: return "'";
case GLFW_KEY_COMMA: return ",";
case GLFW_KEY_MINUS:
case GLFW_KEY_KP_SUBTRACT: return "-";
case GLFW_KEY_PERIOD:
case GLFW_KEY_KP_DECIMAL: return ".";
case GLFW_KEY_SLASH:
case GLFW_KEY_KP_DIVIDE: return "/";
case GLFW_KEY_SEMICOLON: return ";";
case GLFW_KEY_EQUAL:
case GLFW_KEY_KP_EQUAL: return "=";
case GLFW_KEY_LEFT_BRACKET: return "[";
case GLFW_KEY_RIGHT_BRACKET: return "]";
case GLFW_KEY_KP_MULTIPLY: return "*";
case GLFW_KEY_KP_ADD: return "+";
case GLFW_KEY_BACKSLASH:
case GLFW_KEY_WORLD_1:
case GLFW_KEY_WORLD_2: return "\\";
case GLFW_KEY_0:
case GLFW_KEY_KP_0: return "0";
case GLFW_KEY_1:
case GLFW_KEY_KP_1: return "1";
case GLFW_KEY_2:
case GLFW_KEY_KP_2: return "2";
case GLFW_KEY_3:
case GLFW_KEY_KP_3: return "3";
case GLFW_KEY_4:
case GLFW_KEY_KP_4: return "4";
case GLFW_KEY_5:
case GLFW_KEY_KP_5: return "5";
case GLFW_KEY_6:
case GLFW_KEY_KP_6: return "6";
case GLFW_KEY_7:
case GLFW_KEY_KP_7: return "7";
case GLFW_KEY_8:
case GLFW_KEY_KP_8: return "8";
case GLFW_KEY_9:
case GLFW_KEY_KP_9: return "9";
case GLFW_KEY_A: return "a";
case GLFW_KEY_B: return "b";
case GLFW_KEY_C: return "c";
case GLFW_KEY_D: return "d";
case GLFW_KEY_E: return "e";
case GLFW_KEY_F: return "f";
case GLFW_KEY_G: return "g";
case GLFW_KEY_H: return "h";
case GLFW_KEY_I: return "i";
case GLFW_KEY_J: return "j";
case GLFW_KEY_K: return "k";
case GLFW_KEY_L: return "l";
case GLFW_KEY_M: return "m";
case GLFW_KEY_N: return "n";
case GLFW_KEY_O: return "o";
case GLFW_KEY_P: return "p";
case GLFW_KEY_Q: return "q";
case GLFW_KEY_R: return "r";
case GLFW_KEY_S: return "s";
case GLFW_KEY_T: return "t";
case GLFW_KEY_U: return "u";
case GLFW_KEY_V: return "v";
case GLFW_KEY_W: return "w";
case GLFW_KEY_X: return "x";
case GLFW_KEY_Y: return "y";
case GLFW_KEY_Z: return "z";
}
return NULL;
}
int
_glfwPlatformGetNativeKeyForKey(int key) {
return key;
}
void
_glfwPlatformGetRequiredInstanceExtensions(char **extensions UNUSED) {}
int
_glfwPlatformGetPhysicalDevicePresentationSupport(VkInstance instance UNUSED, VkPhysicalDevice device UNUSED, uint32_t queuefamily UNUSED) {
return false;
}
VkResult
_glfwPlatformCreateWindowSurface(
VkInstance instance UNUSED, _GLFWwindow *window UNUSED, const VkAllocationCallbacks *allocator UNUSED, VkSurfaceKHR *surface UNUSED) {
// This seems like the most appropriate error to return here
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
+294
View File
@@ -0,0 +1,294 @@
//========================================================================
// GLFW 3.4 OSMesa - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2016 Google Inc.
// Copyright (c) 2016-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// Please use C89 style variable declarations in this file because VS 2010
//========================================================================
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "internal.h"
static void
makeContextCurrentOSMesa(_GLFWwindow *window) {
if (window) {
int width, height;
_glfwPlatformGetFramebufferSize(window, &width, &height);
// Check to see if we need to allocate a new buffer
if ((window->context.osmesa.buffer == NULL) || (width != window->context.osmesa.width) || (height != window->context.osmesa.height)) {
free(window->context.osmesa.buffer);
// Allocate the new buffer (width * height * 8-bit RGBA)
window->context.osmesa.buffer = calloc(4, (size_t)width * height);
window->context.osmesa.width = width;
window->context.osmesa.height = height;
}
if (!OSMesaMakeCurrent(window->context.osmesa.handle, window->context.osmesa.buffer, GL_UNSIGNED_BYTE, width, height)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "OSMesa: Failed to make context current");
return;
}
}
_glfwPlatformSetTls(&_glfw.contextSlot, window);
}
static GLFWglproc
getProcAddressOSMesa(const char *procname) {
return (GLFWglproc)OSMesaGetProcAddress(procname);
}
static void
destroyContextOSMesa(_GLFWwindow *window) {
if (window->context.osmesa.handle) {
OSMesaDestroyContext(window->context.osmesa.handle);
window->context.osmesa.handle = NULL;
}
if (window->context.osmesa.buffer) {
free(window->context.osmesa.buffer);
window->context.osmesa.width = 0;
window->context.osmesa.height = 0;
}
}
static void
swapBuffersOSMesa(_GLFWwindow *window UNUSED) {
// No double buffering on OSMesa
}
static void
swapIntervalOSMesa(int interval UNUSED) {
// No swap interval on OSMesa
}
static int
extensionSupportedOSMesa(const char *extension UNUSED) {
// OSMesa does not have extensions
return false;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
bool
_glfwInitOSMesa(void) {
int i;
const char *sonames[] = {
#if defined(_GLFW_OSMESA_LIBRARY)
_GLFW_OSMESA_LIBRARY,
#elif defined(_WIN32)
"libOSMesa.dll",
"OSMesa.dll",
#elif defined(__APPLE__)
"libOSMesa.8.dylib",
#elif defined(__CYGWIN__)
"libOSMesa-8.so",
#else
"libOSMesa.so.8",
"libOSMesa.so.6",
#endif
NULL};
if (_glfw.osmesa.handle) return true;
for (i = 0; sonames[i]; i++) {
_glfw.osmesa.handle = _glfw_dlopen(sonames[i]);
if (_glfw.osmesa.handle) break;
}
if (!_glfw.osmesa.handle) {
_glfwInputError(GLFW_API_UNAVAILABLE, "OSMesa: Library not found");
return false;
}
glfw_dlsym(_glfw.osmesa.CreateContextExt, _glfw.osmesa.handle, "OSMesaCreateContextExt");
glfw_dlsym(_glfw.osmesa.CreateContextAttribs, _glfw.osmesa.handle, "OSMesaCreateContextAttribs");
glfw_dlsym(_glfw.osmesa.DestroyContext, _glfw.osmesa.handle, "OSMesaDestroyContext");
glfw_dlsym(_glfw.osmesa.MakeCurrent, _glfw.osmesa.handle, "OSMesaMakeCurrent");
glfw_dlsym(_glfw.osmesa.GetColorBuffer, _glfw.osmesa.handle, "OSMesaGetColorBuffer");
glfw_dlsym(_glfw.osmesa.GetDepthBuffer, _glfw.osmesa.handle, "OSMesaGetDepthBuffer");
glfw_dlsym(_glfw.osmesa.GetProcAddress, _glfw.osmesa.handle, "OSMesaGetProcAddress");
if (!_glfw.osmesa.CreateContextExt || !_glfw.osmesa.DestroyContext || !_glfw.osmesa.MakeCurrent || !_glfw.osmesa.GetColorBuffer ||
!_glfw.osmesa.GetDepthBuffer || !_glfw.osmesa.GetProcAddress) {
_glfwInputError(GLFW_PLATFORM_ERROR, "OSMesa: Failed to load required entry points");
_glfwTerminateOSMesa();
return false;
}
return true;
}
void
_glfwTerminateOSMesa(void) {
if (_glfw.osmesa.handle) {
_glfw_dlclose(_glfw.osmesa.handle);
_glfw.osmesa.handle = NULL;
}
}
#define setAttrib(a, v) \
{ \
assert(((size_t)index + 1) < sizeof(attribs) / sizeof(attribs[0])); \
attribs[index++] = a; \
attribs[index++] = v; \
}
bool
_glfwCreateContextOSMesa(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) {
OSMesaContext share = NULL;
const int accumBits = fbconfig->accumRedBits + fbconfig->accumGreenBits + fbconfig->accumBlueBits + fbconfig->accumAlphaBits;
if (ctxconfig->client == GLFW_OPENGL_ES_API) {
_glfwInputError(GLFW_API_UNAVAILABLE, "OSMesa: OpenGL ES is not available on OSMesa");
return false;
}
if (ctxconfig->share) share = ctxconfig->share->context.osmesa.handle;
if (OSMesaCreateContextAttribs) {
int index = 0, attribs[40];
setAttrib(OSMESA_FORMAT, OSMESA_RGBA);
setAttrib(OSMESA_DEPTH_BITS, fbconfig->depthBits);
setAttrib(OSMESA_STENCIL_BITS, fbconfig->stencilBits);
setAttrib(OSMESA_ACCUM_BITS, accumBits);
if (ctxconfig->profile == GLFW_OPENGL_CORE_PROFILE) {
setAttrib(OSMESA_PROFILE, OSMESA_CORE_PROFILE);
} else if (ctxconfig->profile == GLFW_OPENGL_COMPAT_PROFILE) {
setAttrib(OSMESA_PROFILE, OSMESA_COMPAT_PROFILE);
}
if (ctxconfig->major != 1 || ctxconfig->minor != 0) {
setAttrib(OSMESA_CONTEXT_MAJOR_VERSION, ctxconfig->major);
setAttrib(OSMESA_CONTEXT_MINOR_VERSION, ctxconfig->minor);
}
if (ctxconfig->forward) {
_glfwInputError(GLFW_VERSION_UNAVAILABLE, "OSMesa: Forward-compatible contexts not supported");
return false;
}
setAttrib(0, 0);
window->context.osmesa.handle = OSMesaCreateContextAttribs(attribs, share);
} else {
if (ctxconfig->profile) {
_glfwInputError(GLFW_VERSION_UNAVAILABLE, "OSMesa: OpenGL profiles unavailable");
return false;
}
window->context.osmesa.handle = OSMesaCreateContextExt(OSMESA_RGBA, fbconfig->depthBits, fbconfig->stencilBits, accumBits, share);
}
if (window->context.osmesa.handle == NULL) {
_glfwInputError(GLFW_VERSION_UNAVAILABLE, "OSMesa: Failed to create context");
return false;
}
window->context.makeCurrent = makeContextCurrentOSMesa;
window->context.swapBuffers = swapBuffersOSMesa;
window->context.swapInterval = swapIntervalOSMesa;
window->context.extensionSupported = extensionSupportedOSMesa;
window->context.getProcAddress = getProcAddressOSMesa;
window->context.destroy = destroyContextOSMesa;
return true;
}
#undef setAttrib
//////////////////////////////////////////////////////////////////////////
////// GLFW native API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI int
glfwGetOSMesaColorBuffer(GLFWwindow *handle, int *width, int *height, int *format, void **buffer) {
void *mesaBuffer;
GLint mesaWidth, mesaHeight, mesaFormat;
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(window != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(false);
if (!OSMesaGetColorBuffer(window->context.osmesa.handle, &mesaWidth, &mesaHeight, &mesaFormat, &mesaBuffer)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "OSMesa: Failed to retrieve color buffer");
return false;
}
if (width) *width = mesaWidth;
if (height) *height = mesaHeight;
if (format) *format = mesaFormat;
if (buffer) *buffer = mesaBuffer;
return true;
}
GLFWAPI int
glfwGetOSMesaDepthBuffer(GLFWwindow *handle, int *width, int *height, int *bytesPerValue, void **buffer) {
void *mesaBuffer;
GLint mesaWidth, mesaHeight, mesaBytes;
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(window != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(false);
if (!OSMesaGetDepthBuffer(window->context.osmesa.handle, &mesaWidth, &mesaHeight, &mesaBytes, &mesaBuffer)) {
_glfwInputError(GLFW_PLATFORM_ERROR, "OSMesa: Failed to retrieve depth buffer");
return false;
}
if (width) *width = mesaWidth;
if (height) *height = mesaHeight;
if (bytesPerValue) *bytesPerValue = mesaBytes;
if (buffer) *buffer = mesaBuffer;
return true;
}
GLFWAPI OSMesaContext
glfwGetOSMesaContext(GLFWwindow *handle) {
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(window != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
if (window->context.client == GLFW_NO_API) {
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL);
return NULL;
}
return window->context.osmesa.handle;
}
+85
View File
@@ -0,0 +1,85 @@
//========================================================================
// GLFW 3.4 OSMesa - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2016 Google Inc.
// Copyright (c) 2016-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#define OSMESA_RGBA 0x1908
#define OSMESA_FORMAT 0x22
#define OSMESA_DEPTH_BITS 0x30
#define OSMESA_STENCIL_BITS 0x31
#define OSMESA_ACCUM_BITS 0x32
#define OSMESA_PROFILE 0x33
#define OSMESA_CORE_PROFILE 0x34
#define OSMESA_COMPAT_PROFILE 0x35
#define OSMESA_CONTEXT_MAJOR_VERSION 0x36
#define OSMESA_CONTEXT_MINOR_VERSION 0x37
typedef void *OSMesaContext;
typedef void (*OSMESAproc)(void);
typedef OSMesaContext(GLAPIENTRY *PFN_OSMesaCreateContextExt)(GLenum, GLint, GLint, GLint, OSMesaContext);
typedef OSMesaContext(GLAPIENTRY *PFN_OSMesaCreateContextAttribs)(const int *, OSMesaContext);
typedef void(GLAPIENTRY *PFN_OSMesaDestroyContext)(OSMesaContext);
typedef int(GLAPIENTRY *PFN_OSMesaMakeCurrent)(OSMesaContext, void *, int, int, int);
typedef int(GLAPIENTRY *PFN_OSMesaGetColorBuffer)(OSMesaContext, int *, int *, int *, void **);
typedef int(GLAPIENTRY *PFN_OSMesaGetDepthBuffer)(OSMesaContext, int *, int *, int *, void **);
typedef GLFWglproc(GLAPIENTRY *PFN_OSMesaGetProcAddress)(const char *);
#define OSMesaCreateContextExt _glfw.osmesa.CreateContextExt
#define OSMesaCreateContextAttribs _glfw.osmesa.CreateContextAttribs
#define OSMesaDestroyContext _glfw.osmesa.DestroyContext
#define OSMesaMakeCurrent _glfw.osmesa.MakeCurrent
#define OSMesaGetColorBuffer _glfw.osmesa.GetColorBuffer
#define OSMesaGetDepthBuffer _glfw.osmesa.GetDepthBuffer
#define OSMesaGetProcAddress _glfw.osmesa.GetProcAddress
// OSMesa-specific per-context data
//
typedef struct _GLFWcontextOSMesa {
OSMesaContext handle;
int width;
int height;
void *buffer;
} _GLFWcontextOSMesa;
// OSMesa-specific global data
//
typedef struct _GLFWlibraryOSMesa {
void *handle;
PFN_OSMesaCreateContextExt CreateContextExt;
PFN_OSMesaCreateContextAttribs CreateContextAttribs;
PFN_OSMesaDestroyContext DestroyContext;
PFN_OSMesaMakeCurrent MakeCurrent;
PFN_OSMesaGetColorBuffer GetColorBuffer;
PFN_OSMesaGetDepthBuffer GetDepthBuffer;
PFN_OSMesaGetProcAddress GetProcAddress;
} _GLFWlibraryOSMesa;
bool _glfwInitOSMesa(void);
void _glfwTerminateOSMesa(void);
bool _glfwCreateContextOSMesa(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig);
+99
View File
@@ -0,0 +1,99 @@
//========================================================================
// GLFW 3.4 POSIX - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include <assert.h>
#include <string.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
bool
_glfwPlatformCreateTls(_GLFWtls *tls) {
assert(tls->posix.allocated == false);
if (pthread_key_create(&tls->posix.key, NULL) != 0) {
_glfwInputError(GLFW_PLATFORM_ERROR, "POSIX: Failed to create context TLS");
return false;
}
tls->posix.allocated = true;
return true;
}
void
_glfwPlatformDestroyTls(_GLFWtls *tls) {
if (tls->posix.allocated) pthread_key_delete(tls->posix.key);
memset(tls, 0, sizeof(_GLFWtls));
}
void *
_glfwPlatformGetTls(_GLFWtls *tls) {
assert(tls->posix.allocated == true);
return pthread_getspecific(tls->posix.key);
}
void
_glfwPlatformSetTls(_GLFWtls *tls, void *value) {
assert(tls->posix.allocated == true);
pthread_setspecific(tls->posix.key, value);
}
bool
_glfwPlatformCreateMutex(_GLFWmutex *mutex) {
assert(mutex->posix.allocated == false);
if (pthread_mutex_init(&mutex->posix.handle, NULL) != 0) {
_glfwInputError(GLFW_PLATFORM_ERROR, "POSIX: Failed to create mutex");
return false;
}
return mutex->posix.allocated = true;
}
void
_glfwPlatformDestroyMutex(_GLFWmutex *mutex) {
if (mutex->posix.allocated) pthread_mutex_destroy(&mutex->posix.handle);
memset(mutex, 0, sizeof(_GLFWmutex));
}
void
_glfwPlatformLockMutex(_GLFWmutex *mutex) {
assert(mutex->posix.allocated == true);
pthread_mutex_lock(&mutex->posix.handle);
}
void
_glfwPlatformUnlockMutex(_GLFWmutex *mutex) {
assert(mutex->posix.allocated == true);
pthread_mutex_unlock(&mutex->posix.handle);
}
+48
View File
@@ -0,0 +1,48 @@
//========================================================================
// GLFW 3.4 POSIX - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2017 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <pthread.h>
#define _GLFW_PLATFORM_TLS_STATE _GLFWtlsPOSIX posix
#define _GLFW_PLATFORM_MUTEX_STATE _GLFWmutexPOSIX posix
// POSIX-specific thread local storage data
//
typedef struct _GLFWtlsPOSIX {
bool allocated;
pthread_key_t key;
} _GLFWtlsPOSIX;
// POSIX-specific mutex data
//
typedef struct _GLFWmutexPOSIX {
bool allocated;
pthread_mutex_t handle;
} _GLFWmutexPOSIX;
+187
View File
@@ -0,0 +1,187 @@
{
"cocoa": {
"headers": [
"cocoa_platform.h",
"cocoa_joystick.h",
"posix_thread.h",
"nsgl_context.h",
"egl_context.h",
"osmesa_context.h"
],
"sources": [
"cocoa_init.m",
"cocoa_joystick.m",
"cocoa_monitor.m",
"cocoa_window.m",
"cocoa_displaylink.m",
"posix_thread.c",
"nsgl_context.m",
"egl_context.c",
"osmesa_context.c"
]
},
"common": {
"headers": [
"internal.h",
"mappings.h"
],
"sources": [
"context.c",
"init.c",
"input.c",
"monitor.c",
"vulkan.c",
"monotonic.c",
"window.c"
]
},
"osmesa": {
"headers": [
"null_platform.h",
"null_joystick.h",
"posix_thread.h",
"osmesa_context.h"
],
"sources": [
"null_init.c",
"null_monitor.c",
"null_window.c",
"null_joystick.c",
"posix_thread.c",
"osmesa_context.c"
]
},
"wayland": {
"headers": [
"wl_platform.h",
"posix_thread.h",
"wl_cursors.h",
"wl_text_input.h",
"xkb_glfw.h",
"dbus_glfw.h",
"ibus_glfw.h",
"backend_utils.h",
"egl_context.h",
"osmesa_context.h",
"linux_joystick.h",
"null_joystick.h",
"linux_notify.h",
"linux_desktop_settings.h",
"linux_session_monitor.h",
"wl_client_side_decorations.h",
"main_loop.h"
],
"protocols": [
"stable/xdg-shell/xdg-shell.xml",
"stable/viewporter/viewporter.xml",
"unstable/relative-pointer/relative-pointer-unstable-v1.xml",
"unstable/pointer-constraints/pointer-constraints-unstable-v1.xml",
"unstable/xdg-decoration/xdg-decoration-unstable-v1.xml",
"unstable/primary-selection/primary-selection-unstable-v1.xml",
"unstable/text-input/text-input-unstable-v3.xml",
"staging/xdg-activation/xdg-activation-v1.xml",
"unstable/tablet/tablet-unstable-v2.xml",
"staging/cursor-shape/cursor-shape-v1.xml",
"staging/fractional-scale/fractional-scale-v1.xml",
"staging/single-pixel-buffer/single-pixel-buffer-v1.xml",
"unstable/idle-inhibit/idle-inhibit-unstable-v1.xml",
"unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml",
"staging/xdg-toplevel-icon/xdg-toplevel-icon-v1.xml",
"staging/xdg-system-bell/xdg-system-bell-v1.xml",
"staging/xdg-toplevel-tag/xdg-toplevel-tag-v1.xml",
"staging/ext-background-effect/ext-background-effect-v1.xml",
"staging/xdg-toplevel-drag/xdg-toplevel-drag-v1.xml",
"unstable/pointer-gestures/pointer-gestures-unstable-v1.xml",
"unstable/xdg-output/xdg-output-unstable-v1.xml",
"kwin-blur-v1.xml",
"wlr-layer-shell-unstable-v1.xml",
"wlr-virtual-pointer-unstable-v1.xml",
"virtual-keyboard-unstable-v1.xml"
],
"sources": [
"wl_init.c",
"wl_monitor.c",
"wl_window.c",
"wl_cursors.c",
"wl_text_input.c",
"wl_client_side_decorations.c",
"posix_thread.c",
"xkb_glfw.c",
"dbus_glfw.c",
"ibus_glfw.c",
"egl_context.c",
"osmesa_context.c",
"backend_utils.c",
"linux_joystick.c",
"linux_desktop_settings.c",
"null_joystick.c",
"momentum-scroll.c",
"linux_notify.c",
"linux_session_monitor.c",
"wl_inject.c"
]
},
"wayland_protocols": [
1,
17
],
"win32": {
"headers": [
"win32_platform.h",
"win32_joystick.h",
"wgl_context.h",
"egl_context.h",
"osmesa_context.h"
],
"sources": [
"win32_init.c",
"win32_joystick.c",
"win32_monitor.c",
"win32_time.c",
"win32_thread.c",
"win32_window.c",
"wgl_context.c",
"egl_context.c",
"osmesa_context.c"
]
},
"x11": {
"headers": [
"x11_platform.h",
"xkb_glfw.h",
"dbus_glfw.h",
"ibus_glfw.h",
"backend_utils.h",
"posix_thread.h",
"glx_context.h",
"egl_context.h",
"osmesa_context.h",
"linux_joystick.h",
"null_joystick.h",
"linux_notify.h",
"linux_desktop_settings.h",
"linux_session_monitor.h",
"main_loop.h"
],
"sources": [
"x11_init.c",
"x11_monitor.c",
"x11_window.c",
"xkb_glfw.c",
"dbus_glfw.c",
"ibus_glfw.c",
"posix_thread.c",
"glx_context.c",
"egl_context.c",
"osmesa_context.c",
"backend_utils.c",
"linux_joystick.c",
"null_joystick.c",
"linux_desktop_settings.c",
"momentum-scroll.c",
"linux_notify.c",
"linux_session_monitor.c"
]
}
}
+94
View File
@@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="virtual_keyboard_unstable_v1">
<copyright>
Copyright © 2008 Kristian Høgsberg
Copyright © 2012 Collabora, Ltd.
Copyright © 2019 Andri Yngvason
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</copyright>
<interface name="zwp_virtual_keyboard_v1" version="1">
<description summary="virtual keyboard">
The virtual keyboard provides an application with requests which emulate
the behaviour of a physical keyboard.
</description>
<request name="keymap">
<description summary="keyboard mapping">
Provide a file descriptor to the compositor which can be
memory-mapped to provide a keyboard mapping description.
Format carries a value from the keymap_format enumeration.
</description>
<arg name="format" type="uint" summary="keymap format"/>
<arg name="fd" type="fd" summary="keymap file descriptor"/>
<arg name="size" type="uint" summary="keymap size, in bytes"/>
</request>
<request name="key">
<description summary="key event">
A key was pressed or released. The time argument is a timestamp with
millisecond granularity, with an undefined base. All requests regarding
a single object must share the same clock.
</description>
<arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
<arg name="key" type="uint" summary="key that produced the event"/>
<arg name="state" type="uint" summary="physical state of the key"/>
</request>
<request name="modifiers">
<description summary="modifier and group state">
Notifies the compositor that the modifier and/or group state has
changed, and it should update state.
</description>
<arg name="mods_depressed" type="uint" summary="depressed modifiers"/>
<arg name="mods_latched" type="uint" summary="latched modifiers"/>
<arg name="mods_locked" type="uint" summary="locked modifiers"/>
<arg name="group" type="uint" summary="keyboard layout"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy the virtual keyboard"/>
</request>
</interface>
<interface name="zwp_virtual_keyboard_manager_v1" version="1">
<description summary="virtual keyboard manager">
A manager that allows creating virtual keyboards.
</description>
<enum name="error">
<entry name="no_seat" value="0" summary="no seat was passed to create_virtual_keyboard"/>
</enum>
<request name="create_virtual_keyboard">
<description summary="create a new virtual keyboard">
Creates a new virtual keyboard associated to a seat.
</description>
<arg name="seat" type="object" interface="wl_seat" summary="the seat"/>
<arg name="id" type="new_id" interface="zwp_virtual_keyboard_v1"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy the virtual keyboard manager"/>
</request>
</interface>
</protocol>
+259
View File
@@ -0,0 +1,259 @@
//========================================================================
// GLFW 3.4 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2018 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// Please use C89 style variable declarations in this file because VS 2010
//========================================================================
#include "internal.h"
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#define _GLFW_FIND_LOADER 1
#define _GLFW_REQUIRE_LOADER 2
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
bool
_glfwInitVulkan(int mode) {
VkResult err;
VkExtensionProperties *ep;
uint32_t i, count;
if (_glfw.vk.available) return true;
#if !defined(_GLFW_VULKAN_STATIC)
#if defined(_GLFW_VULKAN_LIBRARY)
_glfw.vk.handle = _glfw_dlopen(_GLFW_VULKAN_LIBRARY);
#elif defined(_GLFW_WIN32)
_glfw.vk.handle = _glfw_dlopen("vulkan-1.dll");
#elif defined(_GLFW_COCOA)
_glfw.vk.handle = _glfw_dlopen("libvulkan.1.dylib");
if (!_glfw.vk.handle) _glfw.vk.handle = _glfwLoadLocalVulkanLoaderNS();
#else
_glfw.vk.handle = _glfw_dlopen("libvulkan.so.1");
#endif
if (!_glfw.vk.handle) {
if (mode == _GLFW_REQUIRE_LOADER) _glfwInputError(GLFW_API_UNAVAILABLE, "Vulkan: Loader not found");
return false;
}
*(void **)&_glfw.vk.GetInstanceProcAddr = _glfw_dlsym(_glfw.vk.handle, "vkGetInstanceProcAddr");
if (!_glfw.vk.GetInstanceProcAddr) {
_glfwInputError(GLFW_API_UNAVAILABLE, "Vulkan: Loader does not export vkGetInstanceProcAddr");
_glfwTerminateVulkan();
return false;
}
_glfw.vk.EnumerateInstanceExtensionProperties =
(PFN_vkEnumerateInstanceExtensionProperties)vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceExtensionProperties");
if (!_glfw.vk.EnumerateInstanceExtensionProperties) {
_glfwInputError(GLFW_API_UNAVAILABLE, "Vulkan: Failed to retrieve vkEnumerateInstanceExtensionProperties");
_glfwTerminateVulkan();
return false;
}
#endif // _GLFW_VULKAN_STATIC
err = vkEnumerateInstanceExtensionProperties(NULL, &count, NULL);
if (err) {
// NOTE: This happens on systems with a loader but without any Vulkan ICD
if (mode == _GLFW_REQUIRE_LOADER) {
_glfwInputError(GLFW_API_UNAVAILABLE, "Vulkan: Failed to query instance extension count: %s", _glfwGetVulkanResultString(err));
}
_glfwTerminateVulkan();
return false;
}
ep = calloc(count, sizeof(VkExtensionProperties));
err = vkEnumerateInstanceExtensionProperties(NULL, &count, ep);
if (err) {
_glfwInputError(GLFW_API_UNAVAILABLE, "Vulkan: Failed to query instance extensions: %s", _glfwGetVulkanResultString(err));
free(ep);
_glfwTerminateVulkan();
return false;
}
for (i = 0; i < count; i++) {
if (strcmp(ep[i].extensionName, "VK_KHR_surface") == 0) _glfw.vk.KHR_surface = true;
#if defined(_GLFW_WIN32)
else if (strcmp(ep[i].extensionName, "VK_KHR_win32_surface") == 0) _glfw.vk.KHR_win32_surface = true;
#elif defined(_GLFW_COCOA)
else if (strcmp(ep[i].extensionName, "VK_MVK_macos_surface") == 0) _glfw.vk.MVK_macos_surface = true;
else if (strcmp(ep[i].extensionName, "VK_EXT_metal_surface") == 0) _glfw.vk.EXT_metal_surface = true;
#elif defined(_GLFW_X11)
else if (strcmp(ep[i].extensionName, "VK_KHR_xlib_surface") == 0) _glfw.vk.KHR_xlib_surface = true;
else if (strcmp(ep[i].extensionName, "VK_KHR_xcb_surface") == 0) _glfw.vk.KHR_xcb_surface = true;
#elif defined(_GLFW_WAYLAND)
else if (strcmp(ep[i].extensionName, "VK_KHR_wayland_surface") == 0) _glfw.vk.KHR_wayland_surface = true;
#endif
}
free(ep);
_glfw.vk.available = true;
_glfwPlatformGetRequiredInstanceExtensions(_glfw.vk.extensions);
return true;
}
void
_glfwTerminateVulkan(void) {
#if !defined(_GLFW_VULKAN_STATIC)
if (_glfw.vk.handle) _glfw_dlclose(_glfw.vk.handle);
#endif
}
const char *
_glfwGetVulkanResultString(VkResult result) {
switch (result) {
case VK_SUCCESS: return "Success";
case VK_NOT_READY: return "A fence or query has not yet completed";
case VK_TIMEOUT: return "A wait operation has not completed in the specified time";
case VK_EVENT_SET: return "An event is signaled";
case VK_EVENT_RESET: return "An event is unsignaled";
case VK_INCOMPLETE: return "A return array was too small for the result";
case VK_ERROR_OUT_OF_HOST_MEMORY: return "A host memory allocation has failed";
case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "A device memory allocation has failed";
case VK_ERROR_INITIALIZATION_FAILED: return "Initialization of an object could not be completed for implementation-specific reasons";
case VK_ERROR_DEVICE_LOST: return "The logical or physical device has been lost";
case VK_ERROR_MEMORY_MAP_FAILED: return "Mapping of a memory object has failed";
case VK_ERROR_LAYER_NOT_PRESENT: return "A requested layer is not present or could not be loaded";
case VK_ERROR_EXTENSION_NOT_PRESENT: return "A requested extension is not supported";
case VK_ERROR_FEATURE_NOT_PRESENT: return "A requested feature is not supported";
case VK_ERROR_INCOMPATIBLE_DRIVER: return "The requested version of Vulkan is not supported by the driver or is otherwise incompatible";
case VK_ERROR_TOO_MANY_OBJECTS: return "Too many objects of the type have already been created";
case VK_ERROR_FORMAT_NOT_SUPPORTED: return "A requested format is not supported on this device";
case VK_ERROR_SURFACE_LOST_KHR: return "A surface is no longer available";
case VK_SUBOPTIMAL_KHR: return "A swapchain no longer matches the surface properties exactly, but can still be used";
case VK_ERROR_OUT_OF_DATE_KHR: return "A surface has changed in such a way that it is no longer compatible with the swapchain";
case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "The display used by a swapchain does not use the same presentable image layout";
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "The requested window is already connected to a VkSurfaceKHR, or to some other non-Vulkan API";
case VK_ERROR_VALIDATION_FAILED_EXT: return "A validation layer found an error";
default: return "ERROR: UNKNOWN VULKAN ERROR";
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW public API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI int
glfwVulkanSupported(void) {
_GLFW_REQUIRE_INIT_OR_RETURN(false);
return _glfwInitVulkan(_GLFW_FIND_LOADER);
}
GLFWAPI const char **
glfwGetRequiredInstanceExtensions(uint32_t *count) {
assert(count != NULL);
*count = 0;
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
if (!_glfwInitVulkan(_GLFW_REQUIRE_LOADER)) return NULL;
if (!_glfw.vk.extensions[0]) return NULL;
*count = 2;
return (const char **)_glfw.vk.extensions;
}
GLFWAPI GLFWvkproc
glfwGetInstanceProcAddress(VkInstance instance, const char *procname) {
GLFWvkproc proc;
assert(procname != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
if (!_glfwInitVulkan(_GLFW_REQUIRE_LOADER)) return NULL;
proc = (GLFWvkproc)vkGetInstanceProcAddr(instance, procname);
#if defined(_GLFW_VULKAN_STATIC)
if (!proc) {
if (strcmp(procname, "vkGetInstanceProcAddr") == 0) return (GLFWvkproc)vkGetInstanceProcAddr;
}
#else
if (!proc) *(void **)&proc = _glfw_dlsym(_glfw.vk.handle, procname);
#endif
return proc;
}
GLFWAPI int
glfwGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice device, uint32_t queuefamily) {
assert(instance != VK_NULL_HANDLE);
assert(device != VK_NULL_HANDLE);
_GLFW_REQUIRE_INIT_OR_RETURN(false);
if (!_glfwInitVulkan(_GLFW_REQUIRE_LOADER)) return false;
if (!_glfw.vk.extensions[0]) {
_glfwInputError(GLFW_API_UNAVAILABLE, "Vulkan: Window surface creation extensions not found");
return false;
}
return _glfwPlatformGetPhysicalDevicePresentationSupport(instance, device, queuefamily);
}
GLFWAPI VkResult
glfwCreateWindowSurface(VkInstance instance, GLFWwindow *handle, const VkAllocationCallbacks *allocator, VkSurfaceKHR *surface) {
_GLFWwindow *window = (_GLFWwindow *)handle;
assert(instance != VK_NULL_HANDLE);
assert(window != NULL);
assert(surface != NULL);
*surface = VK_NULL_HANDLE;
_GLFW_REQUIRE_INIT_OR_RETURN(VK_ERROR_INITIALIZATION_FAILED);
if (!_glfwInitVulkan(_GLFW_REQUIRE_LOADER)) return VK_ERROR_INITIALIZATION_FAILED;
if (!_glfw.vk.extensions[0]) {
_glfwInputError(GLFW_API_UNAVAILABLE, "Vulkan: Window surface creation extensions not found");
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
if (window->context.client != GLFW_NO_API) {
_glfwInputError(GLFW_INVALID_VALUE, "Vulkan: Window surface creation requires the window to have the client API set to GLFW_NO_API");
return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
}
return _glfwPlatformCreateWindowSurface(instance, window, allocator, surface);
}
+1019
View File
File diff suppressed because it is too large. Load diff
+1077
View File
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "internal.h"
void csd_initialize_metrics(_GLFWwindow *window);
void csd_free_all_resources(_GLFWwindow *window);
bool csd_change_title(_GLFWwindow *window);
void csd_set_window_geometry(_GLFWwindow *window, int32_t *width, int32_t *height);
bool csd_set_titlebar_color(_GLFWwindow *window, uint32_t color, bool use_system_color);
bool csd_should_window_be_decorated(_GLFWwindow *window);
void csd_set_visible(_GLFWwindow *window, bool visible);
void csd_handle_pointer_event(_GLFWwindow *window, int button, int state, struct wl_surface *surface);
+58
View File
@@ -0,0 +1,58 @@
// Future devs supporting whatever Wayland protocol stabilizes for cursor selection: see _themeAdd.
#include "internal.h"
#include "linux_desktop_settings.h"
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
static GLFWWLCursorThemes cursor_themes;
static int
pixels_from_scale(int scale) {
int factor;
const char *name;
glfw_current_cursor_theme(&name, &factor);
return factor * scale;
}
struct wl_cursor_theme *
glfw_wlc_theme_for_scale(int scale) {
for (size_t i = 0; i < cursor_themes.count; i++) {
if (cursor_themes.themes[i].scale == scale) return cursor_themes.themes[i].theme;
}
if (cursor_themes.count >= cursor_themes.capacity) {
cursor_themes.themes = realloc(cursor_themes.themes, sizeof(GLFWWLCursorTheme) * (cursor_themes.count + 16));
if (!cursor_themes.themes) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Wayland: Out of memory allocating space for cursor themes");
return NULL;
}
cursor_themes.capacity = cursor_themes.count + 16;
}
int factor;
const char *name;
glfw_current_cursor_theme(&name, &factor);
struct wl_cursor_theme *ans = wl_cursor_theme_load(name, pixels_from_scale(scale), _glfw.wl.shm);
if (!ans) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Wayland: wl_cursor_theme_load failed at scale: %d pixels: %d", scale, pixels_from_scale(scale));
return NULL;
}
GLFWWLCursorTheme *theme = cursor_themes.themes + cursor_themes.count++;
theme->scale = scale;
theme->theme = ans;
return ans;
}
void
glfw_wlc_destroy(void) {
for (size_t i = 0; i < cursor_themes.count; i++) { wl_cursor_theme_destroy(cursor_themes.themes[i].theme); }
free(cursor_themes.themes);
cursor_themes.themes = NULL;
cursor_themes.capacity = 0;
cursor_themes.count = 0;
}
+18
View File
@@ -0,0 +1,18 @@
// Declarations for a HiDPI-aware cursor theme manager.
#include <wayland-cursor.h>
typedef struct {
struct wl_cursor_theme *theme;
int scale;
} GLFWWLCursorTheme;
typedef struct {
GLFWWLCursorTheme *themes;
size_t count, capacity;
} GLFWWLCursorThemes;
struct wl_cursor_theme *glfw_wlc_theme_for_scale(int scale);
void glfw_wlc_destroy(void);
+1207
View File
File diff suppressed because it is too large. Load diff
+168
View File
@@ -0,0 +1,168 @@
/*
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
// Virtual pointer and keyboard injection for the Wayland backend.
// Uses zwlr_virtual_pointer_v1 and zwp_virtual_keyboard_v1.
#define _GNU_SOURCE
#include "internal.h"
#include <stdlib.h>
#include "xkb_glfw.h"
#include "memfd.h"
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <linux/input-event-codes.h>
GLFWAPI bool
glfwWaylandCreateVirtualDevices(void) {
if (_glfw.wl.virtual_pointer_manager && _glfw.wl.seat)
_glfw.wl.virtual_pointer = zwlr_virtual_pointer_manager_v1_create_virtual_pointer(_glfw.wl.virtual_pointer_manager, _glfw.wl.seat);
if (_glfw.wl.virtual_keyboard_manager && _glfw.wl.seat)
_glfw.wl.virtual_keyboard = zwp_virtual_keyboard_manager_v1_create_virtual_keyboard(_glfw.wl.virtual_keyboard_manager, _glfw.wl.seat);
if (_glfw.wl.virtual_pointer || _glfw.wl.virtual_keyboard) {
// Two roundtrips: first ensures the compositor has processed the creation
// requests, second gives wlroots time to advertise the updated seat
// capabilities (pointer/keyboard) to any client that connects next.
wl_display_roundtrip(_glfw.wl.display);
wl_display_roundtrip(_glfw.wl.display);
}
return _glfw.wl.virtual_pointer != NULL;
}
static uint32_t
ms_now(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint32_t)(ts.tv_sec * 1000u + ts.tv_nsec / 1000000u);
}
static uint32_t
glfw_button_to_evdev(int button) {
switch (button) {
case GLFW_MOUSE_BUTTON_LEFT: return BTN_LEFT;
case GLFW_MOUSE_BUTTON_RIGHT: return BTN_RIGHT;
case GLFW_MOUSE_BUTTON_MIDDLE: return BTN_MIDDLE;
case 3: return BTN_SIDE;
case 4: return BTN_EXTRA;
case 5: return BTN_FORWARD;
case 6: return BTN_BACK;
case 7: return BTN_TASK;
default: return BTN_LEFT;
}
}
GLFWAPI void
glfwWaylandInjectMouseMotionAbsolute(uint32_t x, uint32_t y, uint32_t x_extent, uint32_t y_extent) {
if (!_glfw.wl.virtual_pointer) return;
zwlr_virtual_pointer_v1_motion_absolute(_glfw.wl.virtual_pointer, ms_now(), x, y, x_extent, y_extent);
zwlr_virtual_pointer_v1_frame(_glfw.wl.virtual_pointer);
wl_display_flush(_glfw.wl.display);
}
GLFWAPI void
glfwWaylandInjectMouseButton(int button, int action) {
if (!_glfw.wl.virtual_pointer) return;
uint32_t state = (action == GLFW_PRESS) ? 1u : 0u;
zwlr_virtual_pointer_v1_button(_glfw.wl.virtual_pointer, ms_now(), glfw_button_to_evdev(button), state);
zwlr_virtual_pointer_v1_frame(_glfw.wl.virtual_pointer);
wl_display_flush(_glfw.wl.display);
}
// --- keyboard injection ---
typedef struct {
xkb_keysym_t target;
uint32_t scancode; // evdev scancode = XKB keycode - 8; 0 means not found
} KeySearch;
static void
search_keymap_for_sym(struct xkb_keymap *keymap, xkb_keycode_t keycode, void *data) {
KeySearch *s = data;
if (s->scancode) return;
const xkb_keysym_t *syms;
int n = xkb_keymap_key_get_syms_by_level(keymap, keycode, 0, 0, &syms);
for (int i = 0; i < n; i++) {
if (syms[i] == s->target) {
s->scancode = keycode - 8;
return;
}
}
}
static bool keymap_sent = false;
static void
ensure_keymap_sent(void) {
if (keymap_sent || !_glfw.wl.virtual_keyboard) return;
struct xkb_keymap *km = _glfw.wl.xkb.keymap ? _glfw.wl.xkb.keymap : _glfw.wl.xkb.default_keymap;
if (!km) return;
char *str = xkb_keymap_get_as_string(km, XKB_KEYMAP_FORMAT_TEXT_V1);
if (!str) return;
size_t len = strlen(str) + 1;
#ifdef HAS_MEMFD_CREATE
int fd = glfw_memfd_create("vk-keymap", MFD_CLOEXEC);
#else
char template[] = "/tmp/.vk-keymap-XXXXXX";
int fd = createTmpfileCloexec(template);
#endif
if (fd >= 0 && (size_t)write(fd, str, len) == len) {
zwp_virtual_keyboard_v1_keymap(_glfw.wl.virtual_keyboard, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, fd, (uint32_t)len);
keymap_sent = true;
}
free(str);
if (fd >= 0) close(fd);
}
GLFWAPI void
glfwWaylandInjectKey(int key, int action, int mods) {
if (!_glfw.wl.virtual_keyboard) return;
ensure_keymap_sent();
if (!keymap_sent) return;
struct xkb_keymap *km = _glfw.wl.xkb.keymap ? _glfw.wl.xkb.keymap : _glfw.wl.xkb.default_keymap;
if (!km) return;
xkb_keysym_t sym;
if ((uint32_t)key >= GLFW_FKEY_FIRST) {
sym = glfw_xkb_sym_for_key((uint32_t)key);
if (sym == XKB_KEY_NoSymbol) return;
} else {
sym = xkb_utf32_to_keysym((uint32_t)key);
if (sym == XKB_KEY_NoSymbol) return;
}
KeySearch search = {.target = sym, .scancode = 0};
xkb_keymap_key_for_each(km, search_keymap_for_sym, &search);
if (!search.scancode) return;
uint32_t depressed = 0;
if (mods & GLFW_MOD_SHIFT) {
xkb_mod_index_t idx = xkb_keymap_mod_get_index(km, XKB_MOD_NAME_SHIFT);
if (idx != XKB_MOD_INVALID) depressed |= (1u << idx);
}
if (mods & GLFW_MOD_CONTROL) {
xkb_mod_index_t idx = xkb_keymap_mod_get_index(km, XKB_MOD_NAME_CTRL);
if (idx != XKB_MOD_INVALID) depressed |= (1u << idx);
}
if (mods & GLFW_MOD_ALT) {
xkb_mod_index_t idx = xkb_keymap_mod_get_index(km, XKB_MOD_NAME_ALT);
if (idx != XKB_MOD_INVALID) depressed |= (1u << idx);
}
if (mods & GLFW_MOD_SUPER) {
xkb_mod_index_t idx = xkb_keymap_mod_get_index(km, XKB_MOD_NAME_LOGO);
if (idx != XKB_MOD_INVALID) depressed |= (1u << idx);
}
zwp_virtual_keyboard_v1_modifiers(_glfw.wl.virtual_keyboard, depressed, 0, 0, 0);
uint32_t state = (action != GLFW_RELEASE) ? 1u : 0u;
zwp_virtual_keyboard_v1_key(_glfw.wl.virtual_keyboard, ms_now(), search.scancode, state);
wl_display_flush(_glfw.wl.display);
}
GLFWAPI void
glfwWaylandInjectCleanup(void) {
keymap_sent = false;
}
+347
View File
@@ -0,0 +1,347 @@
//========================================================================
// GLFW 3.4 Wayland - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2014 Jonas Ådahl <jadahl@gmail.com>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
static void
outputHandleGeometry(
void *data,
struct wl_output *output UNUSED,
int32_t x,
int32_t y,
int32_t physicalWidth,
int32_t physicalHeight,
int32_t subpixel UNUSED,
const char *make UNUSED,
const char *model UNUSED,
int32_t transform) {
struct _GLFWmonitor *monitor = data;
monitor->wl.x = x;
monitor->wl.y = y;
monitor->widthMM = physicalWidth;
monitor->heightMM = physicalHeight;
monitor->wl.transform = transform;
}
static void
outputHandleMode(void *data, struct wl_output *output UNUSED, uint32_t flags, int32_t width, int32_t height, int32_t refresh) {
struct _GLFWmonitor *monitor = data;
GLFWvidmode mode;
mode.width = width;
mode.height = height;
mode.redBits = 8;
mode.greenBits = 8;
mode.blueBits = 8;
mode.refreshRate = (int)round(refresh / 1000.0);
monitor->modeCount++;
monitor->modes = realloc(monitor->modes, monitor->modeCount * sizeof(GLFWvidmode));
monitor->modes[monitor->modeCount - 1] = mode;
if (flags & WL_OUTPUT_MODE_CURRENT) monitor->wl.currentMode = monitor->modeCount - 1;
}
static void
outputHandleDone(void *data, struct wl_output *output UNUSED) {
struct _GLFWmonitor *monitor = data;
for (int i = 0; i < _glfw.monitorCount; i++) {
if (_glfw.monitors[i] == monitor) return;
}
_glfwInputMonitor(monitor, GLFW_CONNECTED, _GLFW_INSERT_LAST);
}
static void
outputHandleScale(void *data, struct wl_output *output UNUSED, int32_t factor) {
struct _GLFWmonitor *monitor = data;
if (factor > 0 && factor < 24) monitor->wl.scale = factor;
}
static void
outputHandleName(void *data, struct wl_output *output UNUSED, const char *name) {
struct _GLFWmonitor *monitor = data;
if (name) {
if (monitor->name) free((void *)monitor->name);
monitor->name = _glfw_strdup(name);
}
}
static void
outputHandleDescription(void *data, struct wl_output *output UNUSED, const char *description) {
struct _GLFWmonitor *monitor = data;
if (description) {
if (monitor->description) free((void *)monitor->description);
monitor->description = _glfw_strdup(description);
}
}
static const struct wl_output_listener outputListener = {
outputHandleGeometry,
outputHandleMode,
outputHandleDone,
outputHandleScale,
outputHandleName,
outputHandleDescription,
};
static void
xdgOutputHandleLogicalPosition(void *data, struct zxdg_output_v1 *xdg_output UNUSED, int32_t x, int32_t y) {
struct _GLFWmonitor *monitor = data;
monitor->wl.x = x;
monitor->wl.y = y;
monitor->wl.xdg_position_received = true;
}
static void
xdgOutputHandleLogicalSize(void *data, struct zxdg_output_v1 *xdg_output UNUSED, int32_t width, int32_t height) {
struct _GLFWmonitor *monitor = data;
monitor->wl.xdg_logical_width = width;
monitor->wl.xdg_logical_height = height;
monitor->wl.xdg_size_received = true;
}
static void
computeXdgFractionalScale(struct _GLFWmonitor *monitor) {
if (monitor->wl.xdg_logical_width <= 0 || monitor->wl.xdg_logical_height <= 0) return;
if (monitor->modeCount == 0 || monitor->wl.currentMode < 0) return;
GLFWvidmode *mode = &monitor->modes[monitor->wl.currentMode];
if (mode->width <= 0 || mode->height <= 0) return;
// For 90° and 270° rotations the compositor maps physical width↔height,
// so use the swapped axis when dividing by the logical size.
int phys_w = mode->width, phys_h = mode->height;
int32_t t = monitor->wl.transform;
if (t == WL_OUTPUT_TRANSFORM_90 || t == WL_OUTPUT_TRANSFORM_270 || t == WL_OUTPUT_TRANSFORM_FLIPPED_90 || t == WL_OUTPUT_TRANSFORM_FLIPPED_270) {
int tmp = phys_w;
phys_w = phys_h;
phys_h = tmp;
}
double sx = (double)phys_w / monitor->wl.xdg_logical_width;
double sy = (double)phys_h / monitor->wl.xdg_logical_height;
// Use the average in case of minor rounding differences between axes.
monitor->wl.fractional_scale = (sx + sy) * 0.5;
}
static void
xdgOutputHandleDone(void *data, struct zxdg_output_v1 *xdg_output UNUSED) {
struct _GLFWmonitor *monitor = data;
computeXdgFractionalScale(monitor);
}
static void
xdgOutputHandleName(void *data, struct zxdg_output_v1 *xdg_output UNUSED, const char *name) {
// wl_output already provides the name; skip to avoid duplicate frees.
(void)data;
(void)name;
}
static void
xdgOutputHandleDescription(void *data, struct zxdg_output_v1 *xdg_output UNUSED, const char *description) {
(void)data;
(void)description;
}
static const struct zxdg_output_v1_listener xdgOutputListener = {
xdgOutputHandleLogicalPosition,
xdgOutputHandleLogicalSize,
xdgOutputHandleDone,
xdgOutputHandleName,
xdgOutputHandleDescription,
};
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
void
_glfwCreateXdgOutputWayland(_GLFWmonitor *monitor) {
if (!_glfw.wl.xdg_output_manager || monitor->wl.xdg_output) return;
monitor->wl.xdg_output = zxdg_output_manager_v1_get_xdg_output(_glfw.wl.xdg_output_manager, monitor->wl.output);
if (monitor->wl.xdg_output) zxdg_output_v1_add_listener(monitor->wl.xdg_output, &xdgOutputListener, monitor);
}
void
_glfwAddOutputWayland(uint32_t name, uint32_t version) {
_GLFWmonitor *monitor;
struct wl_output *output;
if (version < 2) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Wayland: Unsupported output interface version");
return;
}
// The actual name of this output will be set in the handlers.
monitor = _glfwAllocMonitor("unnamed", 0, 0);
output = wl_registry_bind(_glfw.wl.registry, name, &wl_output_interface, MIN(version, (unsigned)WL_OUTPUT_NAME_SINCE_VERSION));
if (!output) {
_glfwFreeMonitor(monitor);
return;
}
monitor->wl.scale = 1;
monitor->wl.output = output;
monitor->wl.name = name;
wl_output_add_listener(output, &outputListener, monitor);
_glfwCreateXdgOutputWayland(monitor);
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
void
_glfwPlatformFreeMonitor(_GLFWmonitor *monitor) {
if (monitor->wl.xdg_output) zxdg_output_v1_destroy(monitor->wl.xdg_output);
if (monitor->wl.output) wl_output_destroy(monitor->wl.output);
}
void
_glfwPlatformGetMonitorPos(_GLFWmonitor *monitor, int *xpos, int *ypos) {
if (xpos) *xpos = monitor->wl.x;
if (ypos) *ypos = monitor->wl.y;
}
void
_glfwPlatformGetMonitorContentScale(_GLFWmonitor *monitor, float *xscale, float *yscale) {
float scale = monitor->wl.fractional_scale > 0.0 ? (float)monitor->wl.fractional_scale : (float)monitor->wl.scale;
if (xscale) *xscale = scale;
if (yscale) *yscale = scale;
}
void
_glfwPlatformGetMonitorWorkarea(_GLFWmonitor *monitor, int *xpos, int *ypos, int *width, int *height) {
if (xpos) *xpos = monitor->wl.x;
if (ypos) *ypos = monitor->wl.y;
if (width) *width = monitor->modes[monitor->wl.currentMode].width;
if (height) *height = monitor->modes[monitor->wl.currentMode].height;
}
GLFWvidmode *
_glfwPlatformGetVideoModes(_GLFWmonitor *monitor, int *found) {
*found = monitor->modeCount;
return monitor->modes;
}
bool
_glfwPlatformGetVideoMode(_GLFWmonitor *monitor, GLFWvidmode *mode) {
if (monitor->modeCount > monitor->wl.currentMode) {
*mode = monitor->modes[monitor->wl.currentMode];
return true;
}
return false;
}
bool
_glfwPlatformGetGammaRamp(_GLFWmonitor *monitor UNUSED, GLFWgammaramp *ramp UNUSED) {
_glfwInputError(GLFW_FEATURE_UNAVAILABLE, "Wayland: Gamma ramp access is not available");
return false;
}
void
_glfwPlatformSetGammaRamp(_GLFWmonitor *monitor UNUSED, const GLFWgammaramp *ramp UNUSED) {
_glfwInputError(GLFW_FEATURE_UNAVAILABLE, "Wayland: Gamma ramp access is not available");
}
//////////////////////////////////////////////////////////////////////////
////// GLFW native API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI struct wl_output *
glfwGetWaylandMonitor(GLFWmonitor *handle) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
return monitor->wl.output;
}
GLFWAPI double
glfwGetWaylandCurrentMonitorFractionalScale(void) {
_GLFW_REQUIRE_INIT_OR_RETURN(1.0);
if (!_glfw.wl.xdg_output_manager || _glfw.monitorCount == 0) return 1.0;
// Use the monitor of the currently focused window, then the most recently
// focused window, then fall back to the primary monitor.
_GLFWmonitor *monitor = NULL;
GLFWid focus_ids[2] = {_glfw.wl.keyboardFocusId, _glfw.wl.lastKeyboardFocusId};
for (int i = 0; i < 2 && !monitor; i++) {
if (!focus_ids[i]) continue;
_GLFWwindow *window = _glfwWindowForId(focus_ids[i]);
if (window && window->wl.monitorsCount > 0) monitor = window->wl.monitors[0];
}
if (!monitor) {
// No focused window to key off of (typically the first window at
// startup). Prefer the output at the logical origin (0, 0): the
// compositor's top-left/primary output is a better guess for where a
// new window will be placed than registry order. Fall back to the
// first output if no output reports position (0, 0).
//
// xdg_output geometry arrives asynchronously and x/y remain zero until
// it does, so wait for every monitor's logical geometry before trusting
// the reported positions (otherwise an as-yet-unpositioned output would
// spuriously match (0, 0)).
for (int i = 0; i < _glfw.monitorCount; i++) {
_GLFWmonitor *m = _glfw.monitors[i];
while (m->wl.xdg_output && !(m->wl.xdg_size_received && m->wl.xdg_position_received)) {
if (wl_display_roundtrip(_glfw.wl.display) < 0) break;
}
}
for (int i = 0; i < _glfw.monitorCount; i++) {
_GLFWmonitor *m = _glfw.monitors[i];
if (m->wl.xdg_output && m->wl.xdg_size_received && m->wl.xdg_position_received && m->wl.x == 0 && m->wl.y == 0) {
monitor = m;
break;
}
}
if (!monitor) monitor = _glfw.monitors[0];
}
if (!monitor->wl.xdg_output) return monitor->wl.scale > 0 ? (double)monitor->wl.scale : 1.0;
// Block until the compositor has delivered xdg_output logical size and position.
while (!(monitor->wl.xdg_size_received && monitor->wl.xdg_position_received)) {
if (wl_display_roundtrip(_glfw.wl.display) < 0) break;
}
if (monitor->wl.fractional_scale <= 0.0) computeXdgFractionalScale(monitor);
return monitor->wl.fractional_scale > 0.0 ? monitor->wl.fractional_scale : (monitor->wl.scale > 0 ? (double)monitor->wl.scale : 1.0);
}
+560
View File
@@ -0,0 +1,560 @@
//========================================================================
// GLFW 3.4 Wayland - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2014 Jonas Ådahl <jadahl@gmail.com>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <wayland-client.h>
#include <dlfcn.h>
#include <poll.h>
typedef VkFlags VkWaylandSurfaceCreateFlagsKHR;
typedef struct VkWaylandSurfaceCreateInfoKHR {
VkStructureType sType;
const void *pNext;
VkWaylandSurfaceCreateFlagsKHR flags;
struct wl_display *display;
struct wl_surface *surface;
} VkWaylandSurfaceCreateInfoKHR;
typedef VkResult(APIENTRY *PFN_vkCreateWaylandSurfaceKHR)(VkInstance, const VkWaylandSurfaceCreateInfoKHR *, const VkAllocationCallbacks *, VkSurfaceKHR *);
typedef VkBool32(APIENTRY *PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR)(VkPhysicalDevice, uint32_t, struct wl_display *);
#include "posix_thread.h"
#ifdef __linux__
#include "linux_joystick.h"
#else
#include "null_joystick.h"
#endif
#include "backend_utils.h"
#include "xkb_glfw.h"
#include "wl_cursors.h"
#include "wayland-xdg-shell-client-protocol.h"
#include "wayland-xdg-decoration-unstable-v1-client-protocol.h"
#include "wayland-relative-pointer-unstable-v1-client-protocol.h"
#include "wayland-pointer-constraints-unstable-v1-client-protocol.h"
#include "wayland-primary-selection-unstable-v1-client-protocol.h"
#include "wayland-primary-selection-unstable-v1-client-protocol.h"
#include "wayland-xdg-activation-v1-client-protocol.h"
#include "wayland-cursor-shape-v1-client-protocol.h"
#include "wayland-fractional-scale-v1-client-protocol.h"
#include "wayland-viewporter-client-protocol.h"
#include "wayland-kwin-blur-v1-client-protocol.h"
#include "wayland-ext-background-effect-v1-client-protocol.h"
#include "wayland-wlr-layer-shell-unstable-v1-client-protocol.h"
#include "wayland-single-pixel-buffer-v1-client-protocol.h"
#include "wayland-idle-inhibit-unstable-v1-client-protocol.h"
#include "wayland-keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h"
#include "wayland-xdg-toplevel-icon-v1-client-protocol.h"
#include "wayland-xdg-system-bell-v1-client-protocol.h"
#include "wayland-xdg-toplevel-tag-v1-client-protocol.h"
#include "wayland-xdg-toplevel-drag-v1-client-protocol.h"
#include "wayland-xdg-output-unstable-v1-client-protocol.h"
#include "wayland-wlr-virtual-pointer-unstable-v1-client-protocol.h"
#include "wayland-virtual-keyboard-unstable-v1-client-protocol.h"
#define _glfw_dlopen(name) dlopen(name, RTLD_LAZY | RTLD_LOCAL)
#define _glfw_dlclose(handle) dlclose(handle)
#define _glfw_dlsym(handle, name) dlsym(handle, name)
#define _GLFW_PLATFORM_WINDOW_STATE _GLFWwindowWayland wl
#define _GLFW_PLATFORM_LIBRARY_WINDOW_STATE _GLFWlibraryWayland wl
#define _GLFW_PLATFORM_MONITOR_STATE _GLFWmonitorWayland wl
#define _GLFW_PLATFORM_CURSOR_STATE _GLFWcursorWayland wl
#define _GLFW_PLATFORM_CONTEXT_STATE
#define _GLFW_PLATFORM_LIBRARY_CONTEXT_STATE
typedef struct wl_cursor_theme *(*PFN_wl_cursor_theme_load)(const char *, int, struct wl_shm *);
typedef void (*PFN_wl_cursor_theme_destroy)(struct wl_cursor_theme *);
typedef struct wl_cursor *(*PFN_wl_cursor_theme_get_cursor)(struct wl_cursor_theme *, const char *);
typedef struct wl_buffer *(*PFN_wl_cursor_image_get_buffer)(struct wl_cursor_image *);
#define wl_cursor_theme_load _glfw.wl.cursor.theme_load
#define wl_cursor_theme_destroy _glfw.wl.cursor.theme_destroy
#define wl_cursor_theme_get_cursor _glfw.wl.cursor.theme_get_cursor
#define wl_cursor_image_get_buffer _glfw.wl.cursor.image_get_buffer
typedef struct wl_egl_window *(*PFN_wl_egl_window_create)(struct wl_surface *, int, int);
typedef void (*PFN_wl_egl_window_destroy)(struct wl_egl_window *);
typedef void (*PFN_wl_egl_window_resize)(struct wl_egl_window *, int, int, int, int);
#define wl_egl_window_create _glfw.wl.egl.window_create
#define wl_egl_window_destroy _glfw.wl.egl.window_destroy
#define wl_egl_window_resize _glfw.wl.egl.window_resize
typedef enum _GLFWCSDSurface {
CENTRAL_WINDOW,
CSD_titlebar,
CSD_shadow_top,
CSD_shadow_left,
CSD_shadow_bottom,
CSD_shadow_right,
CSD_shadow_upper_left,
CSD_shadow_upper_right,
CSD_shadow_lower_left,
CSD_shadow_lower_right,
} _GLFWCSDSurface;
typedef struct _GLFWWaylandBufferPair {
struct wl_buffer *a, *b, *front, *back;
struct {
uint8_t *a, *b, *front, *back;
} data;
// The back buffer could not be rendered into as it was busy
bool has_pending_update;
size_t size_in_bytes, width, height, viewport_width, viewport_height, stride;
// Busy means attached to a surface and not yet released by the compositor
bool a_busy, b_busy;
} _GLFWWaylandBufferPair;
typedef struct _GLFWWaylandCSDSurface {
struct wl_surface *surface;
struct wl_subsurface *subsurface;
struct wp_viewport *wp_viewport;
_GLFWWaylandBufferPair buffer;
int x, y;
} _GLFWWaylandCSDSurface;
typedef enum WaylandWindowState {
TOPLEVEL_STATE_NONE = 0,
TOPLEVEL_STATE_MAXIMIZED = 1,
TOPLEVEL_STATE_FULLSCREEN = 2,
TOPLEVEL_STATE_RESIZING = 4,
TOPLEVEL_STATE_ACTIVATED = 8,
TOPLEVEL_STATE_TILED_LEFT = 16,
TOPLEVEL_STATE_TILED_RIGHT = 32,
TOPLEVEL_STATE_TILED_TOP = 64,
TOPLEVEL_STATE_TILED_BOTTOM = 128,
TOPLEVEL_STATE_SUSPENDED = 256,
TOPLEVEL_STATE_CONSTRAINED_LEFT = 512,
TOPLEVEL_STATE_CONSTRAINED_RIGHT = 1024,
TOPLEVEL_STATE_CONSTRAINED_TOP = 2048,
TOPLEVEL_STATE_CONSTRAINED_BOTTOM = 4096,
} WaylandWindowState;
typedef struct glfw_wl_xdg_activation_request {
GLFWid window_id;
GLFWactivationcallback callback;
void *callback_data;
uintptr_t request_id;
void *token;
} glfw_wl_xdg_activation_request;
static const WaylandWindowState TOPLEVEL_STATE_DOCKED = TOPLEVEL_STATE_MAXIMIZED | TOPLEVEL_STATE_FULLSCREEN | TOPLEVEL_STATE_TILED_TOP |
TOPLEVEL_STATE_TILED_LEFT | TOPLEVEL_STATE_TILED_RIGHT | TOPLEVEL_STATE_TILED_BOTTOM;
enum WaylandWindowPendingState { PENDING_STATE_TOPLEVEL = 1, PENDING_STATE_DECORATION = 2 };
enum _GLFWWaylandAxisEvent { AXIS_EVENT_UNKNOWN = 0, AXIS_EVENT_CONTINUOUS = 1, AXIS_EVENT_DISCRETE = 2, AXIS_EVENT_VALUE120 = 3 };
// Wayland-specific per-window data
//
typedef struct _GLFWwindowWayland {
int width, height;
bool visible, created;
bool hovered;
bool transparent;
struct wl_surface *surface;
bool waiting_for_swap_to_commit;
struct wl_egl_window *native;
struct wl_callback *callback;
struct {
struct xdg_surface *surface;
struct xdg_toplevel *toplevel;
struct zxdg_toplevel_decoration_v1 *decoration;
struct {
int width, height;
} top_level_bounds;
} xdg;
struct wp_fractional_scale_v1 *wp_fractional_scale_v1;
struct wp_viewport *wp_viewport;
struct org_kde_kwin_blur *org_kde_kwin_blur;
struct ext_background_effect_surface_v1 *ext_background_effect_surface_v1;
bool has_blur, expect_scale_from_compositor, window_fully_created;
struct {
bool surface_configured, preferred_scale_received, fractional_scale_received;
} once;
struct wl_buffer *temp_buffer_used_during_window_creation;
struct {
GLFWLayerShellConfig config;
struct zwlr_layer_surface_v1 *zwlr_layer_surface_v1;
} layer_shell;
/* information about axis events on current frame */
struct {
struct {
enum _GLFWWaylandAxisEvent x_axis_type;
float x;
enum _GLFWWaylandAxisEvent y_axis_type;
float y;
} discrete, continuous;
/* Event timestamp in nanoseconds */
bool x_stop_received, y_stop_received;
uint32_t source_type;
monotonic_t x_start_time, x_stop_time, y_stop_time, y_start_time;
} pointer_curr_axis_info;
GLFWOffsetType prev_frame_offset_type;
_GLFWcursor *currentCursor;
double cursorPosX, cursorPosY, allCursorPosX, allCursorPosY;
char *title;
char appId[256], windowTag[256];
// We need to track the monitors the window spans on to calculate the
// optimal scaling factor.
struct {
uint32_t deduced, preferred;
} integer_scale;
uint32_t fractional_scale;
bool initial_scale_notified;
_GLFWmonitor **monitors;
int monitorsCount;
int monitorsSize;
struct {
struct zwp_relative_pointer_v1 *relativePointer;
struct zwp_locked_pointer_v1 *lockedPointer;
} pointerLock;
struct {
int pressed_button; // a GLFWTitlebarButton
bool serverSide, titlebar_needs_update, dragging, titlebar_hidden;
_GLFWCSDSurface focus;
_GLFWWaylandCSDSurface titlebar, shadow_left, shadow_right, shadow_top, shadow_bottom, shadow_upper_left, shadow_upper_right, shadow_lower_left,
shadow_lower_right;
struct {
uint8_t *data;
size_t size;
} mapping;
struct {
int width, height;
bool focused;
double fscale;
WaylandWindowState toplevel_states;
} for_window_state;
struct {
unsigned int width, top, horizontal, vertical, visible_titlebar_height;
} metrics;
struct {
int32_t x, y, width, height;
} geometry;
struct {
bool hovered;
int width, left;
} minimize, maximize, close;
struct {
uint32_t *data;
size_t for_decoration_size, stride, segments, corner_size;
} shadow_tile;
monotonic_t last_click_on_top_decoration_at;
uint32_t titlebar_color;
bool use_custom_titlebar_color;
} decorations;
struct {
unsigned long long id;
void (*callback)(unsigned long long id);
struct wl_callback *current_wl_callback;
} frameCallbackData;
struct {
int32_t width, height;
} user_requested_content_size;
struct {
bool minimize, maximize, fullscreen, window_menu;
} wm_capabilities;
bool maximize_on_first_show;
uint32_t pending_state;
struct {
int width, height;
WaylandWindowState toplevel_states;
uint32_t decoration_mode;
} current, pending;
struct zwp_keyboard_shortcuts_inhibitor_v1 *keyboard_shortcuts_inhibitor;
} _GLFWwindowWayland;
typedef struct _GLFWWaylandDataOffer {
void *id;
bool is_self_offer;
bool is_primary;
const char *mime_for_drop;
uint32_t source_actions;
uint32_t dnd_action;
struct wl_surface *surface;
const char **mimes;
size_t mimes_capacity, mimes_count;
const char **copy_mimes; // Working copy passed to callbacks; pointers into mimes[]
size_t copy_mimes_count; // Count of entries in copy_mimes (accepted count after callback)
bool drag_accepted, dropped;
enum wl_data_device_manager_dnd_action preferred;
int allowed;
uint32_t serial;
struct {
id_type watch_id;
int fd;
char *mime;
} *requested_drop_data;
size_t dd_capacity, dd_count;
} _GLFWWaylandDataOffer;
typedef struct _GLFWWaylandTouchPoint {
int32_t id;
GLFWid window_id;
GLFWTouchPointState state;
bool pressed_in_frame;
double x, y;
} _GLFWWaylandTouchPoint;
// Wayland-specific global data
//
typedef struct _GLFWlibraryWayland {
struct wl_display *display;
struct wl_registry *registry;
struct wl_compositor *compositor;
struct wl_subcompositor *subcompositor;
struct wl_shm *shm;
struct wl_seat *seat;
struct wl_pointer *pointer;
struct wl_keyboard *keyboard;
struct wl_touch *touch;
// The touch points that are down, each tied to the window it landed on.
// Changes collect here and are reported at the wl_touch frame event.
// pressed_in_frame marks a point the application has not heard of yet
struct {
_GLFWWaylandTouchPoint points[16];
size_t count;
// The time of the latest wl_touch event, in milliseconds of the compositor clock
uint32_t last_event_time;
bool has_event_time;
} touch_state;
struct wl_data_device_manager *dataDeviceManager;
struct wl_data_device *dataDevice;
struct xdg_wm_base *wmBase;
int xdg_wm_base_version;
struct zxdg_decoration_manager_v1 *decorationManager;
struct zwp_relative_pointer_manager_v1 *relativePointerManager;
struct zwp_pointer_constraints_v1 *pointerConstraints;
struct wl_data_source *dataSourceForClipboard;
struct zwp_primary_selection_device_manager_v1 *primarySelectionDeviceManager;
struct zwp_primary_selection_device_v1 *primarySelectionDevice;
struct zwp_primary_selection_source_v1 *dataSourceForPrimarySelection;
char clipboard_copy_mime[256];
char primary_selection_copy_mime[256];
struct xdg_activation_v1 *xdg_activation_v1;
struct xdg_toplevel_icon_manager_v1 *xdg_toplevel_icon_manager_v1;
struct xdg_system_bell_v1 *xdg_system_bell_v1;
struct xdg_toplevel_tag_manager_v1 *xdg_toplevel_tag_manager_v1;
struct xdg_toplevel_drag_manager_v1 *xdg_toplevel_drag_manager_v1;
struct wp_cursor_shape_manager_v1 *wp_cursor_shape_manager_v1;
struct wp_cursor_shape_device_v1 *wp_cursor_shape_device_v1;
struct wp_fractional_scale_manager_v1 *wp_fractional_scale_manager_v1;
struct wp_viewporter *wp_viewporter;
struct org_kde_kwin_blur_manager *org_kde_kwin_blur_manager;
struct ext_background_effect_manager_v1 *ext_background_effect_manager_v1;
uint32_t ext_background_effect_capabilities;
struct zwlr_layer_shell_v1 *zwlr_layer_shell_v1;
uint32_t zwlr_layer_shell_v1_version;
struct wp_single_pixel_buffer_manager_v1 *wp_single_pixel_buffer_manager_v1;
struct zwp_idle_inhibit_manager_v1 *idle_inhibit_manager;
struct zwp_keyboard_shortcuts_inhibit_manager_v1 *keyboard_shortcuts_inhibit_manager;
struct zwp_pointer_gestures_v1 *pointer_gestures;
struct zwp_pointer_gesture_hold_v1 *pointer_gesture_hold;
struct zxdg_output_manager_v1 *xdg_output_manager;
struct zwlr_virtual_pointer_manager_v1 *virtual_pointer_manager;
struct zwlr_virtual_pointer_v1 *virtual_pointer;
struct zwp_virtual_keyboard_manager_v1 *virtual_keyboard_manager;
struct zwp_virtual_keyboard_v1 *virtual_keyboard;
int compositorVersion;
int seatVersion;
bool has_key_repeat_events;
struct wl_surface *cursorSurface;
GLFWCursorShape cursorPreviousShape;
uint32_t serial, input_serial, pointer_serial, pointer_enter_serial, keyboard_enter_serial;
// serial of the button press that started the current pointer implicit
// grab, and the number of currently pressed pointer buttons. Requests
// such as wl_data_device.start_drag are silently ignored by compositors
// unless made with the serial of an active implicit grab.
uint32_t pointer_grab_serial;
unsigned pointer_button_count;
int32_t keyboardRepeatRate;
monotonic_t keyboardRepeatDelay;
struct {
uint32_t key;
id_type keyRepeatTimer;
GLFWid keyboardFocusId;
} keyRepeatInfo;
id_type cursorAnimationTimer;
_GLFWXKBData xkb;
_GLFWDBUSData dbus;
_GLFWwindow *pointerFocus;
GLFWid keyboardFocusId;
GLFWid lastKeyboardFocusId;
struct {
void *handle;
PFN_wl_cursor_theme_load theme_load;
PFN_wl_cursor_theme_destroy theme_destroy;
PFN_wl_cursor_theme_get_cursor theme_get_cursor;
PFN_wl_cursor_image_get_buffer image_get_buffer;
} cursor;
struct {
void *handle;
PFN_wl_egl_window_create window_create;
PFN_wl_egl_window_destroy window_destroy;
PFN_wl_egl_window_resize window_resize;
} egl;
struct {
glfw_wl_xdg_activation_request *array;
size_t capacity, sz;
} activation_requests;
EventLoopData eventLoopData;
_GLFWWaylandDataOffer untyped_data_offers[8];
_GLFWWaylandDataOffer clipboard_data_offer, primary_data_offer, drop_data_offer;
bool has_preferred_buffer_scale;
char *compositor_name;
// Drag source state
struct {
struct wl_data_source *source;
struct wl_surface *drag_icon;
struct wp_viewport *drag_viewport;
struct xdg_toplevel_drag_v1 *toplevel_drag;
struct xdg_surface *toplevel_xdg_surface;
struct xdg_toplevel *toplevel_xdg_toplevel;
struct wl_buffer *toplevel_buffer;
// wl_data_device.start_drag is silently ignored by compositors when
// its serial does not match an active pointer implicit grab, which
// can happen as drags are started asynchronously and the client side
// view of the grab can be stale. A wl_display.sync issued right after
// start_drag detects this: any compositor event proving the DND
// session is live (wl_pointer.leave, wl_data_device.enter, any
// wl_data_source event) is ordered before the sync callback, so if
// the callback fires first the start_drag was dropped.
struct wl_callback *start_confirmation;
bool session_confirmed;
// The drag toplevel was configured before the session was confirmed,
// mapping it was deferred so it cannot end up as a stray regular
// window if start_drag was silently ignored.
bool toplevel_map_deferred;
// Number of extra sync roundtrips issued waiting for confirmation;
// some compositors (e.g. niri) send the confirmation event (drag icon
// wl_surface.enter) after the first sync roundtrip, so we retry once
// before concluding that start_drag was silently ignored.
uint8_t sync_retries;
struct {
const char *mime_type;
int fd;
GLFWid watch_id;
char *pending_data;
size_t sz, offset;
} *data_requests;
size_t count, capacity;
GLFWDragOperationType action;
} drag;
} _GLFWlibraryWayland;
// Wayland-specific per-monitor data
//
typedef struct _GLFWmonitorWayland {
struct wl_output *output;
struct zxdg_output_v1 *xdg_output;
uint32_t name;
int currentMode;
int x;
int y;
int scale;
int32_t transform;
int32_t xdg_logical_width;
int32_t xdg_logical_height;
double fractional_scale;
bool xdg_size_received;
bool xdg_position_received;
} _GLFWmonitorWayland;
// Wayland-specific per-cursor data
//
typedef struct _GLFWcursorWayland {
struct wl_cursor *cursor;
struct wl_buffer *buffer;
int width, height;
int xhot, yhot;
unsigned int currentImage;
/** The scale of the cursor, or 0 if the cursor should be loaded late, or -1 if the cursor variable itself is unused. */
int scale;
/** Cursor shape stored to allow late cursor loading in setCursorImage. */
GLFWCursorShape shape;
} _GLFWcursorWayland;
void _glfwAddOutputWayland(uint32_t name, uint32_t version);
void _glfwCreateXdgOutputWayland(_GLFWmonitor *monitor);
void _glfwWaylandBeforeBufferSwap(_GLFWwindow *window);
void _glfwWaylandAfterBufferSwap(_GLFWwindow *window);
void _glfwWaylandSurfaceOutputsChanged(_GLFWwindow *window);
void _glfwSetupWaylandDataDevice(void);
void _glfwSetupWaylandPrimarySelectionDevice(void);
double _glfwWaylandWindowScale(_GLFWwindow *);
int _glfwWaylandIntegerWindowScale(_GLFWwindow *);
void animateCursorImage(id_type timer_id, void *data);
struct wl_cursor *_glfwLoadCursor(GLFWCursorShape, struct wl_cursor_theme *);
void destroy_data_offer(_GLFWWaylandDataOffer *);
const char *_glfwWaylandCompositorName(void);
void _glfwWaylandConfirmDragSession(void);
typedef struct wayland_cursor_shape {
int which;
const char *name;
} wayland_cursor_shape;
wayland_cursor_shape glfw_cursor_shape_to_wayland_cursor_shape(GLFWCursorShape g);
+192
View File
@@ -0,0 +1,192 @@
/*
* wl_text_input.c
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "wl_text_input.h"
#include "internal.h"
#include "wayland-text-input-unstable-v3-client-protocol.h"
#include <stdlib.h>
#include <string.h>
#define debug debug_input
static struct zwp_text_input_v3 *text_input;
static struct zwp_text_input_manager_v3 *text_input_manager;
static char *pending_pre_edit = NULL;
static char *current_pre_edit = NULL;
static char *pending_commit = NULL;
static bool ime_focused = false;
static int last_cursor_left = 0, last_cursor_top = 0, last_cursor_width = 0, last_cursor_height = 0;
uint32_t commit_serial = 0;
static void
commit(void) {
if (text_input) {
zwp_text_input_v3_commit(text_input);
commit_serial++;
}
}
static void
text_input_enter(void *data UNUSED, struct zwp_text_input_v3 *txt_input, struct wl_surface *surface UNUSED) {
debug("text-input: enter event\n");
if (txt_input) {
ime_focused = true;
zwp_text_input_v3_enable(txt_input);
zwp_text_input_v3_set_content_type(txt_input, ZWP_TEXT_INPUT_V3_CONTENT_HINT_NONE, ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_TERMINAL);
if (last_cursor_width > 0) {
zwp_text_input_v3_set_cursor_rectangle(txt_input, last_cursor_left, last_cursor_top, last_cursor_width, last_cursor_height);
}
commit();
}
}
static void
text_input_leave(void *data UNUSED, struct zwp_text_input_v3 *txt_input, struct wl_surface *surface UNUSED) {
debug("text-input: leave event\n");
if (txt_input) {
ime_focused = false;
zwp_text_input_v3_disable(txt_input);
commit();
}
}
static void
send_text(const char *text, GLFWIMEState ime_state) {
_GLFWwindow *w = _glfwFocusedWindow();
if (w && w->callbacks.keyboard) {
GLFWkeyevent fake_ev = {.action = text ? GLFW_PRESS : GLFW_RELEASE};
fake_ev.text = text;
fake_ev.ime_state = ime_state;
w->callbacks.keyboard((GLFWwindow *)w, &fake_ev);
}
}
static void
text_input_preedit_string(void *data UNUSED, struct zwp_text_input_v3 *txt_input UNUSED, const char *text, int32_t cursor_begin, int32_t cursor_end) {
debug("text-input: preedit_string event: text: %s cursor_begin: %d cursor_end: %d\n", text, cursor_begin, cursor_end);
free(pending_pre_edit);
pending_pre_edit = text ? _glfw_strdup(text) : NULL;
}
static void
text_input_commit_string(void *data UNUSED, struct zwp_text_input_v3 *txt_input UNUSED, const char *text) {
debug("text-input: commit_string event: text: %s\n", text);
free(pending_commit);
pending_commit = text ? _glfw_strdup(text) : NULL;
}
static void
text_input_delete_surrounding_text(void *data UNUSED, struct zwp_text_input_v3 *txt_input UNUSED, uint32_t before_length, uint32_t after_length) {
debug("text-input: delete_surrounding_text event: before_length: %u after_length: %u\n", before_length, after_length);
}
static void
text_input_done(void *data UNUSED, struct zwp_text_input_v3 *txt_input UNUSED, uint32_t serial) {
debug("text-input: done event: serial: %u current_commit_serial: %u\n", serial, commit_serial);
const bool bad_event = serial != commit_serial;
// See https://wayland.app/protocols/text-input-unstable-v3#zwp_text_input_v3:event:done
// for handling of bad events. As best as I can tell spec says we perform all client side actions as usual
// but send nothing back to the compositor, aka no cursor position update.
// See https://github.com/kovidgoyal/kitty/pull/7283 for discussion
if ((pending_pre_edit == NULL && current_pre_edit == NULL) || (pending_pre_edit && current_pre_edit && strcmp(pending_pre_edit, current_pre_edit) == 0)) {
free(pending_pre_edit);
pending_pre_edit = NULL;
} else {
free(current_pre_edit);
current_pre_edit = pending_pre_edit;
pending_pre_edit = NULL;
if (current_pre_edit) {
send_text(current_pre_edit, bad_event ? GLFW_IME_WAYLAND_DONE_EVENT : GLFW_IME_PREEDIT_CHANGED);
} else {
// Clear pre-edit text
send_text(NULL, GLFW_IME_WAYLAND_DONE_EVENT);
}
}
if (pending_commit) {
send_text(pending_commit, GLFW_IME_COMMIT_TEXT);
free(pending_commit);
pending_commit = NULL;
}
}
void
_glfwWaylandBindTextInput(struct wl_registry *registry, uint32_t name) {
if (!text_input_manager && _glfw.hints.init.wl.ime) text_input_manager = wl_registry_bind(registry, name, &zwp_text_input_manager_v3_interface, 1);
}
void
_glfwWaylandInitTextInput(void) {
static const struct zwp_text_input_v3_listener text_input_listener = {
.enter = text_input_enter,
.leave = text_input_leave,
.preedit_string = text_input_preedit_string,
.commit_string = text_input_commit_string,
.delete_surrounding_text = text_input_delete_surrounding_text,
.done = text_input_done,
};
if (_glfw.hints.init.wl.ime && !text_input && text_input_manager && _glfw.wl.seat) {
text_input = zwp_text_input_manager_v3_get_text_input(text_input_manager, _glfw.wl.seat);
if (text_input) zwp_text_input_v3_add_listener(text_input, &text_input_listener, NULL);
}
}
void
_glfwWaylandDestroyTextInput(void) {
if (text_input) zwp_text_input_v3_destroy(text_input);
if (text_input_manager) zwp_text_input_manager_v3_destroy(text_input_manager);
text_input = NULL;
text_input_manager = NULL;
free(pending_pre_edit);
pending_pre_edit = NULL;
free(current_pre_edit);
current_pre_edit = NULL;
free(pending_commit);
pending_commit = NULL;
}
void
_glfwPlatformUpdateIMEState(_GLFWwindow *w, const GLFWIMEUpdateEvent *ev) {
if (!text_input) return;
switch (ev->type) {
case GLFW_IME_UPDATE_FOCUS:
debug("\ntext-input: updating IME focus state, ime_focused: %d ev->focused: %d\n", ime_focused, ev->focused);
if (ime_focused) {
zwp_text_input_v3_enable(text_input);
zwp_text_input_v3_set_content_type(text_input, ZWP_TEXT_INPUT_V3_CONTENT_HINT_NONE, ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_TERMINAL);
} else {
free(pending_pre_edit);
pending_pre_edit = NULL;
if (current_pre_edit) {
// Clear pre-edit text
send_text(NULL, GLFW_IME_PREEDIT_CHANGED);
free(current_pre_edit);
current_pre_edit = NULL;
}
if (pending_commit) {
free(pending_commit);
pending_commit = NULL;
}
zwp_text_input_v3_disable(text_input);
}
commit();
break;
case GLFW_IME_UPDATE_CURSOR_POSITION: {
const double scale = _glfwWaylandWindowScale(w);
#define s(x) (int)round((x) / scale)
const int left = s(ev->cursor.left), top = s(ev->cursor.top), width = s(ev->cursor.width), height = s(ev->cursor.height);
#undef s
if (left != last_cursor_left || top != last_cursor_top || width != last_cursor_width || height != last_cursor_height) {
last_cursor_left = left;
last_cursor_top = top;
last_cursor_width = width;
last_cursor_height = height;
debug("\ntext-input: updating cursor position: left=%d top=%d width=%d height=%d\n", left, top, width, height);
zwp_text_input_v3_set_cursor_rectangle(text_input, left, top, width, height);
commit();
}
} break;
}
}
+12
View File
@@ -0,0 +1,12 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include <wayland-client.h>
void _glfwWaylandBindTextInput(struct wl_registry *registry, uint32_t name);
void _glfwWaylandInitTextInput(void);
void _glfwWaylandDestroyTextInput(void);
+3789
View File
File diff suppressed because it is too large. Load diff
+407
View File
@@ -0,0 +1,407 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="wlr_layer_shell_unstable_v1">
<copyright>
Copyright © 2017 Drew DeVault
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
the copyright holders not be used in advertising or publicity
pertaining to distribution of the software without specific,
written prior permission. The copyright holders make no
representations about the suitability of this software for any
purpose. It is provided "as is" without express or implied
warranty.
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
</copyright>
<interface name="zwlr_layer_shell_v1" version="5">
<description summary="create surfaces that are layers of the desktop">
Clients can use this interface to assign the surface_layer role to
wl_surfaces. Such surfaces are assigned to a "layer" of the output and
rendered with a defined z-depth respective to each other. They may also be
anchored to the edges and corners of a screen and specify input handling
semantics. This interface should be suitable for the implementation of
many desktop shell components, and a broad number of other applications
that interact with the desktop.
</description>
<request name="get_layer_surface">
<description summary="create a layer_surface from a surface">
Create a layer surface for an existing surface. This assigns the role of
layer_surface, or raises a protocol error if another role is already
assigned.
Creating a layer surface from a wl_surface which has a buffer attached
or committed is a client error, and any attempts by a client to attach
or manipulate a buffer prior to the first layer_surface.configure call
must also be treated as errors.
After creating a layer_surface object and setting it up, the client
must perform an initial commit without any buffer attached.
The compositor will reply with a layer_surface.configure event.
The client must acknowledge it and is then allowed to attach a buffer
to map the surface.
You may pass NULL for output to allow the compositor to decide which
output to use. Generally this will be the one that the user most
recently interacted with.
Clients can specify a namespace that defines the purpose of the layer
surface.
</description>
<arg name="id" type="new_id" interface="zwlr_layer_surface_v1"/>
<arg name="surface" type="object" interface="wl_surface"/>
<arg name="output" type="object" interface="wl_output" allow-null="true"/>
<arg name="layer" type="uint" enum="layer" summary="layer to add this surface to"/>
<arg name="namespace" type="string" summary="namespace for the layer surface"/>
</request>
<enum name="error">
<entry name="role" value="0" summary="wl_surface has another role"/>
<entry name="invalid_layer" value="1" summary="layer value is invalid"/>
<entry name="already_constructed" value="2" summary="wl_surface has a buffer attached or committed"/>
</enum>
<enum name="layer">
<description summary="available layers for surfaces">
These values indicate which layers a surface can be rendered in. They
are ordered by z depth, bottom-most first. Traditional shell surfaces
will typically be rendered between the bottom and top layers.
Fullscreen shell surfaces are typically rendered at the top layer.
Multiple surfaces can share a single layer, and ordering within a
single layer is undefined.
</description>
<entry name="background" value="0"/>
<entry name="bottom" value="1"/>
<entry name="top" value="2"/>
<entry name="overlay" value="3"/>
</enum>
<!-- Version 3 additions -->
<request name="destroy" type="destructor" since="3">
<description summary="destroy the layer_shell object">
This request indicates that the client will not use the layer_shell
object any more. Objects that have been created through this instance
are not affected.
</description>
</request>
</interface>
<interface name="zwlr_layer_surface_v1" version="5">
<description summary="layer metadata interface">
An interface that may be implemented by a wl_surface, for surfaces that
are designed to be rendered as a layer of a stacked desktop-like
environment.
Layer surface state (layer, size, anchor, exclusive zone,
margin, interactivity) is double-buffered, and will be applied at the
time wl_surface.commit of the corresponding wl_surface is called.
Attaching a null buffer to a layer surface unmaps it.
Unmapping a layer_surface means that the surface cannot be shown by the
compositor until it is explicitly mapped again. The layer_surface
returns to the state it had right after layer_shell.get_layer_surface.
The client can re-map the surface by performing a commit without any
buffer attached, waiting for a configure event and handling it as usual.
</description>
<request name="set_size">
<description summary="sets the size of the surface">
Sets the size of the surface in surface-local coordinates. The
compositor will display the surface centered with respect to its
anchors.
If you pass 0 for either value, the compositor will assign it and
inform you of the assignment in the configure event. You must set your
anchor to opposite edges in the dimensions you omit; not doing so is a
protocol error. Both values are 0 by default.
Size is double-buffered, see wl_surface.commit.
</description>
<arg name="width" type="uint"/>
<arg name="height" type="uint"/>
</request>
<request name="set_anchor">
<description summary="configures the anchor point of the surface">
Requests that the compositor anchor the surface to the specified edges
and corners. If two orthogonal edges are specified (e.g. 'top' and
'left'), then the anchor point will be the intersection of the edges
(e.g. the top left corner of the output); otherwise the anchor point
will be centered on that edge, or in the center if none is specified.
Anchor is double-buffered, see wl_surface.commit.
</description>
<arg name="anchor" type="uint" enum="anchor"/>
</request>
<request name="set_exclusive_zone">
<description summary="configures the exclusive geometry of this surface">
Requests that the compositor avoids occluding an area with other
surfaces. The compositor's use of this information is
implementation-dependent - do not assume that this region will not
actually be occluded.
A positive value is only meaningful if the surface is anchored to one
edge or an edge and both perpendicular edges. If the surface is not
anchored, anchored to only two perpendicular edges (a corner), anchored
to only two parallel edges or anchored to all edges, a positive value
will be treated the same as zero.
A positive zone is the distance from the edge in surface-local
coordinates to consider exclusive.
Surfaces that do not wish to have an exclusive zone may instead specify
how they should interact with surfaces that do. If set to zero, the
surface indicates that it would like to be moved to avoid occluding
surfaces with a positive exclusive zone. If set to -1, the surface
indicates that it would not like to be moved to accommodate for other
surfaces, and the compositor should extend it all the way to the edges
it is anchored to.
For example, a panel might set its exclusive zone to 10, so that
maximized shell surfaces are not shown on top of it. A notification
might set its exclusive zone to 0, so that it is moved to avoid
occluding the panel, but shell surfaces are shown underneath it. A
wallpaper or lock screen might set their exclusive zone to -1, so that
they stretch below or over the panel.
The default value is 0.
Exclusive zone is double-buffered, see wl_surface.commit.
</description>
<arg name="zone" type="int"/>
</request>
<request name="set_margin">
<description summary="sets a margin from the anchor point">
Requests that the surface be placed some distance away from the anchor
point on the output, in surface-local coordinates. Setting this value
for edges you are not anchored to has no effect.
The exclusive zone includes the margin.
Margin is double-buffered, see wl_surface.commit.
</description>
<arg name="top" type="int"/>
<arg name="right" type="int"/>
<arg name="bottom" type="int"/>
<arg name="left" type="int"/>
</request>
<enum name="keyboard_interactivity">
<description summary="types of keyboard interaction possible for a layer shell surface">
Types of keyboard interaction possible for layer shell surfaces. The
rationale for this is twofold: (1) some applications are not interested
in keyboard events and not allowing them to be focused can improve the
desktop experience; (2) some applications will want to take exclusive
keyboard focus.
</description>
<entry name="none" value="0">
<description summary="no keyboard focus is possible">
This value indicates that this surface is not interested in keyboard
events and the compositor should never assign it the keyboard focus.
This is the default value, set for newly created layer shell surfaces.
This is useful for e.g. desktop widgets that display information or
only have interaction with non-keyboard input devices.
</description>
</entry>
<entry name="exclusive" value="1">
<description summary="request exclusive keyboard focus">
Request exclusive keyboard focus if this surface is above the shell surface layer.
For the top and overlay layers, the seat will always give
exclusive keyboard focus to the top-most layer which has keyboard
interactivity set to exclusive. If this layer contains multiple
surfaces with keyboard interactivity set to exclusive, the compositor
determines the one receiving keyboard events in an implementation-
defined manner. In this case, no guarantee is made when this surface
will receive keyboard focus (if ever).
For the bottom and background layers, the compositor is allowed to use
normal focus semantics.
This setting is mainly intended for applications that need to ensure
they receive all keyboard events, such as a lock screen or a password
prompt.
</description>
</entry>
<entry name="on_demand" value="2" since="4">
<description summary="request regular keyboard focus semantics">
This requests the compositor to allow this surface to be focused and
unfocused by the user in an implementation-defined manner. The user
should be able to unfocus this surface even regardless of the layer
it is on.
Typically, the compositor will want to use its normal mechanism to
manage keyboard focus between layer shell surfaces with this setting
and regular toplevels on the desktop layer (e.g. click to focus).
Nevertheless, it is possible for a compositor to require a special
interaction to focus or unfocus layer shell surfaces (e.g. requiring
a click even if focus follows the mouse normally, or providing a
keybinding to switch focus between layers).
This setting is mainly intended for desktop shell components (e.g.
panels) that allow keyboard interaction. Using this option can allow
implementing a desktop shell that can be fully usable without the
mouse.
</description>
</entry>
</enum>
<request name="set_keyboard_interactivity">
<description summary="requests keyboard events">
Set how keyboard events are delivered to this surface. By default,
layer shell surfaces do not receive keyboard events; this request can
be used to change this.
This setting is inherited by child surfaces set by the get_popup
request.
Layer surfaces receive pointer, touch, and tablet events normally. If
you do not want to receive them, set the input region on your surface
to an empty region.
Keyboard interactivity is double-buffered, see wl_surface.commit.
</description>
<arg name="keyboard_interactivity" type="uint" enum="keyboard_interactivity"/>
</request>
<request name="get_popup">
<description summary="assign this layer_surface as an xdg_popup parent">
This assigns an xdg_popup's parent to this layer_surface. This popup
should have been created via xdg_surface::get_popup with the parent set
to NULL, and this request must be invoked before committing the popup's
initial state.
See the documentation of xdg_popup for more details about what an
xdg_popup is and how it is used.
</description>
<arg name="popup" type="object" interface="xdg_popup"/>
</request>
<request name="ack_configure">
<description summary="ack a configure event">
When a configure event is received, if a client commits the
surface in response to the configure event, then the client
must make an ack_configure request sometime before the commit
request, passing along the serial of the configure event.
If the client receives multiple configure events before it
can respond to one, it only has to ack the last configure event.
A client is not required to commit immediately after sending
an ack_configure request - it may even ack_configure several times
before its next surface commit.
A client may send multiple ack_configure requests before committing, but
only the last request sent before a commit indicates which configure
event the client really is responding to.
</description>
<arg name="serial" type="uint" summary="the serial from the configure event"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy the layer_surface">
This request destroys the layer surface.
</description>
</request>
<event name="configure">
<description summary="suggest a surface change">
The configure event asks the client to resize its surface.
Clients should arrange their surface for the new states, and then send
an ack_configure request with the serial sent in this configure event at
some point before committing the new surface.
The client is free to dismiss all but the last configure event it
received.
The width and height arguments specify the size of the window in
surface-local coordinates.
The size is a hint, in the sense that the client is free to ignore it if
it doesn't resize, pick a smaller size (to satisfy aspect ratio or
resize in steps of NxM pixels). If the client picks a smaller size and
is anchored to two opposite anchors (e.g. 'top' and 'bottom'), the
surface will be centered on this axis.
If the width or height arguments are zero, it means the client should
decide its own window dimension.
</description>
<arg name="serial" type="uint"/>
<arg name="width" type="uint"/>
<arg name="height" type="uint"/>
</event>
<event name="closed">
<description summary="surface should be closed">
The closed event is sent by the compositor when the surface will no
longer be shown. The output may have been destroyed or the user may
have asked for it to be removed. Further changes to the surface will be
ignored. The client should destroy the resource after receiving this
event, and create a new surface if they so choose.
</description>
</event>
<enum name="error">
<entry name="invalid_surface_state" value="0" summary="provided surface state is invalid"/>
<entry name="invalid_size" value="1" summary="size is invalid"/>
<entry name="invalid_anchor" value="2" summary="anchor bitfield is invalid"/>
<entry name="invalid_keyboard_interactivity" value="3" summary="keyboard interactivity is invalid"/>
<entry name="invalid_exclusive_edge" value="4" summary="exclusive edge is invalid given the surface anchors"/>
</enum>
<enum name="anchor" bitfield="true">
<entry name="top" value="1" summary="the top edge of the anchor rectangle"/>
<entry name="bottom" value="2" summary="the bottom edge of the anchor rectangle"/>
<entry name="left" value="4" summary="the left edge of the anchor rectangle"/>
<entry name="right" value="8" summary="the right edge of the anchor rectangle"/>
</enum>
<!-- Version 2 additions -->
<request name="set_layer" since="2">
<description summary="change the layer of the surface">
Change the layer that the surface is rendered on.
Layer is double-buffered, see wl_surface.commit.
</description>
<arg name="layer" type="uint" enum="zwlr_layer_shell_v1.layer" summary="layer to move this surface to"/>
</request>
<!-- Version 5 additions -->
<request name="set_exclusive_edge" since="5">
<description summary="set the edge the exclusive zone will be applied to">
Requests an edge for the exclusive zone to apply. The exclusive
edge will be automatically deduced from anchor points when possible,
but when the surface is anchored to a corner, it will be necessary
to set it explicitly to disambiguate, as it is not possible to deduce
which one of the two corner edges should be used.
The edge must be one the surface is anchored to, otherwise the
invalid_exclusive_edge protocol error will be raised.
</description>
<arg name="edge" type="uint" enum="anchor"/>
</request>
</interface>
</protocol>
+116
View File
@@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="wlr_virtual_pointer_unstable_v1">
<copyright>
Copyright © 2019 Josef Gajdusek
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</copyright>
<interface name="zwlr_virtual_pointer_v1" version="2">
<description summary="virtual pointer">
This protocol allows clients to emulate a physical pointer device.
</description>
<enum name="error">
<entry name="invalid_axis" value="0" summary="client sent invalid axis enumeration value"/>
<entry name="invalid_axis_source" value="1" summary="client sent invalid axis source enumeration value"/>
</enum>
<request name="motion">
<description summary="pointer relative motion event"/>
<arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
<arg name="dx" type="fixed" summary="displacement on the x-axis"/>
<arg name="dy" type="fixed" summary="displacement on the y-axis"/>
</request>
<request name="motion_absolute">
<description summary="pointer absolute motion event"/>
<arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
<arg name="x" type="uint" summary="position on the x-axis"/>
<arg name="y" type="uint" summary="position on the y-axis"/>
<arg name="x_extent" type="uint" summary="extent of the x-axis"/>
<arg name="y_extent" type="uint" summary="extent of the y-axis"/>
</request>
<request name="button">
<description summary="button event"/>
<arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
<arg name="button" type="uint" summary="button that produced the event"/>
<arg name="state" type="uint" summary="physical state of the button"/>
</request>
<request name="axis">
<description summary="axis event"/>
<arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
<arg name="axis" type="uint" summary="axis type"/>
<arg name="value" type="fixed" summary="length of a vector along the specified axis in surface-local coordinates"/>
</request>
<request name="frame">
<description summary="end of a pointer event sequence"/>
</request>
<request name="axis_source">
<description summary="axis source event"/>
<arg name="axis_source" type="uint" summary="source of the axis event"/>
</request>
<request name="axis_stop">
<description summary="axis stop event"/>
<arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
<arg name="axis" type="uint" summary="the axis stopped with this event"/>
</request>
<request name="axis_discrete">
<description summary="axis click event"/>
<arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
<arg name="axis" type="uint" summary="axis type"/>
<arg name="value" type="fixed" summary="length of a vector along the specified axis in surface-local coordinates"/>
<arg name="discrete" type="int" summary="number of steps"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy the virtual pointer object"/>
</request>
</interface>
<interface name="zwlr_virtual_pointer_manager_v1" version="2">
<description summary="virtual pointer manager">
This object allows clients to create individual virtual pointer objects.
</description>
<request name="create_virtual_pointer">
<description summary="create a virtual pointer"/>
<arg name="seat" type="object" interface="wl_seat" allow-null="true" summary="seat for the pointer"/>
<arg name="id" type="new_id" interface="zwlr_virtual_pointer_v1"/>
</request>
<request name="create_virtual_pointer_with_output" since="2">
<description summary="create a virtual pointer for a given output"/>
<arg name="seat" type="object" interface="wl_seat" allow-null="true"/>
<arg name="output" type="object" interface="wl_output" allow-null="true"/>
<arg name="id" type="new_id" interface="zwlr_virtual_pointer_v1"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy the virtual pointer manager"/>
</request>
</interface>
</protocol>
+830
View File
@@ -0,0 +1,830 @@
//========================================================================
// GLFW 3.4 X11 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#define _GNU_SOURCE
#include "internal.h"
#include "backend_utils.h"
#include "linux_desktop_settings.h"
#include <X11/Xresource.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <locale.h>
#include <fcntl.h>
#include <unistd.h>
// Return the atom ID only if it is listed in the specified array
//
static Atom
getAtomIfSupported(Atom *supportedAtoms, unsigned long atomCount, const Atom atom) {
for (unsigned long i = 0; i < atomCount; i++) {
if (supportedAtoms[i] == atom) return atom;
}
return None;
}
// Check whether the running window manager is EWMH-compliant
//
static void
detectEWMH(void) {
// First we read the _NET_SUPPORTING_WM_CHECK property on the root window
Window *windowFromRoot = NULL;
if (!_glfwGetWindowPropertyX11(_glfw.x11.root, _glfw.x11.NET_SUPPORTING_WM_CHECK, XA_WINDOW, (unsigned char **)&windowFromRoot)) { return; }
_glfwGrabErrorHandlerX11();
// If it exists, it should be the XID of a top-level window
// Then we look for the same property on that window
Window *windowFromChild = NULL;
if (!_glfwGetWindowPropertyX11(*windowFromRoot, _glfw.x11.NET_SUPPORTING_WM_CHECK, XA_WINDOW, (unsigned char **)&windowFromChild)) {
XFree(windowFromRoot);
return;
}
_glfwReleaseErrorHandlerX11();
// If the property exists, it should contain the XID of the window
if (*windowFromRoot != *windowFromChild) {
XFree(windowFromRoot);
XFree(windowFromChild);
return;
}
XFree(windowFromRoot);
XFree(windowFromChild);
// We are now fairly sure that an EWMH-compliant WM is currently running
// We can now start querying the WM about what features it supports by
// looking in the _NET_SUPPORTED property on the root window
// It should contain a list of supported EWMH protocol and state atoms
Atom *supportedAtoms = NULL;
const unsigned long atomCount = _glfwGetWindowPropertyX11(_glfw.x11.root, _glfw.x11.NET_SUPPORTED, XA_ATOM, (unsigned char **)&supportedAtoms);
if (!supportedAtoms) return;
// See which of the atoms we support that are supported by the WM
#define ALL_ATOMS \
S(NET_WM_STATE) \
S(NET_WM_STATE_ABOVE) \
S(NET_WM_STATE_BELOW) \
S(NET_WM_STATE_FULLSCREEN) \
S(NET_WM_STATE_MAXIMIZED_VERT) \
S(NET_WM_STATE_MAXIMIZED_HORZ) \
S(NET_WM_STATE_DEMANDS_ATTENTION) \
S(NET_WM_STATE_SKIP_TASKBAR) \
S(NET_WM_STATE_SKIP_PAGER) \
S(NET_WM_STATE_STICKY) \
\
S(NET_WM_FULLSCREEN_MONITORS) \
S(NET_WM_STRUT_PARTIAL) \
\
S(NET_WM_WINDOW_TYPE) \
S(NET_WM_WINDOW_TYPE_NORMAL) \
S(NET_WM_WINDOW_TYPE_DOCK) \
S(NET_WM_WINDOW_TYPE_DESKTOP) \
S(NET_WM_WINDOW_TYPE_UTILITY) \
S(NET_WM_WINDOW_TYPE_SPLASH) \
S(NET_WM_WINDOW_TYPE_DIALOG) \
S(NET_WM_WINDOW_TYPE_MENU) \
S(NET_WM_WINDOW_TYPE_NOTIFICATION) \
\
S(NET_WORKAREA) \
S(NET_CURRENT_DESKTOP) \
S(NET_ACTIVE_WINDOW) \
S(NET_FRAME_EXTENTS) \
S(NET_REQUEST_FRAME_EXTENTS) \
\
S(NET_WM_ALLOWED_ACTIONS) \
S(NET_WM_ACTION_MOVE) \
S(NET_WM_ACTION_RESIZE) \
S(NET_WM_ACTION_MINIMIZE) \
S(NET_WM_ACTION_SHADE) \
S(NET_WM_ACTION_STICK) \
S(NET_WM_ACTION_MAXIMIZE_HORZ) \
S(NET_WM_ACTION_MAXIMIZE_VERT) \
S(NET_WM_ACTION_FULLSCREEN) \
S(NET_WM_ACTION_CHANGE_DESKTOP) \
S(NET_WM_ACTION_CLOSE) \
S(NET_WM_ACTION_ABOVE) \
S(NET_WM_ACTION_BELOW) \
S(NET_WM_ACTION_ABOVE_BELOW)
static const char *atom_names[40] = {
#define S(x) "_" #x,
ALL_ATOMS};
#undef S
Atom atoms[arraysz(atom_names)];
XInternAtoms(_glfw.x11.display, (char **)atom_names, arraysz(atom_names), False, atoms);
unsigned i = 0;
#define S(name) _glfw.x11.name = getAtomIfSupported(supportedAtoms, atomCount, atoms[i++]);
ALL_ATOMS
#undef S
#undef ALL_ATOMS
XFree(supportedAtoms);
}
void
read_xi_scroll_devices(void) {
#define xi _glfw.x11.xi
xi.num_scroll_devices = 0;
// Require XI2.1 or later for smooth scrolling
if (!xi.available || xi.major < 2 || (xi.major == 2 && xi.minor < 1) || !xi.LIBINPUT_SCROLL_METHOD_ENABLED) return;
#undef xi
int deviceCount;
// Grab the error handler to prevent XI_BadDevice errors from killing kitty
// when a device is removed between XIQueryDevice and XIGetProperty calls.
_glfwGrabErrorHandlerX11();
XIDeviceInfo *devices = XIQueryDevice(_glfw.x11.display, XIAllDevices, &deviceCount);
if (!devices) {
_glfwReleaseErrorHandlerX11();
return;
}
for (int i = 0; i < deviceCount; i++) {
XIDeviceInfo *device = &devices[i];
if (device->use == XIMasterPointer) _glfw.x11.xi.master_pointer_id = device->deviceid;
if (device->use != XISlavePointer || !device->enabled) continue;
Atom actual_type;
int actual_format;
unsigned long nitems, bytes_after;
unsigned char *data = NULL;
bool is_highres = false;
XIGetProperty(
_glfw.x11.display,
device->deviceid,
_glfw.x11.xi.LIBINPUT_SCROLL_METHOD_ENABLED,
0,
2,
False,
XA_INTEGER,
&actual_type,
&actual_format,
&nitems,
&bytes_after,
&data);
if (data) {
if (nitems > 1) is_highres = data[0] || data[1];
XFree(data);
}
// Detect if this is a finger-based device (touchpad/touchscreen)
bool is_finger_based = false;
// Method 1: Check for libinput tapping support (touchpads only)
if (_glfw.x11.xi.LIBINPUT_TAPPING != None) {
Atom tapping_type;
int tapping_format;
unsigned long tapping_nitems, tapping_bytes;
unsigned char *tapping_data = NULL;
if (XIGetProperty(
_glfw.x11.display,
device->deviceid,
_glfw.x11.xi.LIBINPUT_TAPPING,
0,
1,
False,
AnyPropertyType,
&tapping_type,
&tapping_format,
&tapping_nitems,
&tapping_bytes,
&tapping_data) == Success) {
if (tapping_data) {
if (tapping_nitems > 0) is_finger_based = true;
XFree(tapping_data);
}
}
}
// Method 2: Check for touch class (touchscreens/touchpads)
if (!is_finger_based) {
for (int j = 0; j < device->num_classes; j++) {
if (device->classes[j]->type == XITouchClass) {
is_finger_based = true;
break;
}
}
}
for (int j = 0; j < device->num_classes; j++) {
if (device->classes[j]->type != XIScrollClass) continue;
XIScrollClassInfo *scroll = (XIScrollClassInfo *)device->classes[j];
XIScrollDevice *d = NULL;
for (unsigned k = 0; k < _glfw.x11.xi.num_scroll_devices; k++) {
XIScrollDevice *t = _glfw.x11.xi.scroll_devices + k;
if (t->deviceid == device->deviceid && t->sourceid == scroll->sourceid) {
d = t;
break;
}
}
if (!d) {
if (_glfw.x11.xi.num_scroll_devices >= arraysz(_glfw.x11.xi.scroll_devices)) continue;
d = &_glfw.x11.xi.scroll_devices[_glfw.x11.xi.num_scroll_devices++];
*d = (XIScrollDevice){
.is_finger_based = is_finger_based,
.deviceid = device->deviceid,
.sourceid = scroll->sourceid,
};
if (is_highres) {
d->type_detected = true;
d->offset_type = GLFW_SCROLL_OFFEST_HIGHRES;
}
memcpy(d->name, device->name, MIN(sizeof(d->name) - 1, strlen(device->name)));
}
if (d->num_valuators >= arraysz(d->valuators)) continue;
XIScrollValuator *v = d->valuators + d->num_valuators++;
*v = (XIScrollValuator){
.number = scroll->number,
.is_vertical = scroll->scroll_type == XIScrollTypeVertical,
.increment = scroll->increment,
};
}
for (int j = 0; j < device->num_classes; j++) {
if (device->classes[j]->type != XIValuatorClass) continue;
XIValuatorClassInfo *vi = (XIValuatorClassInfo *)device->classes[j];
XIScrollDevice *d = NULL;
for (unsigned k = 0; k < _glfw.x11.xi.num_scroll_devices; k++) {
XIScrollDevice *t = _glfw.x11.xi.scroll_devices + k;
if (t->deviceid == device->deviceid && t->sourceid == vi->sourceid) {
d = t;
break;
}
}
if (!d) continue;
XIScrollValuator *v = NULL;
for (unsigned k = 0; k < d->num_valuators; k++) {
XIScrollValuator *t = d->valuators + k;
if (t->number == vi->number) {
v = t;
break;
}
}
if (!v) continue;
v->value = vi->value;
v->mode = vi->mode;
v->resolution = vi->resolution;
v->min = vi->min;
v->max = vi->max;
v->initialized = true;
}
}
XIFreeDeviceInfo(devices);
_glfwReleaseErrorHandlerX11();
}
// Look for and initialize supported X11 extensions
//
static bool
initExtensions(void) {
_glfw.x11.vidmode.handle = _glfw_dlopen("libXxf86vm.so.1");
if (_glfw.x11.vidmode.handle) {
glfw_dlsym(_glfw.x11.vidmode.QueryExtension, _glfw.x11.vidmode.handle, "XF86VidModeQueryExtension");
glfw_dlsym(_glfw.x11.vidmode.GetGammaRamp, _glfw.x11.vidmode.handle, "XF86VidModeGetGammaRamp");
glfw_dlsym(_glfw.x11.vidmode.SetGammaRamp, _glfw.x11.vidmode.handle, "XF86VidModeSetGammaRamp");
glfw_dlsym(_glfw.x11.vidmode.GetGammaRampSize, _glfw.x11.vidmode.handle, "XF86VidModeGetGammaRampSize");
_glfw.x11.vidmode.available = XF86VidModeQueryExtension(_glfw.x11.display, &_glfw.x11.vidmode.eventBase, &_glfw.x11.vidmode.errorBase);
}
#if defined(__CYGWIN__)
_glfw.x11.xi.handle = _glfw_dlopen("libXi-6.so");
#else
_glfw.x11.xi.handle = _glfw_dlopen("libXi.so.6");
#endif
if (_glfw.x11.xi.handle) {
glfw_dlsym(_glfw.x11.xi.QueryVersion, _glfw.x11.xi.handle, "XIQueryVersion");
glfw_dlsym(_glfw.x11.xi.SelectEvents, _glfw.x11.xi.handle, "XISelectEvents");
glfw_dlsym(_glfw.x11.xi.QueryDevice, _glfw.x11.xi.handle, "XIQueryDevice");
glfw_dlsym(_glfw.x11.xi.FreeDeviceInfo, _glfw.x11.xi.handle, "XIFreeDeviceInfo");
glfw_dlsym(_glfw.x11.xi.GetProperty, _glfw.x11.xi.handle, "XIGetProperty");
if (XQueryExtension(_glfw.x11.display, "XInputExtension", &_glfw.x11.xi.majorOpcode, &_glfw.x11.xi.eventBase, &_glfw.x11.xi.errorBase)) {
_glfw.x11.xi.major = 2;
_glfw.x11.xi.minor = 1;
if (XIQueryVersion(_glfw.x11.display, &_glfw.x11.xi.major, &_glfw.x11.xi.minor) == Success) { _glfw.x11.xi.available = true; }
}
}
#if defined(__CYGWIN__)
_glfw.x11.randr.handle = _glfw_dlopen("libXrandr-2.so");
#else
_glfw.x11.randr.handle = _glfw_dlopen("libXrandr.so.2");
#endif
if (_glfw.x11.randr.handle) {
glfw_dlsym(_glfw.x11.randr.AllocGamma, _glfw.x11.randr.handle, "XRRAllocGamma");
glfw_dlsym(_glfw.x11.randr.FreeGamma, _glfw.x11.randr.handle, "XRRFreeGamma");
glfw_dlsym(_glfw.x11.randr.FreeCrtcInfo, _glfw.x11.randr.handle, "XRRFreeCrtcInfo");
glfw_dlsym(_glfw.x11.randr.FreeGamma, _glfw.x11.randr.handle, "XRRFreeGamma");
glfw_dlsym(_glfw.x11.randr.FreeOutputInfo, _glfw.x11.randr.handle, "XRRFreeOutputInfo");
glfw_dlsym(_glfw.x11.randr.FreeScreenResources, _glfw.x11.randr.handle, "XRRFreeScreenResources");
glfw_dlsym(_glfw.x11.randr.GetCrtcGamma, _glfw.x11.randr.handle, "XRRGetCrtcGamma");
glfw_dlsym(_glfw.x11.randr.GetCrtcGammaSize, _glfw.x11.randr.handle, "XRRGetCrtcGammaSize");
glfw_dlsym(_glfw.x11.randr.GetCrtcInfo, _glfw.x11.randr.handle, "XRRGetCrtcInfo");
glfw_dlsym(_glfw.x11.randr.GetOutputInfo, _glfw.x11.randr.handle, "XRRGetOutputInfo");
glfw_dlsym(_glfw.x11.randr.GetOutputPrimary, _glfw.x11.randr.handle, "XRRGetOutputPrimary");
glfw_dlsym(_glfw.x11.randr.GetScreenResourcesCurrent, _glfw.x11.randr.handle, "XRRGetScreenResourcesCurrent");
glfw_dlsym(_glfw.x11.randr.QueryExtension, _glfw.x11.randr.handle, "XRRQueryExtension");
glfw_dlsym(_glfw.x11.randr.QueryVersion, _glfw.x11.randr.handle, "XRRQueryVersion");
glfw_dlsym(_glfw.x11.randr.SelectInput, _glfw.x11.randr.handle, "XRRSelectInput");
glfw_dlsym(_glfw.x11.randr.SetCrtcConfig, _glfw.x11.randr.handle, "XRRSetCrtcConfig");
glfw_dlsym(_glfw.x11.randr.SetCrtcGamma, _glfw.x11.randr.handle, "XRRSetCrtcGamma");
glfw_dlsym(_glfw.x11.randr.UpdateConfiguration, _glfw.x11.randr.handle, "XRRUpdateConfiguration");
if (XRRQueryExtension(_glfw.x11.display, &_glfw.x11.randr.eventBase, &_glfw.x11.randr.errorBase)) {
if (XRRQueryVersion(_glfw.x11.display, &_glfw.x11.randr.major, &_glfw.x11.randr.minor)) {
// The GLFW RandR path requires at least version 1.3
if (_glfw.x11.randr.major > 1 || _glfw.x11.randr.minor >= 3) _glfw.x11.randr.available = true;
} else {
_glfwInputError(GLFW_PLATFORM_ERROR, "X11: Failed to query RandR version");
}
}
}
if (_glfw.x11.randr.available) {
XRRScreenResources *sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root);
if (!sr->ncrtc || !XRRGetCrtcGammaSize(_glfw.x11.display, sr->crtcs[0])) {
// This is likely an older Nvidia driver with broken gamma support
// Flag it as useless and fall back to xf86vm gamma, if available
_glfw.x11.randr.gammaBroken = true;
}
if (!sr->ncrtc) {
// A system without CRTCs is likely a system with broken RandR
// Disable the RandR monitor path and fall back to core functions
_glfw.x11.randr.monitorBroken = true;
}
XRRFreeScreenResources(sr);
}
if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken) { XRRSelectInput(_glfw.x11.display, _glfw.x11.root, RROutputChangeNotifyMask); }
#if defined(__CYGWIN__)
_glfw.x11.xcursor.handle = _glfw_dlopen("libXcursor-1.so");
#else
_glfw.x11.xcursor.handle = _glfw_dlopen("libXcursor.so.1");
#endif
if (_glfw.x11.xcursor.handle) {
glfw_dlsym(_glfw.x11.xcursor.ImageCreate, _glfw.x11.xcursor.handle, "XcursorImageCreate");
glfw_dlsym(_glfw.x11.xcursor.ImageDestroy, _glfw.x11.xcursor.handle, "XcursorImageDestroy");
glfw_dlsym(_glfw.x11.xcursor.ImageLoadCursor, _glfw.x11.xcursor.handle, "XcursorImageLoadCursor");
}
#if defined(__CYGWIN__)
_glfw.x11.xinerama.handle = _glfw_dlopen("libXinerama-1.so");
#else
_glfw.x11.xinerama.handle = _glfw_dlopen("libXinerama.so.1");
#endif
if (_glfw.x11.xinerama.handle) {
glfw_dlsym(_glfw.x11.xinerama.IsActive, _glfw.x11.xinerama.handle, "XineramaIsActive");
glfw_dlsym(_glfw.x11.xinerama.QueryExtension, _glfw.x11.xinerama.handle, "XineramaQueryExtension");
glfw_dlsym(_glfw.x11.xinerama.QueryScreens, _glfw.x11.xinerama.handle, "XineramaQueryScreens");
if (XineramaQueryExtension(_glfw.x11.display, &_glfw.x11.xinerama.major, &_glfw.x11.xinerama.minor)) {
if (XineramaIsActive(_glfw.x11.display)) _glfw.x11.xinerama.available = true;
}
}
#if defined(__CYGWIN__)
_glfw.x11.xrender.handle = _glfw_dlopen("libXrender-1.so");
#else
_glfw.x11.xrender.handle = _glfw_dlopen("libXrender.so.1");
#endif
if (_glfw.x11.xrender.handle) {
glfw_dlsym(_glfw.x11.xrender.QueryExtension, _glfw.x11.xrender.handle, "XRenderQueryExtension");
glfw_dlsym(_glfw.x11.xrender.QueryVersion, _glfw.x11.xrender.handle, "XRenderQueryVersion");
glfw_dlsym(_glfw.x11.xrender.FindVisualFormat, _glfw.x11.xrender.handle, "XRenderFindVisualFormat");
if (XRenderQueryExtension(_glfw.x11.display, &_glfw.x11.xrender.errorBase, &_glfw.x11.xrender.eventBase)) {
if (XRenderQueryVersion(_glfw.x11.display, &_glfw.x11.xrender.major, &_glfw.x11.xrender.minor)) { _glfw.x11.xrender.available = true; }
}
}
#if defined(__CYGWIN__)
_glfw.x11.xshape.handle = _glfw_dlopen("libXext-6.so");
#else
_glfw.x11.xshape.handle = _glfw_dlopen("libXext.so.6");
#endif
if (_glfw.x11.xshape.handle) {
glfw_dlsym(_glfw.x11.xshape.QueryExtension, _glfw.x11.xshape.handle, "XShapeQueryExtension");
glfw_dlsym(_glfw.x11.xshape.ShapeCombineRegion, _glfw.x11.xshape.handle, "XShapeCombineRegion");
glfw_dlsym(_glfw.x11.xshape.QueryVersion, _glfw.x11.xshape.handle, "XShapeQueryVersion");
if (XShapeQueryExtension(_glfw.x11.display, &_glfw.x11.xshape.errorBase, &_glfw.x11.xshape.eventBase)) {
if (XShapeQueryVersion(_glfw.x11.display, &_glfw.x11.xshape.major, &_glfw.x11.xshape.minor)) { _glfw.x11.xshape.available = true; }
}
}
_glfw.x11.xkb.major = 1;
_glfw.x11.xkb.minor = 0;
_glfw.x11.xkb.available = XkbQueryExtension(
_glfw.x11.display, &_glfw.x11.xkb.majorOpcode, &_glfw.x11.xkb.eventBase, &_glfw.x11.xkb.errorBase, &_glfw.x11.xkb.major, &_glfw.x11.xkb.minor);
if (!_glfw.x11.xkb.available) {
_glfwInputError(GLFW_PLATFORM_ERROR, "X11: Failed to load Xkb extension");
return false;
}
Bool supported;
if (XkbSetDetectableAutoRepeat(_glfw.x11.display, True, &supported)) {
if (supported) _glfw.x11.xkb.detectable = true;
}
if (!glfw_xkb_set_x11_events_mask()) return false;
if (!glfw_xkb_create_context(&_glfw.x11.xkb)) return false;
if (!glfw_xkb_update_x11_keyboard_id(&_glfw.x11.xkb)) return false;
if (!glfw_xkb_compile_keymap(&_glfw.x11.xkb, NULL)) return false;
// String format atoms
_glfw.x11.NULL_ = XInternAtom(_glfw.x11.display, "NULL", False);
_glfw.x11.UTF8_STRING = XInternAtom(_glfw.x11.display, "UTF8_STRING", False);
_glfw.x11.ATOM_PAIR = XInternAtom(_glfw.x11.display, "ATOM_PAIR", False);
// Custom selection property atom
_glfw.x11.GLFW_SELECTION = XInternAtom(_glfw.x11.display, "GLFW_SELECTION", False);
// ICCCM standard clipboard atoms
_glfw.x11.TARGETS = XInternAtom(_glfw.x11.display, "TARGETS", False);
_glfw.x11.MULTIPLE = XInternAtom(_glfw.x11.display, "MULTIPLE", False);
_glfw.x11.PRIMARY = XInternAtom(_glfw.x11.display, "PRIMARY", False);
_glfw.x11.INCR = XInternAtom(_glfw.x11.display, "INCR", False);
_glfw.x11.CLIPBOARD = XInternAtom(_glfw.x11.display, "CLIPBOARD", False);
// Clipboard manager atoms
_glfw.x11.CLIPBOARD_MANAGER = XInternAtom(_glfw.x11.display, "CLIPBOARD_MANAGER", False);
_glfw.x11.SAVE_TARGETS = XInternAtom(_glfw.x11.display, "SAVE_TARGETS", False);
// Xdnd (drag and drop) atoms
_glfw.x11.XdndAware = XInternAtom(_glfw.x11.display, "XdndAware", False);
_glfw.x11.XdndEnter = XInternAtom(_glfw.x11.display, "XdndEnter", False);
_glfw.x11.XdndPosition = XInternAtom(_glfw.x11.display, "XdndPosition", False);
_glfw.x11.XdndStatus = XInternAtom(_glfw.x11.display, "XdndStatus", False);
_glfw.x11.XdndActionCopy = XInternAtom(_glfw.x11.display, "XdndActionCopy", False);
_glfw.x11.XdndActionMove = XInternAtom(_glfw.x11.display, "XdndActionMove", False);
_glfw.x11.XdndActionLink = XInternAtom(_glfw.x11.display, "XdndActionLink", False);
_glfw.x11.XdndDrop = XInternAtom(_glfw.x11.display, "XdndDrop", False);
_glfw.x11.XdndFinished = XInternAtom(_glfw.x11.display, "XdndFinished", False);
_glfw.x11.XdndSelection = XInternAtom(_glfw.x11.display, "XdndSelection", False);
_glfw.x11.XdndTypeList = XInternAtom(_glfw.x11.display, "XdndTypeList", False);
_glfw.x11.XdndActionList = XInternAtom(_glfw.x11.display, "XdndActionList", False);
_glfw.x11.XdndActionAsk = XInternAtom(_glfw.x11.display, "XdndActionAsk", False);
_glfw.x11.XdndLeave = XInternAtom(_glfw.x11.display, "XdndLeave", False);
_glfw.x11.XdndProxy = XInternAtom(_glfw.x11.display, "XdndProxy", False);
// ICCCM, EWMH and Motif window property atoms
// These can be set safely even without WM support
// The EWMH atoms that require WM support are handled in detectEWMH
_glfw.x11.WM_PROTOCOLS = XInternAtom(_glfw.x11.display, "WM_PROTOCOLS", False);
_glfw.x11.WM_STATE = XInternAtom(_glfw.x11.display, "WM_STATE", False);
_glfw.x11.WM_DELETE_WINDOW = XInternAtom(_glfw.x11.display, "WM_DELETE_WINDOW", False);
_glfw.x11.NET_SUPPORTED = XInternAtom(_glfw.x11.display, "_NET_SUPPORTED", False);
_glfw.x11.NET_SUPPORTING_WM_CHECK = XInternAtom(_glfw.x11.display, "_NET_SUPPORTING_WM_CHECK", False);
_glfw.x11.NET_WM_ICON = XInternAtom(_glfw.x11.display, "_NET_WM_ICON", False);
_glfw.x11.NET_WM_PING = XInternAtom(_glfw.x11.display, "_NET_WM_PING", False);
_glfw.x11.NET_WM_PID = XInternAtom(_glfw.x11.display, "_NET_WM_PID", False);
_glfw.x11.NET_WM_NAME = XInternAtom(_glfw.x11.display, "_NET_WM_NAME", False);
_glfw.x11.NET_WM_ICON_NAME = XInternAtom(_glfw.x11.display, "_NET_WM_ICON_NAME", False);
_glfw.x11.NET_WM_BYPASS_COMPOSITOR = XInternAtom(_glfw.x11.display, "_NET_WM_BYPASS_COMPOSITOR", False);
_glfw.x11.NET_WM_WINDOW_OPACITY = XInternAtom(_glfw.x11.display, "_NET_WM_WINDOW_OPACITY", False);
_glfw.x11.MOTIF_WM_HINTS = XInternAtom(_glfw.x11.display, "_MOTIF_WM_HINTS", False);
_glfw.x11.xi.LIBINPUT_SCROLL_METHOD_ENABLED = XInternAtom(_glfw.x11.display, "libinput Scroll Method Enabled", False);
_glfw.x11.xi.LIBINPUT_TAPPING = XInternAtom(_glfw.x11.display, "libinput Tapping Enabled", False);
read_xi_scroll_devices();
// Select XI_HierarchyChanged events to detect device add/remove
if (_glfw.x11.xi.available) {
XIEventMask em;
unsigned char mask[XIMaskLen(XI_HierarchyChanged)] = {0};
em.deviceid = XIAllDevices;
em.mask_len = sizeof(mask);
em.mask = mask;
XISetMask(mask, XI_HierarchyChanged);
XISelectEvents(_glfw.x11.display, _glfw.x11.root, &em, 1);
}
// The compositing manager selection name contains the screen number
{
char name[32];
snprintf(name, sizeof(name), "_NET_WM_CM_S%u", _glfw.x11.screen);
_glfw.x11.NET_WM_CM_Sx = XInternAtom(_glfw.x11.display, name, False);
}
// Detect whether an EWMH-conformant window manager is running
detectEWMH();
return true;
}
// Retrieve system content scale via folklore heuristics
//
void
_glfwGetSystemContentScaleX11(float *xscale, float *yscale, bool bypass_cache) {
// Start by assuming the default X11 DPI
// NOTE: Some desktop environments (KDE) may remove the Xft.dpi field when it
// would be set to 96, so assume that is the case if we cannot find it
float xdpi = 96.f, ydpi = 96.f;
// NOTE: Basing the scale on Xft.dpi where available should provide the most
// consistent user experience (matches Qt, Gtk, etc), although not
// always the most accurate one
char *rms = NULL;
char *owned_rms = NULL;
if (bypass_cache) {
_glfwGetWindowPropertyX11(_glfw.x11.root, _glfw.x11.RESOURCE_MANAGER, XA_STRING, (unsigned char **)&owned_rms);
rms = owned_rms;
} else {
rms = XResourceManagerString(_glfw.x11.display);
}
if (rms) {
XrmDatabase db = XrmGetStringDatabase(rms);
if (db) {
XrmValue value;
char *type = NULL;
if (XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &value)) {
if (type && strcmp(type, "String") == 0) xdpi = ydpi = (float)atof(value.addr);
}
XrmDestroyDatabase(db);
}
XFree(owned_rms);
}
*xscale = xdpi / 96.f;
*yscale = ydpi / 96.f;
}
// Create a blank cursor for hidden and disabled cursor modes
//
static Cursor
createHiddenCursor(void) {
unsigned char pixels[16 * 16 * 4] = {0};
GLFWimage image = {16, 16, pixels};
return _glfwCreateCursorX11(&image, 0, 0);
}
// Create a helper window for IPC
//
static Window
createHelperWindow(void) {
XSetWindowAttributes wa;
wa.event_mask = PropertyChangeMask;
return XCreateWindow(_glfw.x11.display, _glfw.x11.root, 0, 0, 1, 1, 0, 0, InputOnly, DefaultVisual(_glfw.x11.display, _glfw.x11.screen), CWEventMask, &wa);
}
// X error handler
//
static int
errorHandler(Display *display, XErrorEvent *event) {
if (_glfw.x11.display != display) return 0;
_glfw.x11.errorCode = event->error_code;
return 0;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Sets the X error handler callback
//
void
_glfwGrabErrorHandlerX11(void) {
_glfw.x11.errorCode = Success;
XSetErrorHandler(errorHandler);
}
// Clears the X error handler callback
//
void
_glfwReleaseErrorHandlerX11(void) {
// Synchronize to make sure all commands are processed
XSync(_glfw.x11.display, False);
XSetErrorHandler(NULL);
}
// Reports the specified error, appending information about the last X error
//
void
_glfwInputErrorX11(int error, const char *message) {
char buffer[_GLFW_MESSAGE_SIZE];
XGetErrorText(_glfw.x11.display, _glfw.x11.errorCode, buffer, sizeof(buffer));
_glfwInputError(error, "%s: %s", message, buffer);
}
// Creates a native cursor object from the specified image and hotspot
//
Cursor
_glfwCreateCursorX11(const GLFWimage *image, int xhot, int yhot) {
int i;
Cursor cursor;
if (!_glfw.x11.xcursor.handle) return None;
XcursorImage *native = XcursorImageCreate(image->width, image->height);
if (native == NULL) return None;
native->xhot = xhot;
native->yhot = yhot;
unsigned char *source = (unsigned char *)image->pixels;
XcursorPixel *target = native->pixels;
for (i = 0; i < image->width * image->height; i++, target++, source += 4) {
unsigned int alpha = source[3];
*target = (alpha << 24) | ((unsigned char)((source[0] * alpha) / 255) << 16) | ((unsigned char)((source[1] * alpha) / 255) << 8) |
((unsigned char)((source[2] * alpha) / 255) << 0);
}
cursor = XcursorImageLoadCursor(_glfw.x11.display, native);
XcursorImageDestroy(native);
return cursor;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI GLFWColorScheme
glfwGetCurrentSystemColorTheme(bool query_if_unintialized) {
return glfw_current_system_color_theme(query_if_unintialized);
}
void
_glfwPlatformInputColorScheme(GLFWColorScheme appearance UNUSED) {}
int
_glfwPlatformInit(bool *supports_window_occlusion) {
*supports_window_occlusion = false;
XInitThreads();
XrmInitialize();
_glfw.x11.display = XOpenDisplay(NULL);
if (!_glfw.x11.display) {
const char *display = getenv("DISPLAY");
if (display && display[0]) {
_glfwInputError(GLFW_PLATFORM_ERROR, "X11: Failed to open display %s", display);
} else {
_glfwInputError(GLFW_PLATFORM_ERROR, "X11: The DISPLAY environment variable is missing");
}
return false;
}
if (!initPollData(&_glfw.x11.eventLoopData, ConnectionNumber(_glfw.x11.display))) {
_glfwInputError(GLFW_PLATFORM_ERROR, "X11: Failed to initialize event loop data");
}
glfw_dbus_init(&_glfw.x11.dbus, &_glfw.x11.eventLoopData);
glfw_initialize_desktop_settings(); // needed for color scheme change notification
_glfw.x11.screen = DefaultScreen(_glfw.x11.display);
_glfw.x11.root = RootWindow(_glfw.x11.display, _glfw.x11.screen);
_glfw.x11.context = XUniqueContext();
_glfw.x11.RESOURCE_MANAGER = XInternAtom(_glfw.x11.display, "RESOURCE_MANAGER", True);
_glfw.x11._KDE_NET_WM_BLUR_BEHIND_REGION = None;
XSelectInput(_glfw.x11.display, _glfw.x11.root, PropertyChangeMask);
_glfwGetSystemContentScaleX11(&_glfw.x11.contentScaleX, &_glfw.x11.contentScaleY, false);
if (!initExtensions()) return false;
_glfw.x11.helperWindowHandle = createHelperWindow();
_glfw.x11.hiddenCursorHandle = createHiddenCursor();
_glfwPollMonitorsX11();
return true;
}
void
_glfwPlatformTerminate(void) {
removeAllTimers(&_glfw.x11.eventLoopData);
if (_glfw.x11.helperWindowHandle) {
if (XGetSelectionOwner(_glfw.x11.display, _glfw.x11.CLIPBOARD) == _glfw.x11.helperWindowHandle) { _glfwPushSelectionToManagerX11(); }
XDestroyWindow(_glfw.x11.display, _glfw.x11.helperWindowHandle);
_glfw.x11.helperWindowHandle = None;
}
if (_glfw.x11.hiddenCursorHandle) {
XFreeCursor(_glfw.x11.display, _glfw.x11.hiddenCursorHandle);
_glfw.x11.hiddenCursorHandle = (Cursor)0;
}
glfw_xkb_release(&_glfw.x11.xkb);
glfw_dbus_terminate(&_glfw.x11.dbus);
if (_glfw.x11.mime_atoms.array) {
for (size_t i = 0; i < _glfw.x11.mime_atoms.sz; i++) { free((void *)_glfw.x11.mime_atoms.array[i].mime); }
free(_glfw.x11.mime_atoms.array);
}
if (_glfw.x11.clipboard_atoms.array) { free(_glfw.x11.clipboard_atoms.array); }
if (_glfw.x11.primary_atoms.array) { free(_glfw.x11.primary_atoms.array); }
free_dnd_data();
if (_glfw.x11.display) {
XCloseDisplay(_glfw.x11.display);
_glfw.x11.display = NULL;
_glfw.x11.eventLoopData.fds[0].fd = -1;
}
if (_glfw.x11.xcursor.handle) {
_glfw_dlclose(_glfw.x11.xcursor.handle);
_glfw.x11.xcursor.handle = NULL;
}
if (_glfw.x11.randr.handle) {
_glfw_dlclose(_glfw.x11.randr.handle);
_glfw.x11.randr.handle = NULL;
}
if (_glfw.x11.xinerama.handle) {
_glfw_dlclose(_glfw.x11.xinerama.handle);
_glfw.x11.xinerama.handle = NULL;
}
if (_glfw.x11.xrender.handle) {
_glfw_dlclose(_glfw.x11.xrender.handle);
_glfw.x11.xrender.handle = NULL;
}
if (_glfw.x11.vidmode.handle) {
_glfw_dlclose(_glfw.x11.vidmode.handle);
_glfw.x11.vidmode.handle = NULL;
}
if (_glfw.x11.xi.handle) {
_glfw_dlclose(_glfw.x11.xi.handle);
_glfw.x11.xi.handle = NULL;
}
// NOTE: These need to be unloaded after XCloseDisplay, as they register
// cleanup callbacks that get called by that function
_glfwTerminateEGL();
_glfwTerminateGLX();
finalizePollData(&_glfw.x11.eventLoopData);
}
const char *
_glfwPlatformGetVersionString(void) {
return _GLFW_VERSION_NUMBER " X11 GLX EGL OSMesa"
#if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
" clock_gettime"
#else
" gettimeofday"
#endif
#if defined(__linux__)
" evdev"
#endif
#if defined(_GLFW_BUILD_DLL)
" shared"
#endif
;
}
#include "main_loop.h"
+493
View File
@@ -0,0 +1,493 @@
//========================================================================
// GLFW 3.4 X11 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================
#include "internal.h"
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
// Check whether the display mode should be included in enumeration
//
static bool
modeIsGood(const XRRModeInfo *mi) {
return (mi->modeFlags & RR_Interlace) == 0;
}
// Calculates the refresh rate, in Hz, from the specified RandR mode info
//
static int
calculateRefreshRate(const XRRModeInfo *mi) {
if (mi->hTotal && mi->vTotal) return (int)round((double)mi->dotClock / ((double)mi->hTotal * (double)mi->vTotal));
else return 0;
}
// Returns the mode info for a RandR mode XID
//
static const XRRModeInfo *
getModeInfo(const XRRScreenResources *sr, RRMode id) {
for (int i = 0; i < sr->nmode; i++) {
if (sr->modes[i].id == id) return sr->modes + i;
}
return NULL;
}
// Convert RandR mode info to GLFW video mode
//
static GLFWvidmode
vidmodeFromModeInfo(const XRRModeInfo *mi, const XRRCrtcInfo *ci) {
GLFWvidmode mode;
if (ci->rotation == RR_Rotate_90 || ci->rotation == RR_Rotate_270) {
mode.width = mi->height;
mode.height = mi->width;
} else {
mode.width = mi->width;
mode.height = mi->height;
}
mode.refreshRate = calculateRefreshRate(mi);
_glfwSplitBPP(DefaultDepth(_glfw.x11.display, _glfw.x11.screen), &mode.redBits, &mode.greenBits, &mode.blueBits);
return mode;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Poll for changes in the set of connected monitors
//
void
_glfwPollMonitorsX11(void) {
if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken) {
int disconnectedCount, screenCount = 0;
_GLFWmonitor **disconnected = NULL;
XineramaScreenInfo *screens = NULL;
XRRScreenResources *sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root);
RROutput primary = XRRGetOutputPrimary(_glfw.x11.display, _glfw.x11.root);
if (_glfw.x11.xinerama.available) screens = XineramaQueryScreens(_glfw.x11.display, &screenCount);
disconnectedCount = _glfw.monitorCount;
if (disconnectedCount) {
disconnected = calloc(_glfw.monitorCount, sizeof(_GLFWmonitor *));
memcpy(disconnected, _glfw.monitors, _glfw.monitorCount * sizeof(_GLFWmonitor *));
}
for (int i = 0; i < sr->noutput; i++) {
int j, type, widthMM, heightMM;
XRROutputInfo *oi = XRRGetOutputInfo(_glfw.x11.display, sr, sr->outputs[i]);
if (oi->connection != RR_Connected || oi->crtc == None) {
XRRFreeOutputInfo(oi);
continue;
}
for (j = 0; j < disconnectedCount; j++) {
if (disconnected[j] && disconnected[j]->x11.output == sr->outputs[i]) {
disconnected[j] = NULL;
break;
}
}
if (j < disconnectedCount) {
XRRFreeOutputInfo(oi);
continue;
}
XRRCrtcInfo *ci = XRRGetCrtcInfo(_glfw.x11.display, sr, oi->crtc);
if (!ci) {
XRRFreeOutputInfo(oi);
continue;
}
if (ci->rotation == RR_Rotate_90 || ci->rotation == RR_Rotate_270) {
widthMM = oi->mm_height;
heightMM = oi->mm_width;
} else {
widthMM = oi->mm_width;
heightMM = oi->mm_height;
}
if (widthMM <= 0 || heightMM <= 0) {
// HACK: If RandR does not provide a physical size, assume the
// X11 default 96 DPI and calculate from the CRTC viewport
// NOTE: These members are affected by rotation, unlike the mode
// info and output info members
widthMM = (int)(ci->width * 25.4f / 96.f);
heightMM = (int)(ci->height * 25.4f / 96.f);
}
_GLFWmonitor *monitor = _glfwAllocMonitor(oi->name, widthMM, heightMM);
monitor->x11.output = sr->outputs[i];
monitor->x11.crtc = oi->crtc;
for (j = 0; j < screenCount; j++) {
if (screens[j].x_org == ci->x && screens[j].y_org == ci->y && screens[j].width == (short int)ci->width &&
screens[j].height == (short int)ci->height) {
monitor->x11.index = j;
break;
}
}
if (monitor->x11.output == primary) type = _GLFW_INSERT_FIRST;
else type = _GLFW_INSERT_LAST;
_glfwInputMonitor(monitor, GLFW_CONNECTED, type);
XRRFreeOutputInfo(oi);
XRRFreeCrtcInfo(ci);
}
XRRFreeScreenResources(sr);
if (screens) XFree(screens);
for (int i = 0; i < disconnectedCount; i++) {
if (disconnected[i]) _glfwInputMonitor(disconnected[i], GLFW_DISCONNECTED, 0);
}
free(disconnected);
} else {
const int widthMM = DisplayWidthMM(_glfw.x11.display, _glfw.x11.screen);
const int heightMM = DisplayHeightMM(_glfw.x11.display, _glfw.x11.screen);
_glfwInputMonitor(_glfwAllocMonitor("Display", widthMM, heightMM), GLFW_CONNECTED, _GLFW_INSERT_FIRST);
}
}
// Set the current video mode for the specified monitor
//
void
_glfwSetVideoModeX11(_GLFWmonitor *monitor, const GLFWvidmode *desired) {
if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken) {
GLFWvidmode current;
RRMode native = None;
const GLFWvidmode *best = _glfwChooseVideoMode(monitor, desired);
_glfwPlatformGetVideoMode(monitor, &current);
if (_glfwCompareVideoModes(&current, best) == 0) return;
XRRScreenResources *sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root);
XRRCrtcInfo *ci = XRRGetCrtcInfo(_glfw.x11.display, sr, monitor->x11.crtc);
XRROutputInfo *oi = XRRGetOutputInfo(_glfw.x11.display, sr, monitor->x11.output);
for (int i = 0; i < oi->nmode; i++) {
const XRRModeInfo *mi = getModeInfo(sr, oi->modes[i]);
if (!modeIsGood(mi)) continue;
const GLFWvidmode mode = vidmodeFromModeInfo(mi, ci);
if (_glfwCompareVideoModes(best, &mode) == 0) {
native = mi->id;
break;
}
}
if (native) {
if (monitor->x11.oldMode == None) monitor->x11.oldMode = ci->mode;
XRRSetCrtcConfig(_glfw.x11.display, sr, monitor->x11.crtc, CurrentTime, ci->x, ci->y, native, ci->rotation, ci->outputs, ci->noutput);
}
XRRFreeOutputInfo(oi);
XRRFreeCrtcInfo(ci);
XRRFreeScreenResources(sr);
}
}
// Restore the saved (original) video mode for the specified monitor
//
void
_glfwRestoreVideoModeX11(_GLFWmonitor *monitor) {
if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken) {
if (monitor->x11.oldMode == None) return;
XRRScreenResources *sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root);
XRRCrtcInfo *ci = XRRGetCrtcInfo(_glfw.x11.display, sr, monitor->x11.crtc);
XRRSetCrtcConfig(_glfw.x11.display, sr, monitor->x11.crtc, CurrentTime, ci->x, ci->y, monitor->x11.oldMode, ci->rotation, ci->outputs, ci->noutput);
XRRFreeCrtcInfo(ci);
XRRFreeScreenResources(sr);
monitor->x11.oldMode = None;
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
void
_glfwPlatformFreeMonitor(_GLFWmonitor *monitor UNUSED) {}
void
_glfwPlatformGetMonitorPos(_GLFWmonitor *monitor, int *xpos, int *ypos) {
if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken) {
XRRScreenResources *sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root);
XRRCrtcInfo *ci = XRRGetCrtcInfo(_glfw.x11.display, sr, monitor->x11.crtc);
if (ci) {
if (xpos) *xpos = ci->x;
if (ypos) *ypos = ci->y;
XRRFreeCrtcInfo(ci);
}
XRRFreeScreenResources(sr);
}
}
void
_glfwPlatformGetMonitorContentScale(_GLFWmonitor *monitor UNUSED, float *xscale, float *yscale) {
if (xscale) *xscale = _glfw.x11.contentScaleX;
if (yscale) *yscale = _glfw.x11.contentScaleY;
}
MonitorGeometry
_glfwPlatformGetMonitorGeometry(_GLFWmonitor *monitor) {
MonitorGeometry ans = {0};
if (!monitor) return ans;
if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken) {
XRRScreenResources *sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root);
XRRCrtcInfo *ci = XRRGetCrtcInfo(_glfw.x11.display, sr, monitor->x11.crtc);
ans.full.x = ci->x;
ans.full.y = ci->y;
const XRRModeInfo *mi = getModeInfo(sr, ci->mode);
if (ci->rotation == RR_Rotate_90 || ci->rotation == RR_Rotate_270) {
ans.full.width = mi->height;
ans.full.height = mi->width;
} else {
ans.full.width = mi->width;
ans.full.height = mi->height;
}
XRRFreeCrtcInfo(ci);
XRRFreeScreenResources(sr);
} else {
ans.full.width = DisplayWidth(_glfw.x11.display, _glfw.x11.screen);
ans.full.height = DisplayHeight(_glfw.x11.display, _glfw.x11.screen);
}
ans.workarea = *(&ans.full);
if (_glfw.x11.NET_WORKAREA && _glfw.x11.NET_CURRENT_DESKTOP) {
Atom *extents = NULL;
Atom *desktop = NULL;
const unsigned long extentCount = _glfwGetWindowPropertyX11(_glfw.x11.root, _glfw.x11.NET_WORKAREA, XA_CARDINAL, (unsigned char **)&extents);
if (_glfwGetWindowPropertyX11(_glfw.x11.root, _glfw.x11.NET_CURRENT_DESKTOP, XA_CARDINAL, (unsigned char **)&desktop) > 0) {
if (extentCount >= 4 && *desktop < extentCount / 4) {
const int globalX = extents[*desktop * 4 + 0];
const int globalY = extents[*desktop * 4 + 1];
const int globalWidth = extents[*desktop * 4 + 2];
const int globalHeight = extents[*desktop * 4 + 3];
if (ans.workarea.x < globalX) {
ans.workarea.width -= globalX - ans.workarea.x;
ans.workarea.x = globalX;
}
if (ans.workarea.y < globalY) {
ans.workarea.height -= globalY - ans.workarea.y;
ans.workarea.y = globalY;
}
if (ans.workarea.x + ans.workarea.width > globalX + globalWidth) ans.workarea.width = globalX - ans.workarea.x + globalWidth;
if (ans.workarea.y + ans.workarea.height > globalY + globalHeight) ans.workarea.height = globalY - ans.workarea.y + globalHeight;
}
}
if (extents) XFree(extents);
if (desktop) XFree(desktop);
}
return ans;
}
void
_glfwPlatformGetMonitorWorkarea(_GLFWmonitor *monitor, int *xpos, int *ypos, int *width, int *height) {
MonitorGeometry ans = _glfwPlatformGetMonitorGeometry(monitor);
if (xpos) *xpos = ans.workarea.x;
if (ypos) *ypos = ans.workarea.y;
if (width) *width = ans.workarea.width;
if (height) *height = ans.workarea.height;
}
GLFWvidmode *
_glfwPlatformGetVideoModes(_GLFWmonitor *monitor, int *count) {
GLFWvidmode *result;
*count = 0;
if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken) {
XRRScreenResources *sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root);
XRRCrtcInfo *ci = XRRGetCrtcInfo(_glfw.x11.display, sr, monitor->x11.crtc);
XRROutputInfo *oi = XRRGetOutputInfo(_glfw.x11.display, sr, monitor->x11.output);
result = calloc(oi->nmode, sizeof(GLFWvidmode));
for (int i = 0; i < oi->nmode; i++) {
const XRRModeInfo *mi = getModeInfo(sr, oi->modes[i]);
if (!modeIsGood(mi)) continue;
const GLFWvidmode mode = vidmodeFromModeInfo(mi, ci);
int j;
for (j = 0; j < *count; j++) {
if (_glfwCompareVideoModes(result + j, &mode) == 0) break;
}
// Skip duplicate modes
if (j < *count) continue;
(*count)++;
result[*count - 1] = mode;
}
XRRFreeOutputInfo(oi);
XRRFreeCrtcInfo(ci);
XRRFreeScreenResources(sr);
} else {
*count = 1;
result = calloc(1, sizeof(GLFWvidmode));
_glfwPlatformGetVideoMode(monitor, result);
}
return result;
}
bool
_glfwPlatformGetVideoMode(_GLFWmonitor *monitor, GLFWvidmode *mode) {
bool ok = false;
if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken) {
XRRScreenResources *sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root);
XRRCrtcInfo *ci = XRRGetCrtcInfo(_glfw.x11.display, sr, monitor->x11.crtc);
if (ci) {
const XRRModeInfo *mi = getModeInfo(sr, ci->mode);
if (mi) { // mi can be NULL if the monitor has been disconnected
*mode = vidmodeFromModeInfo(mi, ci);
ok = true;
}
XRRFreeCrtcInfo(ci);
}
XRRFreeScreenResources(sr);
} else {
ok = true;
mode->width = DisplayWidth(_glfw.x11.display, _glfw.x11.screen);
mode->height = DisplayHeight(_glfw.x11.display, _glfw.x11.screen);
mode->refreshRate = 0;
_glfwSplitBPP(DefaultDepth(_glfw.x11.display, _glfw.x11.screen), &mode->redBits, &mode->greenBits, &mode->blueBits);
}
return ok;
}
bool
_glfwPlatformGetGammaRamp(_GLFWmonitor *monitor, GLFWgammaramp *ramp) {
if (_glfw.x11.randr.available && !_glfw.x11.randr.gammaBroken) {
const size_t size = XRRGetCrtcGammaSize(_glfw.x11.display, monitor->x11.crtc);
XRRCrtcGamma *gamma = XRRGetCrtcGamma(_glfw.x11.display, monitor->x11.crtc);
_glfwAllocGammaArrays(ramp, size);
memcpy(ramp->red, gamma->red, size * sizeof(unsigned short));
memcpy(ramp->green, gamma->green, size * sizeof(unsigned short));
memcpy(ramp->blue, gamma->blue, size * sizeof(unsigned short));
XRRFreeGamma(gamma);
return true;
} else if (_glfw.x11.vidmode.available) {
int size;
XF86VidModeGetGammaRampSize(_glfw.x11.display, _glfw.x11.screen, &size);
_glfwAllocGammaArrays(ramp, size);
XF86VidModeGetGammaRamp(_glfw.x11.display, _glfw.x11.screen, ramp->size, ramp->red, ramp->green, ramp->blue);
return true;
} else {
_glfwInputError(GLFW_PLATFORM_ERROR, "X11: Gamma ramp access not supported by server");
return false;
}
}
void
_glfwPlatformSetGammaRamp(_GLFWmonitor *monitor, const GLFWgammaramp *ramp) {
if (_glfw.x11.randr.available && !_glfw.x11.randr.gammaBroken) {
if (XRRGetCrtcGammaSize(_glfw.x11.display, monitor->x11.crtc) != (int)ramp->size) {
_glfwInputError(GLFW_PLATFORM_ERROR, "X11: Gamma ramp size must match current ramp size");
return;
}
XRRCrtcGamma *gamma = XRRAllocGamma(ramp->size);
memcpy(gamma->red, ramp->red, ramp->size * sizeof(unsigned short));
memcpy(gamma->green, ramp->green, ramp->size * sizeof(unsigned short));
memcpy(gamma->blue, ramp->blue, ramp->size * sizeof(unsigned short));
XRRSetCrtcGamma(_glfw.x11.display, monitor->x11.crtc, gamma);
XRRFreeGamma(gamma);
} else if (_glfw.x11.vidmode.available) {
XF86VidModeSetGammaRamp(
_glfw.x11.display, _glfw.x11.screen, ramp->size, (unsigned short *)ramp->red, (unsigned short *)ramp->green, (unsigned short *)ramp->blue);
} else {
_glfwInputError(GLFW_PLATFORM_ERROR, "X11: Gamma ramp access not supported by server");
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW native API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI RRCrtc
glfwGetX11Adapter(GLFWmonitor *handle) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(None);
return monitor->x11.crtc;
}
GLFWAPI RROutput
glfwGetX11Monitor(GLFWmonitor *handle) {
_GLFWmonitor *monitor = (_GLFWmonitor *)handle;
assert(monitor != NULL);
_GLFW_REQUIRE_INIT_OR_RETURN(None);
return monitor->x11.output;
}
+570
View File
@@ -0,0 +1,570 @@
//========================================================================
// GLFW 3.4 X11 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <unistd.h>
#include <signal.h>
#include <stdint.h>
#include <dlfcn.h>
#include <poll.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/Xatom.h>
#include <X11/Xcursor/Xcursor.h>
// The xcb library is needed to work with libxkb
#include <X11/Xlib-xcb.h>
// The XRandR extension provides mode setting and gamma control
#include <X11/extensions/Xrandr.h>
// The Xkb extension provides improved keyboard support
#include <X11/XKBlib.h>
// The Xinerama extension provides legacy monitor indices
#include <X11/extensions/Xinerama.h>
// The XInput extension provides raw mouse motion input
#include <X11/extensions/XInput2.h>
// The Shape extension provides custom window shapes
#include <X11/extensions/shape.h>
// The libxkb library is used for improved keyboard support
#include "xkb_glfw.h"
#include "backend_utils.h"
typedef XRRCrtcGamma *(*PFN_XRRAllocGamma)(int);
typedef void (*PFN_XRRFreeCrtcInfo)(XRRCrtcInfo *);
typedef void (*PFN_XRRFreeGamma)(XRRCrtcGamma *);
typedef void (*PFN_XRRFreeOutputInfo)(XRROutputInfo *);
typedef void (*PFN_XRRFreeScreenResources)(XRRScreenResources *);
typedef XRRCrtcGamma *(*PFN_XRRGetCrtcGamma)(Display *, RRCrtc);
typedef int (*PFN_XRRGetCrtcGammaSize)(Display *, RRCrtc);
typedef XRRCrtcInfo *(*PFN_XRRGetCrtcInfo)(Display *, XRRScreenResources *, RRCrtc);
typedef XRROutputInfo *(*PFN_XRRGetOutputInfo)(Display *, XRRScreenResources *, RROutput);
typedef RROutput (*PFN_XRRGetOutputPrimary)(Display *, Window);
typedef XRRScreenResources *(*PFN_XRRGetScreenResourcesCurrent)(Display *, Window);
typedef Bool (*PFN_XRRQueryExtension)(Display *, int *, int *);
typedef Status (*PFN_XRRQueryVersion)(Display *, int *, int *);
typedef void (*PFN_XRRSelectInput)(Display *, Window, int);
typedef Status (*PFN_XRRSetCrtcConfig)(Display *, XRRScreenResources *, RRCrtc, Time, int, int, RRMode, Rotation, RROutput *, int);
typedef void (*PFN_XRRSetCrtcGamma)(Display *, RRCrtc, XRRCrtcGamma *);
typedef int (*PFN_XRRUpdateConfiguration)(XEvent *);
#define XRRAllocGamma _glfw.x11.randr.AllocGamma
#define XRRFreeCrtcInfo _glfw.x11.randr.FreeCrtcInfo
#define XRRFreeGamma _glfw.x11.randr.FreeGamma
#define XRRFreeOutputInfo _glfw.x11.randr.FreeOutputInfo
#define XRRFreeScreenResources _glfw.x11.randr.FreeScreenResources
#define XRRGetCrtcGamma _glfw.x11.randr.GetCrtcGamma
#define XRRGetCrtcGammaSize _glfw.x11.randr.GetCrtcGammaSize
#define XRRGetCrtcInfo _glfw.x11.randr.GetCrtcInfo
#define XRRGetOutputInfo _glfw.x11.randr.GetOutputInfo
#define XRRGetOutputPrimary _glfw.x11.randr.GetOutputPrimary
#define XRRGetScreenResourcesCurrent _glfw.x11.randr.GetScreenResourcesCurrent
#define XRRQueryExtension _glfw.x11.randr.QueryExtension
#define XRRQueryVersion _glfw.x11.randr.QueryVersion
#define XRRSelectInput _glfw.x11.randr.SelectInput
#define XRRSetCrtcConfig _glfw.x11.randr.SetCrtcConfig
#define XRRSetCrtcGamma _glfw.x11.randr.SetCrtcGamma
#define XRRUpdateConfiguration _glfw.x11.randr.UpdateConfiguration
typedef XcursorImage *(*PFN_XcursorImageCreate)(int, int);
typedef void (*PFN_XcursorImageDestroy)(XcursorImage *);
typedef Cursor (*PFN_XcursorImageLoadCursor)(Display *, const XcursorImage *);
#define XcursorImageCreate _glfw.x11.xcursor.ImageCreate
#define XcursorImageDestroy _glfw.x11.xcursor.ImageDestroy
#define XcursorImageLoadCursor _glfw.x11.xcursor.ImageLoadCursor
typedef Bool (*PFN_XineramaIsActive)(Display *);
typedef Bool (*PFN_XineramaQueryExtension)(Display *, int *, int *);
typedef XineramaScreenInfo *(*PFN_XineramaQueryScreens)(Display *, int *);
#define XineramaIsActive _glfw.x11.xinerama.IsActive
#define XineramaQueryExtension _glfw.x11.xinerama.QueryExtension
#define XineramaQueryScreens _glfw.x11.xinerama.QueryScreens
typedef Bool (*PFN_XF86VidModeQueryExtension)(Display *, int *, int *);
typedef Bool (*PFN_XF86VidModeGetGammaRamp)(Display *, int, int, unsigned short *, unsigned short *, unsigned short *);
typedef Bool (*PFN_XF86VidModeSetGammaRamp)(Display *, int, int, unsigned short *, unsigned short *, unsigned short *);
typedef Bool (*PFN_XF86VidModeGetGammaRampSize)(Display *, int, int *);
#define XF86VidModeQueryExtension _glfw.x11.vidmode.QueryExtension
#define XF86VidModeGetGammaRamp _glfw.x11.vidmode.GetGammaRamp
#define XF86VidModeSetGammaRamp _glfw.x11.vidmode.SetGammaRamp
#define XF86VidModeGetGammaRampSize _glfw.x11.vidmode.GetGammaRampSize
typedef Status (*PFN_XIQueryVersion)(Display *, int *, int *);
typedef int (*PFN_XISelectEvents)(Display *, Window, XIEventMask *, int);
typedef XIDeviceInfo *(*PFN_XIQueryDevice)(Display *, int, int *);
typedef void (*PFN_XIFreeDeviceInfo)(XIDeviceInfo *);
typedef Status (*PFN_XIGetProperty)(
Display *dpy,
int deviceid,
Atom property,
long offset,
long length,
Bool delete_property,
Atom type,
Atom *type_return,
int *format_return,
unsigned long *num_items_return,
unsigned long *bytes_after_return,
unsigned char **data);
#define XIQueryVersion _glfw.x11.xi.QueryVersion
#define XISelectEvents _glfw.x11.xi.SelectEvents
#define XIQueryDevice _glfw.x11.xi.QueryDevice
#define XIFreeDeviceInfo _glfw.x11.xi.FreeDeviceInfo
#define XIGetProperty _glfw.x11.xi.GetProperty
typedef Bool (*PFN_XRenderQueryExtension)(Display *, int *, int *);
typedef Status (*PFN_XRenderQueryVersion)(Display *dpy, int *, int *);
typedef XRenderPictFormat *(*PFN_XRenderFindVisualFormat)(Display *, Visual const *);
#define XRenderQueryExtension _glfw.x11.xrender.QueryExtension
#define XRenderQueryVersion _glfw.x11.xrender.QueryVersion
#define XRenderFindVisualFormat _glfw.x11.xrender.FindVisualFormat
typedef Bool (*PFN_XShapeQueryExtension)(Display *, int *, int *);
typedef Status (*PFN_XShapeQueryVersion)(Display *dpy, int *, int *);
typedef void (*PFN_XShapeCombineRegion)(Display *, Window, int, int, int, Region, int);
typedef void (*PFN_XShapeCombineMask)(Display *, Window, int, int, int, Pixmap, int);
#define XShapeQueryExtension _glfw.x11.xshape.QueryExtension
#define XShapeQueryVersion _glfw.x11.xshape.QueryVersion
#define XShapeCombineRegion _glfw.x11.xshape.ShapeCombineRegion
#define XShapeCombineMask _glfw.x11.xshape.ShapeCombineMask
typedef VkFlags VkXlibSurfaceCreateFlagsKHR;
typedef VkFlags VkXcbSurfaceCreateFlagsKHR;
typedef struct VkXlibSurfaceCreateInfoKHR {
VkStructureType sType;
const void *pNext;
VkXlibSurfaceCreateFlagsKHR flags;
Display *dpy;
Window window;
} VkXlibSurfaceCreateInfoKHR;
typedef struct VkXcbSurfaceCreateInfoKHR {
VkStructureType sType;
const void *pNext;
VkXcbSurfaceCreateFlagsKHR flags;
xcb_connection_t *connection;
xcb_window_t window;
} VkXcbSurfaceCreateInfoKHR;
typedef VkResult(APIENTRY *PFN_vkCreateXlibSurfaceKHR)(VkInstance, const VkXlibSurfaceCreateInfoKHR *, const VkAllocationCallbacks *, VkSurfaceKHR *);
typedef VkBool32(APIENTRY *PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR)(VkPhysicalDevice, uint32_t, Display *, VisualID);
typedef VkResult(APIENTRY *PFN_vkCreateXcbSurfaceKHR)(VkInstance, const VkXcbSurfaceCreateInfoKHR *, const VkAllocationCallbacks *, VkSurfaceKHR *);
typedef VkBool32(APIENTRY *PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR)(VkPhysicalDevice, uint32_t, xcb_connection_t *, xcb_visualid_t);
#include "posix_thread.h"
#include "glx_context.h"
#if defined(__linux__)
#include "linux_joystick.h"
#else
#include "null_joystick.h"
#endif
#define _glfw_dlopen(name) dlopen(name, RTLD_LAZY | RTLD_LOCAL)
#define _glfw_dlclose(handle) dlclose(handle)
#define _glfw_dlsym(handle, name) dlsym(handle, name)
#define _GLFW_PLATFORM_WINDOW_STATE _GLFWwindowX11 x11
#define _GLFW_PLATFORM_LIBRARY_WINDOW_STATE _GLFWlibraryX11 x11
#define _GLFW_PLATFORM_MONITOR_STATE _GLFWmonitorX11 x11
#define _GLFW_PLATFORM_CURSOR_STATE _GLFWcursorX11 x11
// X11-specific per-window data
//
typedef struct _GLFWwindowX11 {
Colormap colormap;
Window handle;
Window parent;
bool iconified;
bool maximized;
// Whether the visual supports framebuffer transparency
bool transparent;
// Cached position and size used to filter out duplicate events
int width, height;
int xpos, ypos;
// The last received cursor position, regardless of source
int lastCursorPosX, lastCursorPosY;
// The last position the cursor was warped to by GLFW
int warpCursorPosX, warpCursorPosY;
// XI2 smooth scrolling - track valuator values per window
struct {
double verticalValue;
double horizontalValue;
} smoothScroll;
struct {
bool is_active;
GLFWLayerShellConfig config;
} layer_shell;
} _GLFWwindowX11;
typedef struct MimeAtom {
Atom atom;
const char *mime;
} MimeAtom;
typedef struct AtomArray {
MimeAtom *array;
size_t sz, capacity;
} AtomArray;
typedef struct XIScrollValuator {
double increment, value, min, max;
int number, resolution, mode;
bool is_vertical, initialized, has_value;
} XIScrollValuator;
typedef struct XIScrollDevice {
bool is_finger_based;
bool type_detected;
int deviceid, sourceid;
XIScrollValuator valuators[8];
unsigned num_valuators;
char name[32];
unsigned num_events;
GLFWOffsetType offset_type;
bool v120_offset_needs_scaling;
} XIScrollDevice;
typedef struct XdndSelectionRequest {
char *mime;
bool inflight, got_data;
unsigned char *data;
size_t offset, size;
} XdndSelectionRequest;
// X11-specific global data
//
typedef struct _GLFWlibraryX11 {
Display *display;
int screen;
Window root;
// System content scale
float contentScaleX, contentScaleY;
// Helper window for IPC
Window helperWindowHandle;
// Invisible cursor for hidden cursor mode
Cursor hiddenCursorHandle;
// Context for mapping window XIDs to _GLFWwindow pointers
XContext context;
// Most recent error code received by X error handler
int errorCode;
// Where to place the cursor when re-enabled
double restoreCursorPosX, restoreCursorPosY;
// The window whose disabled cursor mode is active
_GLFWwindow *disabledCursorWindow;
// Window manager atoms
Atom NET_SUPPORTED;
Atom NET_SUPPORTING_WM_CHECK;
Atom WM_PROTOCOLS;
Atom WM_STATE;
Atom WM_DELETE_WINDOW;
Atom NET_WM_NAME;
Atom NET_WM_ALLOWED_ACTIONS, NET_WM_ACTION_MOVE, NET_WM_ACTION_RESIZE, NET_WM_ACTION_MINIMIZE, NET_WM_ACTION_SHADE, NET_WM_ACTION_STICK,
NET_WM_ACTION_MAXIMIZE_HORZ, NET_WM_ACTION_MAXIMIZE_VERT, NET_WM_ACTION_FULLSCREEN, NET_WM_ACTION_CHANGE_DESKTOP, NET_WM_ACTION_CLOSE,
NET_WM_ACTION_ABOVE, NET_WM_ACTION_BELOW, NET_WM_ACTION_ABOVE_BELOW;
Atom NET_WM_ICON_NAME;
Atom NET_WM_ICON;
Atom NET_WM_PID;
Atom NET_WM_PING;
Atom NET_WM_WINDOW_TYPE, NET_WM_WINDOW_TYPE_NORMAL, NET_WM_WINDOW_TYPE_DOCK, NET_WM_WINDOW_TYPE_DESKTOP, NET_WM_WINDOW_TYPE_UTILITY,
NET_WM_WINDOW_TYPE_SPLASH, NET_WM_WINDOW_TYPE_DIALOG, NET_WM_WINDOW_TYPE_MENU, NET_WM_WINDOW_TYPE_NOTIFICATION;
Atom NET_WM_STATE;
Atom NET_WM_STATE_ABOVE;
Atom NET_WM_STATE_BELOW;
Atom NET_WM_STATE_FULLSCREEN;
Atom NET_WM_STATE_MAXIMIZED_VERT;
Atom NET_WM_STATE_MAXIMIZED_HORZ;
Atom NET_WM_STATE_DEMANDS_ATTENTION;
Atom NET_WM_STATE_SKIP_TASKBAR;
Atom NET_WM_STATE_SKIP_PAGER;
Atom NET_WM_STATE_STICKY;
Atom NET_WM_BYPASS_COMPOSITOR;
Atom NET_WM_FULLSCREEN_MONITORS;
Atom NET_WM_WINDOW_OPACITY;
Atom NET_WM_CM_Sx;
Atom NET_WORKAREA;
Atom NET_CURRENT_DESKTOP;
Atom NET_ACTIVE_WINDOW;
Atom NET_FRAME_EXTENTS;
Atom NET_REQUEST_FRAME_EXTENTS;
Atom NET_WM_STRUT_PARTIAL;
Atom MOTIF_WM_HINTS;
// Xdnd (drag and drop) atoms
Atom XdndAware;
Atom XdndEnter;
Atom XdndPosition;
Atom XdndStatus;
Atom XdndActionCopy;
Atom XdndActionMove;
Atom XdndActionLink;
Atom XdndDrop;
Atom XdndFinished;
Atom XdndSelection;
Atom XdndTypeList;
Atom XdndActionList;
Atom XdndActionAsk;
Atom XdndLeave;
Atom XdndProxy;
// Selection (clipboard) atoms
Atom TARGETS;
Atom MULTIPLE;
Atom INCR;
Atom CLIPBOARD;
Atom PRIMARY;
Atom CLIPBOARD_MANAGER;
Atom SAVE_TARGETS;
Atom NULL_;
Atom UTF8_STRING;
Atom COMPOUND_STRING;
Atom ATOM_PAIR;
Atom GLFW_SELECTION;
// XRM database atom
Atom RESOURCE_MANAGER;
// KDE window blur
Atom _KDE_NET_WM_BLUR_BEHIND_REGION;
// Atoms for MIME types
AtomArray mime_atoms, clipboard_atoms, primary_atoms;
struct {
bool available;
void *handle;
int eventBase;
int errorBase;
int major;
int minor;
bool gammaBroken;
bool monitorBroken;
PFN_XRRAllocGamma AllocGamma;
PFN_XRRFreeCrtcInfo FreeCrtcInfo;
PFN_XRRFreeGamma FreeGamma;
PFN_XRRFreeOutputInfo FreeOutputInfo;
PFN_XRRFreeScreenResources FreeScreenResources;
PFN_XRRGetCrtcGamma GetCrtcGamma;
PFN_XRRGetCrtcGammaSize GetCrtcGammaSize;
PFN_XRRGetCrtcInfo GetCrtcInfo;
PFN_XRRGetOutputInfo GetOutputInfo;
PFN_XRRGetOutputPrimary GetOutputPrimary;
PFN_XRRGetScreenResourcesCurrent GetScreenResourcesCurrent;
PFN_XRRQueryExtension QueryExtension;
PFN_XRRQueryVersion QueryVersion;
PFN_XRRSelectInput SelectInput;
PFN_XRRSetCrtcConfig SetCrtcConfig;
PFN_XRRSetCrtcGamma SetCrtcGamma;
PFN_XRRUpdateConfiguration UpdateConfiguration;
} randr;
_GLFWXKBData xkb;
_GLFWDBUSData dbus;
struct {
int count;
int timeout;
int interval;
int blanking;
int exposure;
} saver;
struct {
int version;
Window source;
char format[256];
int format_priority;
Window target_window; // For drag events: the window being dragged over
const char **mimes; // Cached MIME types from drag enter (original, never reordered)
size_t mimes_count; // Count of MIME types (full original list, never reduced)
const char **copy_mimes; // Working copy passed to callbacks; pointers into mimes[]
size_t copy_mimes_count; // Accepted count after last callback
bool drag_accepted; // Whether the callback accepted at least one MIME type
bool from_self, dropped;
Time drop_time;
XdndSelectionRequest *selection_requests;
size_t selection_requests_count, selection_requests_capacity;
} xdnd;
// Drag source state
struct {
Window source_window;
Atom *type_atoms; // Atoms for each MIME type
size_t type_count;
Atom action_atom; // XdndActionCopy, XdndActionMove, or XdndActionLink
bool active; // Whether a drag is currently active
Window current_target; // Current drop target window under cursor
Window proxy_target; // Proxy target if current_target has XdndProxy
int xdnd_version; // Xdnd version supported by current target
bool waiting_for_status; // Waiting for XdndStatus from target
bool accepted; // Whether target accepted the drag
Atom accepted_action; // Action accepted by target
struct {
const char *mime_type;
Window requestor;
Atom property;
Atom target;
bool inflight;
} *pending_requests;
size_t pending_count;
size_t pending_capacity;
// Thumbnail window for drag icon
Window thumbnail_window;
Pixmap thumbnail_pixmap;
GC thumbnail_gc;
} drag;
struct {
void *handle;
PFN_XcursorImageCreate ImageCreate;
PFN_XcursorImageDestroy ImageDestroy;
PFN_XcursorImageLoadCursor ImageLoadCursor;
} xcursor;
struct {
bool available;
void *handle;
int major;
int minor;
PFN_XineramaIsActive IsActive;
PFN_XineramaQueryExtension QueryExtension;
PFN_XineramaQueryScreens QueryScreens;
} xinerama;
struct {
bool available;
void *handle;
int eventBase;
int errorBase;
PFN_XF86VidModeQueryExtension QueryExtension;
PFN_XF86VidModeGetGammaRamp GetGammaRamp;
PFN_XF86VidModeSetGammaRamp SetGammaRamp;
PFN_XF86VidModeGetGammaRampSize GetGammaRampSize;
} vidmode;
struct {
bool available;
void *handle;
int majorOpcode;
int eventBase;
int errorBase;
int major;
int minor;
PFN_XIQueryVersion QueryVersion;
PFN_XISelectEvents SelectEvents;
PFN_XIQueryDevice QueryDevice;
PFN_XIFreeDeviceInfo FreeDeviceInfo;
PFN_XIGetProperty GetProperty;
XIScrollDevice scroll_devices[16];
unsigned num_scroll_devices;
// Server timestamp of the last XI_Motion event that carried scroll
// valuators. The X server stamps the wheel button events it emulates
// from those valuators with the same time.
Time last_smooth_scroll_time;
int master_pointer_id;
Atom LIBINPUT_SCROLL_METHOD_ENABLED, LIBINPUT_TAPPING;
} xi;
struct {
bool available;
void *handle;
int major;
int minor;
int eventBase;
int errorBase;
PFN_XRenderQueryExtension QueryExtension;
PFN_XRenderQueryVersion QueryVersion;
PFN_XRenderFindVisualFormat FindVisualFormat;
} xrender;
struct {
bool available;
void *handle;
int major;
int minor;
int eventBase;
int errorBase;
PFN_XShapeQueryExtension QueryExtension;
PFN_XShapeCombineRegion ShapeCombineRegion;
PFN_XShapeQueryVersion QueryVersion;
PFN_XShapeCombineMask ShapeCombineMask;
} xshape;
EventLoopData eventLoopData;
} _GLFWlibraryX11;
// X11-specific per-monitor data
//
typedef struct _GLFWmonitorX11 {
RROutput output;
RRCrtc crtc;
RRMode oldMode;
// Index of corresponding Xinerama screen,
// for EWMH full screen window placement
int index;
} _GLFWmonitorX11;
// X11-specific per-cursor data
//
typedef struct _GLFWcursorX11 {
Cursor handle;
} _GLFWcursorX11;
void _glfwPollMonitorsX11(void);
void _glfwSetVideoModeX11(_GLFWmonitor *monitor, const GLFWvidmode *desired);
void _glfwRestoreVideoModeX11(_GLFWmonitor *monitor);
Cursor _glfwCreateCursorX11(const GLFWimage *image, int xhot, int yhot);
unsigned long _glfwGetWindowPropertyX11(Window window, Atom property, Atom type, unsigned char **value);
bool _glfwIsVisualTransparentX11(Visual *visual);
void _glfwGrabErrorHandlerX11(void);
void _glfwReleaseErrorHandlerX11(void);
void _glfwInputErrorX11(int error, const char *message);
void _glfwGetSystemContentScaleX11(float *xscale, float *yscale, bool bypass_cache);
void _glfwPushSelectionToManagerX11(void);
void read_xi_scroll_devices(void);
void free_dnd_data(void);
+4106
View File
File diff suppressed because it is too large. Load diff
+830
View File
@@ -0,0 +1,830 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include <stdint.h>
#include <xkbcommon/xkbcommon.h>
// needed for xkbcommon < 1.0
/* We don't use the uint32_t types here, to save some space. */
struct codepair {
uint16_t keysym;
uint16_t ucs;
};
static const struct codepair keysymtab[] = {
{0x01a1, 0x0104}, /* Aogonek Ą LATIN CAPITAL LETTER A WITH OGONEK */
{0x01a2, 0x02d8}, /* breve ˘ BREVE */
{0x01a3, 0x0141}, /* Lstroke Ł LATIN CAPITAL LETTER L WITH STROKE */
{0x01a5, 0x013d}, /* Lcaron Ľ LATIN CAPITAL LETTER L WITH CARON */
{0x01a6, 0x015a}, /* Sacute Ś LATIN CAPITAL LETTER S WITH ACUTE */
{0x01a9, 0x0160}, /* Scaron Š LATIN CAPITAL LETTER S WITH CARON */
{0x01aa, 0x015e}, /* Scedilla Ş LATIN CAPITAL LETTER S WITH CEDILLA */
{0x01ab, 0x0164}, /* Tcaron Ť LATIN CAPITAL LETTER T WITH CARON */
{0x01ac, 0x0179}, /* Zacute Ź LATIN CAPITAL LETTER Z WITH ACUTE */
{0x01ae, 0x017d}, /* Zcaron Ž LATIN CAPITAL LETTER Z WITH CARON */
{0x01af, 0x017b}, /* Zabovedot Ż LATIN CAPITAL LETTER Z WITH DOT ABOVE */
{0x01b1, 0x0105}, /* aogonek ą LATIN SMALL LETTER A WITH OGONEK */
{0x01b2, 0x02db}, /* ogonek ˛ OGONEK */
{0x01b3, 0x0142}, /* lstroke ł LATIN SMALL LETTER L WITH STROKE */
{0x01b5, 0x013e}, /* lcaron ľ LATIN SMALL LETTER L WITH CARON */
{0x01b6, 0x015b}, /* sacute ś LATIN SMALL LETTER S WITH ACUTE */
{0x01b7, 0x02c7}, /* caron ˇ CARON */
{0x01b9, 0x0161}, /* scaron š LATIN SMALL LETTER S WITH CARON */
{0x01ba, 0x015f}, /* scedilla ş LATIN SMALL LETTER S WITH CEDILLA */
{0x01bb, 0x0165}, /* tcaron ť LATIN SMALL LETTER T WITH CARON */
{0x01bc, 0x017a}, /* zacute ź LATIN SMALL LETTER Z WITH ACUTE */
{0x01bd, 0x02dd}, /* doubleacute ˝ DOUBLE ACUTE ACCENT */
{0x01be, 0x017e}, /* zcaron ž LATIN SMALL LETTER Z WITH CARON */
{0x01bf, 0x017c}, /* zabovedot ż LATIN SMALL LETTER Z WITH DOT ABOVE */
{0x01c0, 0x0154}, /* Racute Ŕ LATIN CAPITAL LETTER R WITH ACUTE */
{0x01c3, 0x0102}, /* Abreve Ă LATIN CAPITAL LETTER A WITH BREVE */
{0x01c5, 0x0139}, /* Lacute Ĺ LATIN CAPITAL LETTER L WITH ACUTE */
{0x01c6, 0x0106}, /* Cacute Ć LATIN CAPITAL LETTER C WITH ACUTE */
{0x01c8, 0x010c}, /* Ccaron Č LATIN CAPITAL LETTER C WITH CARON */
{0x01ca, 0x0118}, /* Eogonek Ę LATIN CAPITAL LETTER E WITH OGONEK */
{0x01cc, 0x011a}, /* Ecaron Ě LATIN CAPITAL LETTER E WITH CARON */
{0x01cf, 0x010e}, /* Dcaron Ď LATIN CAPITAL LETTER D WITH CARON */
{0x01d0, 0x0110}, /* Dstroke Đ LATIN CAPITAL LETTER D WITH STROKE */
{0x01d1, 0x0143}, /* Nacute Ń LATIN CAPITAL LETTER N WITH ACUTE */
{0x01d2, 0x0147}, /* Ncaron Ň LATIN CAPITAL LETTER N WITH CARON */
{0x01d5, 0x0150}, /* Odoubleacute Ő LATIN CAPITAL LETTER O WITH DOUBLE ACUTE */
{0x01d8, 0x0158}, /* Rcaron Ř LATIN CAPITAL LETTER R WITH CARON */
{0x01d9, 0x016e}, /* Uring Ů LATIN CAPITAL LETTER U WITH RING ABOVE */
{0x01db, 0x0170}, /* Udoubleacute Ű LATIN CAPITAL LETTER U WITH DOUBLE ACUTE */
{0x01de, 0x0162}, /* Tcedilla Ţ LATIN CAPITAL LETTER T WITH CEDILLA */
{0x01e0, 0x0155}, /* racute ŕ LATIN SMALL LETTER R WITH ACUTE */
{0x01e3, 0x0103}, /* abreve ă LATIN SMALL LETTER A WITH BREVE */
{0x01e5, 0x013a}, /* lacute ĺ LATIN SMALL LETTER L WITH ACUTE */
{0x01e6, 0x0107}, /* cacute ć LATIN SMALL LETTER C WITH ACUTE */
{0x01e8, 0x010d}, /* ccaron č LATIN SMALL LETTER C WITH CARON */
{0x01ea, 0x0119}, /* eogonek ę LATIN SMALL LETTER E WITH OGONEK */
{0x01ec, 0x011b}, /* ecaron ě LATIN SMALL LETTER E WITH CARON */
{0x01ef, 0x010f}, /* dcaron ď LATIN SMALL LETTER D WITH CARON */
{0x01f0, 0x0111}, /* dstroke đ LATIN SMALL LETTER D WITH STROKE */
{0x01f1, 0x0144}, /* nacute ń LATIN SMALL LETTER N WITH ACUTE */
{0x01f2, 0x0148}, /* ncaron ň LATIN SMALL LETTER N WITH CARON */
{0x01f5, 0x0151}, /* odoubleacute ő LATIN SMALL LETTER O WITH DOUBLE ACUTE */
{0x01f8, 0x0159}, /* rcaron ř LATIN SMALL LETTER R WITH CARON */
{0x01f9, 0x016f}, /* uring ů LATIN SMALL LETTER U WITH RING ABOVE */
{0x01fb, 0x0171}, /* udoubleacute ű LATIN SMALL LETTER U WITH DOUBLE ACUTE */
{0x01fe, 0x0163}, /* tcedilla ţ LATIN SMALL LETTER T WITH CEDILLA */
{0x01ff, 0x02d9}, /* abovedot ˙ DOT ABOVE */
{0x02a1, 0x0126}, /* Hstroke Ħ LATIN CAPITAL LETTER H WITH STROKE */
{0x02a6, 0x0124}, /* Hcircumflex Ĥ LATIN CAPITAL LETTER H WITH CIRCUMFLEX */
{0x02a9, 0x0130}, /* Iabovedot İ LATIN CAPITAL LETTER I WITH DOT ABOVE */
{0x02ab, 0x011e}, /* Gbreve Ğ LATIN CAPITAL LETTER G WITH BREVE */
{0x02ac, 0x0134}, /* Jcircumflex Ĵ LATIN CAPITAL LETTER J WITH CIRCUMFLEX */
{0x02b1, 0x0127}, /* hstroke ħ LATIN SMALL LETTER H WITH STROKE */
{0x02b6, 0x0125}, /* hcircumflex ĥ LATIN SMALL LETTER H WITH CIRCUMFLEX */
{0x02b9, 0x0131}, /* idotless ı LATIN SMALL LETTER DOTLESS I */
{0x02bb, 0x011f}, /* gbreve ğ LATIN SMALL LETTER G WITH BREVE */
{0x02bc, 0x0135}, /* jcircumflex ĵ LATIN SMALL LETTER J WITH CIRCUMFLEX */
{0x02c5, 0x010a}, /* Cabovedot Ċ LATIN CAPITAL LETTER C WITH DOT ABOVE */
{0x02c6, 0x0108}, /* Ccircumflex Ĉ LATIN CAPITAL LETTER C WITH CIRCUMFLEX */
{0x02d5, 0x0120}, /* Gabovedot Ġ LATIN CAPITAL LETTER G WITH DOT ABOVE */
{0x02d8, 0x011c}, /* Gcircumflex Ĝ LATIN CAPITAL LETTER G WITH CIRCUMFLEX */
{0x02dd, 0x016c}, /* Ubreve Ŭ LATIN CAPITAL LETTER U WITH BREVE */
{0x02de, 0x015c}, /* Scircumflex Ŝ LATIN CAPITAL LETTER S WITH CIRCUMFLEX */
{0x02e5, 0x010b}, /* cabovedot ċ LATIN SMALL LETTER C WITH DOT ABOVE */
{0x02e6, 0x0109}, /* ccircumflex ĉ LATIN SMALL LETTER C WITH CIRCUMFLEX */
{0x02f5, 0x0121}, /* gabovedot ġ LATIN SMALL LETTER G WITH DOT ABOVE */
{0x02f8, 0x011d}, /* gcircumflex ĝ LATIN SMALL LETTER G WITH CIRCUMFLEX */
{0x02fd, 0x016d}, /* ubreve ŭ LATIN SMALL LETTER U WITH BREVE */
{0x02fe, 0x015d}, /* scircumflex ŝ LATIN SMALL LETTER S WITH CIRCUMFLEX */
{0x03a2, 0x0138}, /* kra ĸ LATIN SMALL LETTER KRA */
{0x03a3, 0x0156}, /* Rcedilla Ŗ LATIN CAPITAL LETTER R WITH CEDILLA */
{0x03a5, 0x0128}, /* Itilde Ĩ LATIN CAPITAL LETTER I WITH TILDE */
{0x03a6, 0x013b}, /* Lcedilla Ļ LATIN CAPITAL LETTER L WITH CEDILLA */
{0x03aa, 0x0112}, /* Emacron Ē LATIN CAPITAL LETTER E WITH MACRON */
{0x03ab, 0x0122}, /* Gcedilla Ģ LATIN CAPITAL LETTER G WITH CEDILLA */
{0x03ac, 0x0166}, /* Tslash Ŧ LATIN CAPITAL LETTER T WITH STROKE */
{0x03b3, 0x0157}, /* rcedilla ŗ LATIN SMALL LETTER R WITH CEDILLA */
{0x03b5, 0x0129}, /* itilde ĩ LATIN SMALL LETTER I WITH TILDE */
{0x03b6, 0x013c}, /* lcedilla ļ LATIN SMALL LETTER L WITH CEDILLA */
{0x03ba, 0x0113}, /* emacron ē LATIN SMALL LETTER E WITH MACRON */
{0x03bb, 0x0123}, /* gcedilla ģ LATIN SMALL LETTER G WITH CEDILLA */
{0x03bc, 0x0167}, /* tslash ŧ LATIN SMALL LETTER T WITH STROKE */
{0x03bd, 0x014a}, /* ENG Ŋ LATIN CAPITAL LETTER ENG */
{0x03bf, 0x014b}, /* eng ŋ LATIN SMALL LETTER ENG */
{0x03c0, 0x0100}, /* Amacron Ā LATIN CAPITAL LETTER A WITH MACRON */
{0x03c7, 0x012e}, /* Iogonek Į LATIN CAPITAL LETTER I WITH OGONEK */
{0x03cc, 0x0116}, /* Eabovedot Ė LATIN CAPITAL LETTER E WITH DOT ABOVE */
{0x03cf, 0x012a}, /* Imacron Ī LATIN CAPITAL LETTER I WITH MACRON */
{0x03d1, 0x0145}, /* Ncedilla Ņ LATIN CAPITAL LETTER N WITH CEDILLA */
{0x03d2, 0x014c}, /* Omacron Ō LATIN CAPITAL LETTER O WITH MACRON */
{0x03d3, 0x0136}, /* Kcedilla Ķ LATIN CAPITAL LETTER K WITH CEDILLA */
{0x03d9, 0x0172}, /* Uogonek Ų LATIN CAPITAL LETTER U WITH OGONEK */
{0x03dd, 0x0168}, /* Utilde Ũ LATIN CAPITAL LETTER U WITH TILDE */
{0x03de, 0x016a}, /* Umacron Ū LATIN CAPITAL LETTER U WITH MACRON */
{0x03e0, 0x0101}, /* amacron ā LATIN SMALL LETTER A WITH MACRON */
{0x03e7, 0x012f}, /* iogonek į LATIN SMALL LETTER I WITH OGONEK */
{0x03ec, 0x0117}, /* eabovedot ė LATIN SMALL LETTER E WITH DOT ABOVE */
{0x03ef, 0x012b}, /* imacron ī LATIN SMALL LETTER I WITH MACRON */
{0x03f1, 0x0146}, /* ncedilla ņ LATIN SMALL LETTER N WITH CEDILLA */
{0x03f2, 0x014d}, /* omacron ō LATIN SMALL LETTER O WITH MACRON */
{0x03f3, 0x0137}, /* kcedilla ķ LATIN SMALL LETTER K WITH CEDILLA */
{0x03f9, 0x0173}, /* uogonek ų LATIN SMALL LETTER U WITH OGONEK */
{0x03fd, 0x0169}, /* utilde ũ LATIN SMALL LETTER U WITH TILDE */
{0x03fe, 0x016b}, /* umacron ū LATIN SMALL LETTER U WITH MACRON */
{0x047e, 0x203e}, /* overline ‾ OVERLINE */
{0x04a1, 0x3002}, /* kana_fullstop 。 IDEOGRAPHIC FULL STOP */
{0x04a2, 0x300c}, /* kana_openingbracket 「 LEFT CORNER BRACKET */
{0x04a3, 0x300d}, /* kana_closingbracket 」 RIGHT CORNER BRACKET */
{0x04a4, 0x3001}, /* kana_comma 、 IDEOGRAPHIC COMMA */
{0x04a5, 0x30fb}, /* kana_conjunctive ・ KATAKANA MIDDLE DOT */
{0x04a6, 0x30f2}, /* kana_WO ヲ KATAKANA LETTER WO */
{0x04a7, 0x30a1}, /* kana_a ァ KATAKANA LETTER SMALL A */
{0x04a8, 0x30a3}, /* kana_i ィ KATAKANA LETTER SMALL I */
{0x04a9, 0x30a5}, /* kana_u ゥ KATAKANA LETTER SMALL U */
{0x04aa, 0x30a7}, /* kana_e ェ KATAKANA LETTER SMALL E */
{0x04ab, 0x30a9}, /* kana_o ォ KATAKANA LETTER SMALL O */
{0x04ac, 0x30e3}, /* kana_ya ャ KATAKANA LETTER SMALL YA */
{0x04ad, 0x30e5}, /* kana_yu ュ KATAKANA LETTER SMALL YU */
{0x04ae, 0x30e7}, /* kana_yo ョ KATAKANA LETTER SMALL YO */
{0x04af, 0x30c3}, /* kana_tsu ッ KATAKANA LETTER SMALL TU */
{0x04b0, 0x30fc}, /* prolongedsound ー KATAKANA-HIRAGANA PROLONGED SOUND MARK */
{0x04b1, 0x30a2}, /* kana_A ア KATAKANA LETTER A */
{0x04b2, 0x30a4}, /* kana_I イ KATAKANA LETTER I */
{0x04b3, 0x30a6}, /* kana_U ウ KATAKANA LETTER U */
{0x04b4, 0x30a8}, /* kana_E エ KATAKANA LETTER E */
{0x04b5, 0x30aa}, /* kana_O オ KATAKANA LETTER O */
{0x04b6, 0x30ab}, /* kana_KA カ KATAKANA LETTER KA */
{0x04b7, 0x30ad}, /* kana_KI キ KATAKANA LETTER KI */
{0x04b8, 0x30af}, /* kana_KU ク KATAKANA LETTER KU */
{0x04b9, 0x30b1}, /* kana_KE ケ KATAKANA LETTER KE */
{0x04ba, 0x30b3}, /* kana_KO コ KATAKANA LETTER KO */
{0x04bb, 0x30b5}, /* kana_SA サ KATAKANA LETTER SA */
{0x04bc, 0x30b7}, /* kana_SHI シ KATAKANA LETTER SI */
{0x04bd, 0x30b9}, /* kana_SU ス KATAKANA LETTER SU */
{0x04be, 0x30bb}, /* kana_SE セ KATAKANA LETTER SE */
{0x04bf, 0x30bd}, /* kana_SO ソ KATAKANA LETTER SO */
{0x04c0, 0x30bf}, /* kana_TA タ KATAKANA LETTER TA */
{0x04c1, 0x30c1}, /* kana_CHI チ KATAKANA LETTER TI */
{0x04c2, 0x30c4}, /* kana_TSU ツ KATAKANA LETTER TU */
{0x04c3, 0x30c6}, /* kana_TE テ KATAKANA LETTER TE */
{0x04c4, 0x30c8}, /* kana_TO ト KATAKANA LETTER TO */
{0x04c5, 0x30ca}, /* kana_NA ナ KATAKANA LETTER NA */
{0x04c6, 0x30cb}, /* kana_NI ニ KATAKANA LETTER NI */
{0x04c7, 0x30cc}, /* kana_NU ヌ KATAKANA LETTER NU */
{0x04c8, 0x30cd}, /* kana_NE ネ KATAKANA LETTER NE */
{0x04c9, 0x30ce}, /* kana_NO ノ KATAKANA LETTER NO */
{0x04ca, 0x30cf}, /* kana_HA ハ KATAKANA LETTER HA */
{0x04cb, 0x30d2}, /* kana_HI ヒ KATAKANA LETTER HI */
{0x04cc, 0x30d5}, /* kana_FU フ KATAKANA LETTER HU */
{0x04cd, 0x30d8}, /* kana_HE ヘ KATAKANA LETTER HE */
{0x04ce, 0x30db}, /* kana_HO ホ KATAKANA LETTER HO */
{0x04cf, 0x30de}, /* kana_MA マ KATAKANA LETTER MA */
{0x04d0, 0x30df}, /* kana_MI ミ KATAKANA LETTER MI */
{0x04d1, 0x30e0}, /* kana_MU ム KATAKANA LETTER MU */
{0x04d2, 0x30e1}, /* kana_ME メ KATAKANA LETTER ME */
{0x04d3, 0x30e2}, /* kana_MO モ KATAKANA LETTER MO */
{0x04d4, 0x30e4}, /* kana_YA ヤ KATAKANA LETTER YA */
{0x04d5, 0x30e6}, /* kana_YU ユ KATAKANA LETTER YU */
{0x04d6, 0x30e8}, /* kana_YO ヨ KATAKANA LETTER YO */
{0x04d7, 0x30e9}, /* kana_RA ラ KATAKANA LETTER RA */
{0x04d8, 0x30ea}, /* kana_RI リ KATAKANA LETTER RI */
{0x04d9, 0x30eb}, /* kana_RU ル KATAKANA LETTER RU */
{0x04da, 0x30ec}, /* kana_RE レ KATAKANA LETTER RE */
{0x04db, 0x30ed}, /* kana_RO ロ KATAKANA LETTER RO */
{0x04dc, 0x30ef}, /* kana_WA ワ KATAKANA LETTER WA */
{0x04dd, 0x30f3}, /* kana_N ン KATAKANA LETTER N */
{0x04de, 0x309b}, /* voicedsound ゛ KATAKANA-HIRAGANA VOICED SOUND MARK */
{0x04df, 0x309c}, /* semivoicedsound ゜ KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK */
{0x05ac, 0x060c}, /* Arabic_comma ، ARABIC COMMA */
{0x05bb, 0x061b}, /* Arabic_semicolon ؛ ARABIC SEMICOLON */
{0x05bf, 0x061f}, /* Arabic_question_mark ؟ ARABIC QUESTION MARK */
{0x05c1, 0x0621}, /* Arabic_hamza ء ARABIC LETTER HAMZA */
{0x05c2, 0x0622}, /* Arabic_maddaonalef آ ARABIC LETTER ALEF WITH MADDA ABOVE */
{0x05c3, 0x0623}, /* Arabic_hamzaonalef أ ARABIC LETTER ALEF WITH HAMZA ABOVE */
{0x05c4, 0x0624}, /* Arabic_hamzaonwaw ؤ ARABIC LETTER WAW WITH HAMZA ABOVE */
{0x05c5, 0x0625}, /* Arabic_hamzaunderalef إ ARABIC LETTER ALEF WITH HAMZA BELOW */
{0x05c6, 0x0626}, /* Arabic_hamzaonyeh ئ ARABIC LETTER YEH WITH HAMZA ABOVE */
{0x05c7, 0x0627}, /* Arabic_alef ا ARABIC LETTER ALEF */
{0x05c8, 0x0628}, /* Arabic_beh ب ARABIC LETTER BEH */
{0x05c9, 0x0629}, /* Arabic_tehmarbuta ة ARABIC LETTER TEH MARBUTA */
{0x05ca, 0x062a}, /* Arabic_teh ت ARABIC LETTER TEH */
{0x05cb, 0x062b}, /* Arabic_theh ث ARABIC LETTER THEH */
{0x05cc, 0x062c}, /* Arabic_jeem ج ARABIC LETTER JEEM */
{0x05cd, 0x062d}, /* Arabic_hah ح ARABIC LETTER HAH */
{0x05ce, 0x062e}, /* Arabic_khah خ ARABIC LETTER KHAH */
{0x05cf, 0x062f}, /* Arabic_dal د ARABIC LETTER DAL */
{0x05d0, 0x0630}, /* Arabic_thal ذ ARABIC LETTER THAL */
{0x05d1, 0x0631}, /* Arabic_ra ر ARABIC LETTER REH */
{0x05d2, 0x0632}, /* Arabic_zain ز ARABIC LETTER ZAIN */
{0x05d3, 0x0633}, /* Arabic_seen س ARABIC LETTER SEEN */
{0x05d4, 0x0634}, /* Arabic_sheen ش ARABIC LETTER SHEEN */
{0x05d5, 0x0635}, /* Arabic_sad ص ARABIC LETTER SAD */
{0x05d6, 0x0636}, /* Arabic_dad ض ARABIC LETTER DAD */
{0x05d7, 0x0637}, /* Arabic_tah ط ARABIC LETTER TAH */
{0x05d8, 0x0638}, /* Arabic_zah ظ ARABIC LETTER ZAH */
{0x05d9, 0x0639}, /* Arabic_ain ع ARABIC LETTER AIN */
{0x05da, 0x063a}, /* Arabic_ghain غ ARABIC LETTER GHAIN */
{0x05e0, 0x0640}, /* Arabic_tatweel ـ ARABIC TATWEEL */
{0x05e1, 0x0641}, /* Arabic_feh ف ARABIC LETTER FEH */
{0x05e2, 0x0642}, /* Arabic_qaf ق ARABIC LETTER QAF */
{0x05e3, 0x0643}, /* Arabic_kaf ك ARABIC LETTER KAF */
{0x05e4, 0x0644}, /* Arabic_lam ل ARABIC LETTER LAM */
{0x05e5, 0x0645}, /* Arabic_meem م ARABIC LETTER MEEM */
{0x05e6, 0x0646}, /* Arabic_noon ن ARABIC LETTER NOON */
{0x05e7, 0x0647}, /* Arabic_ha ه ARABIC LETTER HEH */
{0x05e8, 0x0648}, /* Arabic_waw و ARABIC LETTER WAW */
{0x05e9, 0x0649}, /* Arabic_alefmaksura ى ARABIC LETTER ALEF MAKSURA */
{0x05ea, 0x064a}, /* Arabic_yeh ي ARABIC LETTER YEH */
{0x05eb, 0x064b}, /* Arabic_fathatan ً ARABIC FATHATAN */
{0x05ec, 0x064c}, /* Arabic_dammatan ٌ ARABIC DAMMATAN */
{0x05ed, 0x064d}, /* Arabic_kasratan ٍ ARABIC KASRATAN */
{0x05ee, 0x064e}, /* Arabic_fatha َ ARABIC FATHA */
{0x05ef, 0x064f}, /* Arabic_damma ُ ARABIC DAMMA */
{0x05f0, 0x0650}, /* Arabic_kasra ِ ARABIC KASRA */
{0x05f1, 0x0651}, /* Arabic_shadda ّ ARABIC SHADDA */
{0x05f2, 0x0652}, /* Arabic_sukun ْ ARABIC SUKUN */
{0x06a1, 0x0452}, /* Serbian_dje ђ CYRILLIC SMALL LETTER DJE */
{0x06a2, 0x0453}, /* Macedonia_gje ѓ CYRILLIC SMALL LETTER GJE */
{0x06a3, 0x0451}, /* Cyrillic_io ё CYRILLIC SMALL LETTER IO */
{0x06a4, 0x0454}, /* Ukrainian_ie є CYRILLIC SMALL LETTER UKRAINIAN IE */
{0x06a5, 0x0455}, /* Macedonia_dse ѕ CYRILLIC SMALL LETTER DZE */
{0x06a6, 0x0456}, /* Ukrainian_i і CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I */
{0x06a7, 0x0457}, /* Ukrainian_yi ї CYRILLIC SMALL LETTER YI */
{0x06a8, 0x0458}, /* Cyrillic_je ј CYRILLIC SMALL LETTER JE */
{0x06a9, 0x0459}, /* Cyrillic_lje љ CYRILLIC SMALL LETTER LJE */
{0x06aa, 0x045a}, /* Cyrillic_nje њ CYRILLIC SMALL LETTER NJE */
{0x06ab, 0x045b}, /* Serbian_tshe ћ CYRILLIC SMALL LETTER TSHE */
{0x06ac, 0x045c}, /* Macedonia_kje ќ CYRILLIC SMALL LETTER KJE */
{0x06ad, 0x0491}, /* Ukrainian_ghe_with_upturn ґ CYRILLIC SMALL LETTER GHE WITH UPTURN */
{0x06ae, 0x045e}, /* Byelorussian_shortu ў CYRILLIC SMALL LETTER SHORT U */
{0x06af, 0x045f}, /* Cyrillic_dzhe џ CYRILLIC SMALL LETTER DZHE */
{0x06b0, 0x2116}, /* numerosign № NUMERO SIGN */
{0x06b1, 0x0402}, /* Serbian_DJE Ђ CYRILLIC CAPITAL LETTER DJE */
{0x06b2, 0x0403}, /* Macedonia_GJE Ѓ CYRILLIC CAPITAL LETTER GJE */
{0x06b3, 0x0401}, /* Cyrillic_IO Ё CYRILLIC CAPITAL LETTER IO */
{0x06b4, 0x0404}, /* Ukrainian_IE Є CYRILLIC CAPITAL LETTER UKRAINIAN IE */
{0x06b5, 0x0405}, /* Macedonia_DSE Ѕ CYRILLIC CAPITAL LETTER DZE */
{0x06b6, 0x0406}, /* Ukrainian_I І CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I */
{0x06b7, 0x0407}, /* Ukrainian_YI Ї CYRILLIC CAPITAL LETTER YI */
{0x06b8, 0x0408}, /* Cyrillic_JE Ј CYRILLIC CAPITAL LETTER JE */
{0x06b9, 0x0409}, /* Cyrillic_LJE Љ CYRILLIC CAPITAL LETTER LJE */
{0x06ba, 0x040a}, /* Cyrillic_NJE Њ CYRILLIC CAPITAL LETTER NJE */
{0x06bb, 0x040b}, /* Serbian_TSHE Ћ CYRILLIC CAPITAL LETTER TSHE */
{0x06bc, 0x040c}, /* Macedonia_KJE Ќ CYRILLIC CAPITAL LETTER KJE */
{0x06bd, 0x0490}, /* Ukrainian_GHE_WITH_UPTURN Ґ CYRILLIC CAPITAL LETTER GHE WITH UPTURN */
{0x06be, 0x040e}, /* Byelorussian_SHORTU Ў CYRILLIC CAPITAL LETTER SHORT U */
{0x06bf, 0x040f}, /* Cyrillic_DZHE Џ CYRILLIC CAPITAL LETTER DZHE */
{0x06c0, 0x044e}, /* Cyrillic_yu ю CYRILLIC SMALL LETTER YU */
{0x06c1, 0x0430}, /* Cyrillic_a а CYRILLIC SMALL LETTER A */
{0x06c2, 0x0431}, /* Cyrillic_be б CYRILLIC SMALL LETTER BE */
{0x06c3, 0x0446}, /* Cyrillic_tse ц CYRILLIC SMALL LETTER TSE */
{0x06c4, 0x0434}, /* Cyrillic_de д CYRILLIC SMALL LETTER DE */
{0x06c5, 0x0435}, /* Cyrillic_ie е CYRILLIC SMALL LETTER IE */
{0x06c6, 0x0444}, /* Cyrillic_ef ф CYRILLIC SMALL LETTER EF */
{0x06c7, 0x0433}, /* Cyrillic_ghe г CYRILLIC SMALL LETTER GHE */
{0x06c8, 0x0445}, /* Cyrillic_ha х CYRILLIC SMALL LETTER HA */
{0x06c9, 0x0438}, /* Cyrillic_i и CYRILLIC SMALL LETTER I */
{0x06ca, 0x0439}, /* Cyrillic_shorti й CYRILLIC SMALL LETTER SHORT I */
{0x06cb, 0x043a}, /* Cyrillic_ka к CYRILLIC SMALL LETTER KA */
{0x06cc, 0x043b}, /* Cyrillic_el л CYRILLIC SMALL LETTER EL */
{0x06cd, 0x043c}, /* Cyrillic_em м CYRILLIC SMALL LETTER EM */
{0x06ce, 0x043d}, /* Cyrillic_en н CYRILLIC SMALL LETTER EN */
{0x06cf, 0x043e}, /* Cyrillic_o о CYRILLIC SMALL LETTER O */
{0x06d0, 0x043f}, /* Cyrillic_pe п CYRILLIC SMALL LETTER PE */
{0x06d1, 0x044f}, /* Cyrillic_ya я CYRILLIC SMALL LETTER YA */
{0x06d2, 0x0440}, /* Cyrillic_er р CYRILLIC SMALL LETTER ER */
{0x06d3, 0x0441}, /* Cyrillic_es с CYRILLIC SMALL LETTER ES */
{0x06d4, 0x0442}, /* Cyrillic_te т CYRILLIC SMALL LETTER TE */
{0x06d5, 0x0443}, /* Cyrillic_u у CYRILLIC SMALL LETTER U */
{0x06d6, 0x0436}, /* Cyrillic_zhe ж CYRILLIC SMALL LETTER ZHE */
{0x06d7, 0x0432}, /* Cyrillic_ve в CYRILLIC SMALL LETTER VE */
{0x06d8, 0x044c}, /* Cyrillic_softsign ь CYRILLIC SMALL LETTER SOFT SIGN */
{0x06d9, 0x044b}, /* Cyrillic_yeru ы CYRILLIC SMALL LETTER YERU */
{0x06da, 0x0437}, /* Cyrillic_ze з CYRILLIC SMALL LETTER ZE */
{0x06db, 0x0448}, /* Cyrillic_sha ш CYRILLIC SMALL LETTER SHA */
{0x06dc, 0x044d}, /* Cyrillic_e э CYRILLIC SMALL LETTER E */
{0x06dd, 0x0449}, /* Cyrillic_shcha щ CYRILLIC SMALL LETTER SHCHA */
{0x06de, 0x0447}, /* Cyrillic_che ч CYRILLIC SMALL LETTER CHE */
{0x06df, 0x044a}, /* Cyrillic_hardsign ъ CYRILLIC SMALL LETTER HARD SIGN */
{0x06e0, 0x042e}, /* Cyrillic_YU Ю CYRILLIC CAPITAL LETTER YU */
{0x06e1, 0x0410}, /* Cyrillic_A А CYRILLIC CAPITAL LETTER A */
{0x06e2, 0x0411}, /* Cyrillic_BE Б CYRILLIC CAPITAL LETTER BE */
{0x06e3, 0x0426}, /* Cyrillic_TSE Ц CYRILLIC CAPITAL LETTER TSE */
{0x06e4, 0x0414}, /* Cyrillic_DE Д CYRILLIC CAPITAL LETTER DE */
{0x06e5, 0x0415}, /* Cyrillic_IE Е CYRILLIC CAPITAL LETTER IE */
{0x06e6, 0x0424}, /* Cyrillic_EF Ф CYRILLIC CAPITAL LETTER EF */
{0x06e7, 0x0413}, /* Cyrillic_GHE Г CYRILLIC CAPITAL LETTER GHE */
{0x06e8, 0x0425}, /* Cyrillic_HA Х CYRILLIC CAPITAL LETTER HA */
{0x06e9, 0x0418}, /* Cyrillic_I И CYRILLIC CAPITAL LETTER I */
{0x06ea, 0x0419}, /* Cyrillic_SHORTI Й CYRILLIC CAPITAL LETTER SHORT I */
{0x06eb, 0x041a}, /* Cyrillic_KA К CYRILLIC CAPITAL LETTER KA */
{0x06ec, 0x041b}, /* Cyrillic_EL Л CYRILLIC CAPITAL LETTER EL */
{0x06ed, 0x041c}, /* Cyrillic_EM М CYRILLIC CAPITAL LETTER EM */
{0x06ee, 0x041d}, /* Cyrillic_EN Н CYRILLIC CAPITAL LETTER EN */
{0x06ef, 0x041e}, /* Cyrillic_O О CYRILLIC CAPITAL LETTER O */
{0x06f0, 0x041f}, /* Cyrillic_PE П CYRILLIC CAPITAL LETTER PE */
{0x06f1, 0x042f}, /* Cyrillic_YA Я CYRILLIC CAPITAL LETTER YA */
{0x06f2, 0x0420}, /* Cyrillic_ER Р CYRILLIC CAPITAL LETTER ER */
{0x06f3, 0x0421}, /* Cyrillic_ES С CYRILLIC CAPITAL LETTER ES */
{0x06f4, 0x0422}, /* Cyrillic_TE Т CYRILLIC CAPITAL LETTER TE */
{0x06f5, 0x0423}, /* Cyrillic_U У CYRILLIC CAPITAL LETTER U */
{0x06f6, 0x0416}, /* Cyrillic_ZHE Ж CYRILLIC CAPITAL LETTER ZHE */
{0x06f7, 0x0412}, /* Cyrillic_VE В CYRILLIC CAPITAL LETTER VE */
{0x06f8, 0x042c}, /* Cyrillic_SOFTSIGN Ь CYRILLIC CAPITAL LETTER SOFT SIGN */
{0x06f9, 0x042b}, /* Cyrillic_YERU Ы CYRILLIC CAPITAL LETTER YERU */
{0x06fa, 0x0417}, /* Cyrillic_ZE З CYRILLIC CAPITAL LETTER ZE */
{0x06fb, 0x0428}, /* Cyrillic_SHA Ш CYRILLIC CAPITAL LETTER SHA */
{0x06fc, 0x042d}, /* Cyrillic_E Э CYRILLIC CAPITAL LETTER E */
{0x06fd, 0x0429}, /* Cyrillic_SHCHA Щ CYRILLIC CAPITAL LETTER SHCHA */
{0x06fe, 0x0427}, /* Cyrillic_CHE Ч CYRILLIC CAPITAL LETTER CHE */
{0x06ff, 0x042a}, /* Cyrillic_HARDSIGN Ъ CYRILLIC CAPITAL LETTER HARD SIGN */
{0x07a1, 0x0386}, /* Greek_ALPHAaccent Ά GREEK CAPITAL LETTER ALPHA WITH TONOS */
{0x07a2, 0x0388}, /* Greek_EPSILONaccent Έ GREEK CAPITAL LETTER EPSILON WITH TONOS */
{0x07a3, 0x0389}, /* Greek_ETAaccent Ή GREEK CAPITAL LETTER ETA WITH TONOS */
{0x07a4, 0x038a}, /* Greek_IOTAaccent Ί GREEK CAPITAL LETTER IOTA WITH TONOS */
{0x07a5, 0x03aa}, /* Greek_IOTAdiaeresis Ϊ GREEK CAPITAL LETTER IOTA WITH DIALYTIKA */
{0x07a7, 0x038c}, /* Greek_OMICRONaccent Ό GREEK CAPITAL LETTER OMICRON WITH TONOS */
{0x07a8, 0x038e}, /* Greek_UPSILONaccent Ύ GREEK CAPITAL LETTER UPSILON WITH TONOS */
{0x07a9, 0x03ab}, /* Greek_UPSILONdieresis Ϋ GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA */
{0x07ab, 0x038f}, /* Greek_OMEGAaccent Ώ GREEK CAPITAL LETTER OMEGA WITH TONOS */
{0x07ae, 0x0385}, /* Greek_accentdieresis ΅ GREEK DIALYTIKA TONOS */
{0x07af, 0x2015}, /* Greek_horizbar ― HORIZONTAL BAR */
{0x07b1, 0x03ac}, /* Greek_alphaaccent ά GREEK SMALL LETTER ALPHA WITH TONOS */
{0x07b2, 0x03ad}, /* Greek_epsilonaccent έ GREEK SMALL LETTER EPSILON WITH TONOS */
{0x07b3, 0x03ae}, /* Greek_etaaccent ή GREEK SMALL LETTER ETA WITH TONOS */
{0x07b4, 0x03af}, /* Greek_iotaaccent ί GREEK SMALL LETTER IOTA WITH TONOS */
{0x07b5, 0x03ca}, /* Greek_iotadieresis ϊ GREEK SMALL LETTER IOTA WITH DIALYTIKA */
{0x07b6, 0x0390}, /* Greek_iotaaccentdieresis ΐ GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS */
{0x07b7, 0x03cc}, /* Greek_omicronaccent ό GREEK SMALL LETTER OMICRON WITH TONOS */
{0x07b8, 0x03cd}, /* Greek_upsilonaccent ύ GREEK SMALL LETTER UPSILON WITH TONOS */
{0x07b9, 0x03cb}, /* Greek_upsilondieresis ϋ GREEK SMALL LETTER UPSILON WITH DIALYTIKA */
{0x07ba, 0x03b0}, /* Greek_upsilonaccentdieresis ΰ GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS */
{0x07bb, 0x03ce}, /* Greek_omegaaccent ώ GREEK SMALL LETTER OMEGA WITH TONOS */
{0x07c1, 0x0391}, /* Greek_ALPHA Α GREEK CAPITAL LETTER ALPHA */
{0x07c2, 0x0392}, /* Greek_BETA Β GREEK CAPITAL LETTER BETA */
{0x07c3, 0x0393}, /* Greek_GAMMA Γ GREEK CAPITAL LETTER GAMMA */
{0x07c4, 0x0394}, /* Greek_DELTA Δ GREEK CAPITAL LETTER DELTA */
{0x07c5, 0x0395}, /* Greek_EPSILON Ε GREEK CAPITAL LETTER EPSILON */
{0x07c6, 0x0396}, /* Greek_ZETA Ζ GREEK CAPITAL LETTER ZETA */
{0x07c7, 0x0397}, /* Greek_ETA Η GREEK CAPITAL LETTER ETA */
{0x07c8, 0x0398}, /* Greek_THETA Θ GREEK CAPITAL LETTER THETA */
{0x07c9, 0x0399}, /* Greek_IOTA Ι GREEK CAPITAL LETTER IOTA */
{0x07ca, 0x039a}, /* Greek_KAPPA Κ GREEK CAPITAL LETTER KAPPA */
{0x07cb, 0x039b}, /* Greek_LAMBDA Λ GREEK CAPITAL LETTER LAMBDA */
{0x07cc, 0x039c}, /* Greek_MU Μ GREEK CAPITAL LETTER MU */
{0x07cd, 0x039d}, /* Greek_NU Ν GREEK CAPITAL LETTER NU */
{0x07ce, 0x039e}, /* Greek_XI Ξ GREEK CAPITAL LETTER XI */
{0x07cf, 0x039f}, /* Greek_OMICRON Ο GREEK CAPITAL LETTER OMICRON */
{0x07d0, 0x03a0}, /* Greek_PI Π GREEK CAPITAL LETTER PI */
{0x07d1, 0x03a1}, /* Greek_RHO Ρ GREEK CAPITAL LETTER RHO */
{0x07d2, 0x03a3}, /* Greek_SIGMA Σ GREEK CAPITAL LETTER SIGMA */
{0x07d4, 0x03a4}, /* Greek_TAU Τ GREEK CAPITAL LETTER TAU */
{0x07d5, 0x03a5}, /* Greek_UPSILON Υ GREEK CAPITAL LETTER UPSILON */
{0x07d6, 0x03a6}, /* Greek_PHI Φ GREEK CAPITAL LETTER PHI */
{0x07d7, 0x03a7}, /* Greek_CHI Χ GREEK CAPITAL LETTER CHI */
{0x07d8, 0x03a8}, /* Greek_PSI Ψ GREEK CAPITAL LETTER PSI */
{0x07d9, 0x03a9}, /* Greek_OMEGA Ω GREEK CAPITAL LETTER OMEGA */
{0x07e1, 0x03b1}, /* Greek_alpha α GREEK SMALL LETTER ALPHA */
{0x07e2, 0x03b2}, /* Greek_beta β GREEK SMALL LETTER BETA */
{0x07e3, 0x03b3}, /* Greek_gamma γ GREEK SMALL LETTER GAMMA */
{0x07e4, 0x03b4}, /* Greek_delta δ GREEK SMALL LETTER DELTA */
{0x07e5, 0x03b5}, /* Greek_epsilon ε GREEK SMALL LETTER EPSILON */
{0x07e6, 0x03b6}, /* Greek_zeta ζ GREEK SMALL LETTER ZETA */
{0x07e7, 0x03b7}, /* Greek_eta η GREEK SMALL LETTER ETA */
{0x07e8, 0x03b8}, /* Greek_theta θ GREEK SMALL LETTER THETA */
{0x07e9, 0x03b9}, /* Greek_iota ι GREEK SMALL LETTER IOTA */
{0x07ea, 0x03ba}, /* Greek_kappa κ GREEK SMALL LETTER KAPPA */
{0x07eb, 0x03bb}, /* Greek_lambda λ GREEK SMALL LETTER LAMBDA */
{0x07ec, 0x03bc}, /* Greek_mu μ GREEK SMALL LETTER MU */
{0x07ed, 0x03bd}, /* Greek_nu ν GREEK SMALL LETTER NU */
{0x07ee, 0x03be}, /* Greek_xi ξ GREEK SMALL LETTER XI */
{0x07ef, 0x03bf}, /* Greek_omicron ο GREEK SMALL LETTER OMICRON */
{0x07f0, 0x03c0}, /* Greek_pi π GREEK SMALL LETTER PI */
{0x07f1, 0x03c1}, /* Greek_rho ρ GREEK SMALL LETTER RHO */
{0x07f2, 0x03c3}, /* Greek_sigma σ GREEK SMALL LETTER SIGMA */
{0x07f3, 0x03c2}, /* Greek_finalsmallsigma ς GREEK SMALL LETTER FINAL SIGMA */
{0x07f4, 0x03c4}, /* Greek_tau τ GREEK SMALL LETTER TAU */
{0x07f5, 0x03c5}, /* Greek_upsilon υ GREEK SMALL LETTER UPSILON */
{0x07f6, 0x03c6}, /* Greek_phi φ GREEK SMALL LETTER PHI */
{0x07f7, 0x03c7}, /* Greek_chi χ GREEK SMALL LETTER CHI */
{0x07f8, 0x03c8}, /* Greek_psi ψ GREEK SMALL LETTER PSI */
{0x07f9, 0x03c9}, /* Greek_omega ω GREEK SMALL LETTER OMEGA */
{0x08a1, 0x23b7}, /* leftradical ⎷ ??? */
{0x08a2, 0x250c}, /* topleftradical ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT */
{0x08a3, 0x2500}, /* horizconnector ─ BOX DRAWINGS LIGHT HORIZONTAL */
{0x08a4, 0x2320}, /* topintegral ⌠ TOP HALF INTEGRAL */
{0x08a5, 0x2321}, /* botintegral ⌡ BOTTOM HALF INTEGRAL */
{0x08a6, 0x2502}, /* vertconnector │ BOX DRAWINGS LIGHT VERTICAL */
{0x08a7, 0x23a1}, /* topleftsqbracket ⎡ ??? */
{0x08a8, 0x23a3}, /* botleftsqbracket ⎣ ??? */
{0x08a9, 0x23a4}, /* toprightsqbracket ⎤ ??? */
{0x08aa, 0x23a6}, /* botrightsqbracket ⎦ ??? */
{0x08ab, 0x239b}, /* topleftparens ⎛ ??? */
{0x08ac, 0x239d}, /* botleftparens ⎝ ??? */
{0x08ad, 0x239e}, /* toprightparens ⎞ ??? */
{0x08ae, 0x23a0}, /* botrightparens ⎠ ??? */
{0x08af, 0x23a8}, /* leftmiddlecurlybrace ⎨ ??? */
{0x08b0, 0x23ac}, /* rightmiddlecurlybrace ⎬ ??? */
/* 0x08b1 topleftsummation ? ??? */
/* 0x08b2 botleftsummation ? ??? */
/* 0x08b3 topvertsummationconnector ? ??? */
/* 0x08b4 botvertsummationconnector ? ??? */
/* 0x08b5 toprightsummation ? ??? */
/* 0x08b6 botrightsummation ? ??? */
/* 0x08b7 rightmiddlesummation ? ??? */
{0x08bc, 0x2264}, /* lessthanequal ≤ LESS-THAN OR EQUAL TO */
{0x08bd, 0x2260}, /* notequal ≠ NOT EQUAL TO */
{0x08be, 0x2265}, /* greaterthanequal ≥ GREATER-THAN OR EQUAL TO */
{0x08bf, 0x222b}, /* integral ∫ INTEGRAL */
{0x08c0, 0x2234}, /* therefore ∴ THEREFORE */
{0x08c1, 0x221d}, /* variation ∝ PROPORTIONAL TO */
{0x08c2, 0x221e}, /* infinity ∞ INFINITY */
{0x08c5, 0x2207}, /* nabla ∇ NABLA */
{0x08c8, 0x223c}, /* approximate ∼ TILDE OPERATOR */
{0x08c9, 0x2243}, /* similarequal ≃ ASYMPTOTICALLY EQUAL TO */
{0x08cd, 0x21d4}, /* ifonlyif ⇔ LEFT RIGHT DOUBLE ARROW */
{0x08ce, 0x21d2}, /* implies ⇒ RIGHTWARDS DOUBLE ARROW */
{0x08cf, 0x2261}, /* identical ≡ IDENTICAL TO */
{0x08d6, 0x221a}, /* radical √ SQUARE ROOT */
{0x08da, 0x2282}, /* includedin ⊂ SUBSET OF */
{0x08db, 0x2283}, /* includes ⊃ SUPERSET OF */
{0x08dc, 0x2229}, /* intersection ∩ INTERSECTION */
{0x08dd, 0x222a}, /* union ∪ UNION */
{0x08de, 0x2227}, /* logicaland ∧ LOGICAL AND */
{0x08df, 0x2228}, /* logicalor ∨ LOGICAL OR */
{0x08ef, 0x2202}, /* partialderivative ∂ PARTIAL DIFFERENTIAL */
{0x08f6, 0x0192}, /* function ƒ LATIN SMALL LETTER F WITH HOOK */
{0x08fb, 0x2190}, /* leftarrow ← LEFTWARDS ARROW */
{0x08fc, 0x2191}, /* uparrow ↑ UPWARDS ARROW */
{0x08fd, 0x2192}, /* rightarrow → RIGHTWARDS ARROW */
{0x08fe, 0x2193}, /* downarrow ↓ DOWNWARDS ARROW */
/* 0x09df blank ? ??? */
{0x09e0, 0x25c6}, /* soliddiamond ◆ BLACK DIAMOND */
{0x09e1, 0x2592}, /* checkerboard ▒ MEDIUM SHADE */
{0x09e2, 0x2409}, /* ht ␉ SYMBOL FOR HORIZONTAL TABULATION */
{0x09e3, 0x240c}, /* ff ␌ SYMBOL FOR FORM FEED */
{0x09e4, 0x240d}, /* cr ␍ SYMBOL FOR CARRIAGE RETURN */
{0x09e5, 0x240a}, /* lf ␊ SYMBOL FOR LINE FEED */
{0x09e8, 0x2424}, /* nl ␤ SYMBOL FOR NEWLINE */
{0x09e9, 0x240b}, /* vt ␋ SYMBOL FOR VERTICAL TABULATION */
{0x09ea, 0x2518}, /* lowrightcorner ┘ BOX DRAWINGS LIGHT UP AND LEFT */
{0x09eb, 0x2510}, /* uprightcorner ┐ BOX DRAWINGS LIGHT DOWN AND LEFT */
{0x09ec, 0x250c}, /* upleftcorner ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT */
{0x09ed, 0x2514}, /* lowleftcorner └ BOX DRAWINGS LIGHT UP AND RIGHT */
{0x09ee, 0x253c}, /* crossinglines ┼ BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL */
{0x09ef, 0x23ba}, /* horizlinescan1 ⎺ HORIZONTAL SCAN LINE-1 (Unicode 3.2 draft) */
{0x09f0, 0x23bb}, /* horizlinescan3 ⎻ HORIZONTAL SCAN LINE-3 (Unicode 3.2 draft) */
{0x09f1, 0x2500}, /* horizlinescan5 ─ BOX DRAWINGS LIGHT HORIZONTAL */
{0x09f2, 0x23bc}, /* horizlinescan7 ⎼ HORIZONTAL SCAN LINE-7 (Unicode 3.2 draft) */
{0x09f3, 0x23bd}, /* horizlinescan9 ⎽ HORIZONTAL SCAN LINE-9 (Unicode 3.2 draft) */
{0x09f4, 0x251c}, /* leftt ├ BOX DRAWINGS LIGHT VERTICAL AND RIGHT */
{0x09f5, 0x2524}, /* rightt ┤ BOX DRAWINGS LIGHT VERTICAL AND LEFT */
{0x09f6, 0x2534}, /* bott ┴ BOX DRAWINGS LIGHT UP AND HORIZONTAL */
{0x09f7, 0x252c}, /* topt ┬ BOX DRAWINGS LIGHT DOWN AND HORIZONTAL */
{0x09f8, 0x2502}, /* vertbar │ BOX DRAWINGS LIGHT VERTICAL */
{0x0aa1, 0x2003}, /* emspace   EM SPACE */
{0x0aa2, 0x2002}, /* enspace   EN SPACE */
{0x0aa3, 0x2004}, /* em3space   THREE-PER-EM SPACE */
{0x0aa4, 0x2005}, /* em4space   FOUR-PER-EM SPACE */
{0x0aa5, 0x2007}, /* digitspace   FIGURE SPACE */
{0x0aa6, 0x2008}, /* punctspace   PUNCTUATION SPACE */
{0x0aa7, 0x2009}, /* thinspace   THIN SPACE */
{0x0aa8, 0x200a}, /* hairspace   HAIR SPACE */
{0x0aa9, 0x2014}, /* emdash — EM DASH */
{0x0aaa, 0x2013}, /* endash – EN DASH */
{0x0aac, 0x2423}, /* signifblank ␣ OPEN BOX */
{0x0aae, 0x2026}, /* ellipsis … HORIZONTAL ELLIPSIS */
{0x0aaf, 0x2025}, /* doubbaselinedot ‥ TWO DOT LEADER */
{0x0ab0, 0x2153}, /* onethird ⅓ VULGAR FRACTION ONE THIRD */
{0x0ab1, 0x2154}, /* twothirds ⅔ VULGAR FRACTION TWO THIRDS */
{0x0ab2, 0x2155}, /* onefifth ⅕ VULGAR FRACTION ONE FIFTH */
{0x0ab3, 0x2156}, /* twofifths ⅖ VULGAR FRACTION TWO FIFTHS */
{0x0ab4, 0x2157}, /* threefifths ⅗ VULGAR FRACTION THREE FIFTHS */
{0x0ab5, 0x2158}, /* fourfifths ⅘ VULGAR FRACTION FOUR FIFTHS */
{0x0ab6, 0x2159}, /* onesixth ⅙ VULGAR FRACTION ONE SIXTH */
{0x0ab7, 0x215a}, /* fivesixths ⅚ VULGAR FRACTION FIVE SIXTHS */
{0x0ab8, 0x2105}, /* careof ℅ CARE OF */
{0x0abb, 0x2012}, /* figdash ‒ FIGURE DASH */
{0x0abc, 0x27e8}, /* leftanglebracket ⟨ MATHEMATICAL LEFT ANGLE BRACKET */
{0x0abd, 0x002e}, /* decimalpoint . FULL STOP */
{0x0abe, 0x27e9}, /* rightanglebracket ⟩ MATHEMATICAL RIGHT ANGLE BRACKET */
/* 0x0abf marker ? ??? */
{0x0ac3, 0x215b}, /* oneeighth ⅛ VULGAR FRACTION ONE EIGHTH */
{0x0ac4, 0x215c}, /* threeeighths ⅜ VULGAR FRACTION THREE EIGHTHS */
{0x0ac5, 0x215d}, /* fiveeighths ⅝ VULGAR FRACTION FIVE EIGHTHS */
{0x0ac6, 0x215e}, /* seveneighths ⅞ VULGAR FRACTION SEVEN EIGHTHS */
{0x0ac9, 0x2122}, /* trademark ™ TRADE MARK SIGN */
{0x0aca, 0x2613}, /* signaturemark ☓ SALTIRE */
/* 0x0acb trademarkincircle ? ??? */
{0x0acc, 0x25c1}, /* leftopentriangle ◁ WHITE LEFT-POINTING TRIANGLE */
{0x0acd, 0x25b7}, /* rightopentriangle ▷ WHITE RIGHT-POINTING TRIANGLE */
{0x0ace, 0x25cb}, /* emopencircle ○ WHITE CIRCLE */
{0x0acf, 0x25af}, /* emopenrectangle ▯ WHITE VERTICAL RECTANGLE */
{0x0ad0, 0x2018}, /* leftsinglequotemark ‘ LEFT SINGLE QUOTATION MARK */
{0x0ad1, 0x2019}, /* rightsinglequotemark ’ RIGHT SINGLE QUOTATION MARK */
{0x0ad2, 0x201c}, /* leftdoublequotemark “ LEFT DOUBLE QUOTATION MARK */
{0x0ad3, 0x201d}, /* rightdoublequotemark ” RIGHT DOUBLE QUOTATION MARK */
{0x0ad4, 0x211e}, /* prescription ℞ PRESCRIPTION TAKE */
{0x0ad5, 0x2030}, /* permille ‰ PER MILLE SIGN */
{0x0ad6, 0x2032}, /* minutes ′ PRIME */
{0x0ad7, 0x2033}, /* seconds ″ DOUBLE PRIME */
{0x0ad9, 0x271d}, /* latincross ✝ LATIN CROSS */
/* 0x0ada hexagram ? ??? */
{0x0adb, 0x25ac}, /* filledrectbullet ▬ BLACK RECTANGLE */
{0x0adc, 0x25c0}, /* filledlefttribullet ◀ BLACK LEFT-POINTING TRIANGLE */
{0x0add, 0x25b6}, /* filledrighttribullet ▶ BLACK RIGHT-POINTING TRIANGLE */
{0x0ade, 0x25cf}, /* emfilledcircle ● BLACK CIRCLE */
{0x0adf, 0x25ae}, /* emfilledrect ▮ BLACK VERTICAL RECTANGLE */
{0x0ae0, 0x25e6}, /* enopencircbullet ◦ WHITE BULLET */
{0x0ae1, 0x25ab}, /* enopensquarebullet ▫ WHITE SMALL SQUARE */
{0x0ae2, 0x25ad}, /* openrectbullet ▭ WHITE RECTANGLE */
{0x0ae3, 0x25b3}, /* opentribulletup △ WHITE UP-POINTING TRIANGLE */
{0x0ae4, 0x25bd}, /* opentribulletdown ▽ WHITE DOWN-POINTING TRIANGLE */
{0x0ae5, 0x2606}, /* openstar ☆ WHITE STAR */
{0x0ae6, 0x2022}, /* enfilledcircbullet • BULLET */
{0x0ae7, 0x25aa}, /* enfilledsqbullet ▪ BLACK SMALL SQUARE */
{0x0ae8, 0x25b2}, /* filledtribulletup ▲ BLACK UP-POINTING TRIANGLE */
{0x0ae9, 0x25bc}, /* filledtribulletdown ▼ BLACK DOWN-POINTING TRIANGLE */
{0x0aea, 0x261c}, /* leftpointer ☜ WHITE LEFT POINTING INDEX */
{0x0aeb, 0x261e}, /* rightpointer ☞ WHITE RIGHT POINTING INDEX */
{0x0aec, 0x2663}, /* club ♣ BLACK CLUB SUIT */
{0x0aed, 0x2666}, /* diamond ♦ BLACK DIAMOND SUIT */
{0x0aee, 0x2665}, /* heart ♥ BLACK HEART SUIT */
{0x0af0, 0x2720}, /* maltesecross ✠ MALTESE CROSS */
{0x0af1, 0x2020}, /* dagger † DAGGER */
{0x0af2, 0x2021}, /* doubledagger ‡ DOUBLE DAGGER */
{0x0af3, 0x2713}, /* checkmark ✓ CHECK MARK */
{0x0af4, 0x2717}, /* ballotcross ✗ BALLOT X */
{0x0af5, 0x266f}, /* musicalsharp ♯ MUSIC SHARP SIGN */
{0x0af6, 0x266d}, /* musicalflat ♭ MUSIC FLAT SIGN */
{0x0af7, 0x2642}, /* malesymbol ♂ MALE SIGN */
{0x0af8, 0x2640}, /* femalesymbol ♀ FEMALE SIGN */
{0x0af9, 0x260e}, /* telephone ☎ BLACK TELEPHONE */
{0x0afa, 0x2315}, /* telephonerecorder ⌕ TELEPHONE RECORDER */
{0x0afb, 0x2117}, /* phonographcopyright ℗ SOUND RECORDING COPYRIGHT */
{0x0afc, 0x2038}, /* caret ‸ CARET */
{0x0afd, 0x201a}, /* singlelowquotemark ‚ SINGLE LOW-9 QUOTATION MARK */
{0x0afe, 0x201e}, /* doublelowquotemark „ DOUBLE LOW-9 QUOTATION MARK */
/* 0x0aff cursor ? ??? */
{0x0ba3, 0x003c}, /* leftcaret < LESS-THAN SIGN */
{0x0ba6, 0x003e}, /* rightcaret > GREATER-THAN SIGN */
{0x0ba8, 0x2228}, /* downcaret ∨ LOGICAL OR */
{0x0ba9, 0x2227}, /* upcaret ∧ LOGICAL AND */
{0x0bc0, 0x00af}, /* overbar ¯ MACRON */
{0x0bc2, 0x22a4}, /* downtack ⊤ DOWN TACK */
{0x0bc3, 0x2229}, /* upshoe ∩ INTERSECTION */
{0x0bc4, 0x230a}, /* downstile ⌊ LEFT FLOOR */
{0x0bc6, 0x005f}, /* underbar _ LOW LINE */
{0x0bca, 0x2218}, /* jot ∘ RING OPERATOR */
{0x0bcc, 0x2395}, /* quad ⎕ APL FUNCTIONAL SYMBOL QUAD (Unicode 3.0) */
{0x0bce, 0x22a5}, /* uptack ⊥ UP TACK */
{0x0bcf, 0x25cb}, /* circle ○ WHITE CIRCLE */
{0x0bd3, 0x2308}, /* upstile ⌈ LEFT CEILING */
{0x0bd6, 0x222a}, /* downshoe ∪ UNION */
{0x0bd8, 0x2283}, /* rightshoe ⊃ SUPERSET OF */
{0x0bda, 0x2282}, /* leftshoe ⊂ SUBSET OF */
{0x0bdc, 0x22a2}, /* lefttack ⊢ RIGHT TACK */
{0x0bfc, 0x22a3}, /* righttack ⊣ LEFT TACK */
{0x0cdf, 0x2017}, /* hebrew_doublelowline ‗ DOUBLE LOW LINE */
{0x0ce0, 0x05d0}, /* hebrew_aleph א HEBREW LETTER ALEF */
{0x0ce1, 0x05d1}, /* hebrew_bet ב HEBREW LETTER BET */
{0x0ce2, 0x05d2}, /* hebrew_gimel ג HEBREW LETTER GIMEL */
{0x0ce3, 0x05d3}, /* hebrew_dalet ד HEBREW LETTER DALET */
{0x0ce4, 0x05d4}, /* hebrew_he ה HEBREW LETTER HE */
{0x0ce5, 0x05d5}, /* hebrew_waw ו HEBREW LETTER VAV */
{0x0ce6, 0x05d6}, /* hebrew_zain ז HEBREW LETTER ZAYIN */
{0x0ce7, 0x05d7}, /* hebrew_chet ח HEBREW LETTER HET */
{0x0ce8, 0x05d8}, /* hebrew_tet ט HEBREW LETTER TET */
{0x0ce9, 0x05d9}, /* hebrew_yod י HEBREW LETTER YOD */
{0x0cea, 0x05da}, /* hebrew_finalkaph ך HEBREW LETTER FINAL KAF */
{0x0ceb, 0x05db}, /* hebrew_kaph כ HEBREW LETTER KAF */
{0x0cec, 0x05dc}, /* hebrew_lamed ל HEBREW LETTER LAMED */
{0x0ced, 0x05dd}, /* hebrew_finalmem ם HEBREW LETTER FINAL MEM */
{0x0cee, 0x05de}, /* hebrew_mem מ HEBREW LETTER MEM */
{0x0cef, 0x05df}, /* hebrew_finalnun ן HEBREW LETTER FINAL NUN */
{0x0cf0, 0x05e0}, /* hebrew_nun נ HEBREW LETTER NUN */
{0x0cf1, 0x05e1}, /* hebrew_samech ס HEBREW LETTER SAMEKH */
{0x0cf2, 0x05e2}, /* hebrew_ayin ע HEBREW LETTER AYIN */
{0x0cf3, 0x05e3}, /* hebrew_finalpe ף HEBREW LETTER FINAL PE */
{0x0cf4, 0x05e4}, /* hebrew_pe פ HEBREW LETTER PE */
{0x0cf5, 0x05e5}, /* hebrew_finalzade ץ HEBREW LETTER FINAL TSADI */
{0x0cf6, 0x05e6}, /* hebrew_zade צ HEBREW LETTER TSADI */
{0x0cf7, 0x05e7}, /* hebrew_qoph ק HEBREW LETTER QOF */
{0x0cf8, 0x05e8}, /* hebrew_resh ר HEBREW LETTER RESH */
{0x0cf9, 0x05e9}, /* hebrew_shin ש HEBREW LETTER SHIN */
{0x0cfa, 0x05ea}, /* hebrew_taw ת HEBREW LETTER TAV */
{0x0da1, 0x0e01}, /* Thai_kokai ก THAI CHARACTER KO KAI */
{0x0da2, 0x0e02}, /* Thai_khokhai ข THAI CHARACTER KHO KHAI */
{0x0da3, 0x0e03}, /* Thai_khokhuat ฃ THAI CHARACTER KHO KHUAT */
{0x0da4, 0x0e04}, /* Thai_khokhwai ค THAI CHARACTER KHO KHWAI */
{0x0da5, 0x0e05}, /* Thai_khokhon ฅ THAI CHARACTER KHO KHON */
{0x0da6, 0x0e06}, /* Thai_khorakhang ฆ THAI CHARACTER KHO RAKHANG */
{0x0da7, 0x0e07}, /* Thai_ngongu ง THAI CHARACTER NGO NGU */
{0x0da8, 0x0e08}, /* Thai_chochan จ THAI CHARACTER CHO CHAN */
{0x0da9, 0x0e09}, /* Thai_choching ฉ THAI CHARACTER CHO CHING */
{0x0daa, 0x0e0a}, /* Thai_chochang ช THAI CHARACTER CHO CHANG */
{0x0dab, 0x0e0b}, /* Thai_soso ซ THAI CHARACTER SO SO */
{0x0dac, 0x0e0c}, /* Thai_chochoe ฌ THAI CHARACTER CHO CHOE */
{0x0dad, 0x0e0d}, /* Thai_yoying ญ THAI CHARACTER YO YING */
{0x0dae, 0x0e0e}, /* Thai_dochada ฎ THAI CHARACTER DO CHADA */
{0x0daf, 0x0e0f}, /* Thai_topatak ฏ THAI CHARACTER TO PATAK */
{0x0db0, 0x0e10}, /* Thai_thothan ฐ THAI CHARACTER THO THAN */
{0x0db1, 0x0e11}, /* Thai_thonangmontho ฑ THAI CHARACTER THO NANGMONTHO */
{0x0db2, 0x0e12}, /* Thai_thophuthao ฒ THAI CHARACTER THO PHUTHAO */
{0x0db3, 0x0e13}, /* Thai_nonen ณ THAI CHARACTER NO NEN */
{0x0db4, 0x0e14}, /* Thai_dodek ด THAI CHARACTER DO DEK */
{0x0db5, 0x0e15}, /* Thai_totao ต THAI CHARACTER TO TAO */
{0x0db6, 0x0e16}, /* Thai_thothung ถ THAI CHARACTER THO THUNG */
{0x0db7, 0x0e17}, /* Thai_thothahan ท THAI CHARACTER THO THAHAN */
{0x0db8, 0x0e18}, /* Thai_thothong ธ THAI CHARACTER THO THONG */
{0x0db9, 0x0e19}, /* Thai_nonu น THAI CHARACTER NO NU */
{0x0dba, 0x0e1a}, /* Thai_bobaimai บ THAI CHARACTER BO BAIMAI */
{0x0dbb, 0x0e1b}, /* Thai_popla ป THAI CHARACTER PO PLA */
{0x0dbc, 0x0e1c}, /* Thai_phophung ผ THAI CHARACTER PHO PHUNG */
{0x0dbd, 0x0e1d}, /* Thai_fofa ฝ THAI CHARACTER FO FA */
{0x0dbe, 0x0e1e}, /* Thai_phophan พ THAI CHARACTER PHO PHAN */
{0x0dbf, 0x0e1f}, /* Thai_fofan ฟ THAI CHARACTER FO FAN */
{0x0dc0, 0x0e20}, /* Thai_phosamphao ภ THAI CHARACTER PHO SAMPHAO */
{0x0dc1, 0x0e21}, /* Thai_moma ม THAI CHARACTER MO MA */
{0x0dc2, 0x0e22}, /* Thai_yoyak ย THAI CHARACTER YO YAK */
{0x0dc3, 0x0e23}, /* Thai_rorua ร THAI CHARACTER RO RUA */
{0x0dc4, 0x0e24}, /* Thai_ru ฤ THAI CHARACTER RU */
{0x0dc5, 0x0e25}, /* Thai_loling ล THAI CHARACTER LO LING */
{0x0dc6, 0x0e26}, /* Thai_lu ฦ THAI CHARACTER LU */
{0x0dc7, 0x0e27}, /* Thai_wowaen ว THAI CHARACTER WO WAEN */
{0x0dc8, 0x0e28}, /* Thai_sosala ศ THAI CHARACTER SO SALA */
{0x0dc9, 0x0e29}, /* Thai_sorusi ษ THAI CHARACTER SO RUSI */
{0x0dca, 0x0e2a}, /* Thai_sosua ส THAI CHARACTER SO SUA */
{0x0dcb, 0x0e2b}, /* Thai_hohip ห THAI CHARACTER HO HIP */
{0x0dcc, 0x0e2c}, /* Thai_lochula ฬ THAI CHARACTER LO CHULA */
{0x0dcd, 0x0e2d}, /* Thai_oang อ THAI CHARACTER O ANG */
{0x0dce, 0x0e2e}, /* Thai_honokhuk ฮ THAI CHARACTER HO NOKHUK */
{0x0dcf, 0x0e2f}, /* Thai_paiyannoi ฯ THAI CHARACTER PAIYANNOI */
{0x0dd0, 0x0e30}, /* Thai_saraa ะ THAI CHARACTER SARA A */
{0x0dd1, 0x0e31}, /* Thai_maihanakat ั THAI CHARACTER MAI HAN-AKAT */
{0x0dd2, 0x0e32}, /* Thai_saraaa า THAI CHARACTER SARA AA */
{0x0dd3, 0x0e33}, /* Thai_saraam ำ THAI CHARACTER SARA AM */
{0x0dd4, 0x0e34}, /* Thai_sarai ิ THAI CHARACTER SARA I */
{0x0dd5, 0x0e35}, /* Thai_saraii ี THAI CHARACTER SARA II */
{0x0dd6, 0x0e36}, /* Thai_saraue ึ THAI CHARACTER SARA UE */
{0x0dd7, 0x0e37}, /* Thai_sarauee ื THAI CHARACTER SARA UEE */
{0x0dd8, 0x0e38}, /* Thai_sarau ุ THAI CHARACTER SARA U */
{0x0dd9, 0x0e39}, /* Thai_sarauu ู THAI CHARACTER SARA UU */
{0x0dda, 0x0e3a}, /* Thai_phinthu ฺ THAI CHARACTER PHINTHU */
{0x0dde, 0x0e3e}, /* Thai_maihanakat_maitho ฾ ??? */
{0x0ddf, 0x0e3f}, /* Thai_baht ฿ THAI CURRENCY SYMBOL BAHT */
{0x0de0, 0x0e40}, /* Thai_sarae เ THAI CHARACTER SARA E */
{0x0de1, 0x0e41}, /* Thai_saraae แ THAI CHARACTER SARA AE */
{0x0de2, 0x0e42}, /* Thai_sarao โ THAI CHARACTER SARA O */
{0x0de3, 0x0e43}, /* Thai_saraaimaimuan ใ THAI CHARACTER SARA AI MAIMUAN */
{0x0de4, 0x0e44}, /* Thai_saraaimaimalai ไ THAI CHARACTER SARA AI MAIMALAI */
{0x0de5, 0x0e45}, /* Thai_lakkhangyao ๅ THAI CHARACTER LAKKHANGYAO */
{0x0de6, 0x0e46}, /* Thai_maiyamok ๆ THAI CHARACTER MAIYAMOK */
{0x0de7, 0x0e47}, /* Thai_maitaikhu ็ THAI CHARACTER MAITAIKHU */
{0x0de8, 0x0e48}, /* Thai_maiek ่ THAI CHARACTER MAI EK */
{0x0de9, 0x0e49}, /* Thai_maitho ้ THAI CHARACTER MAI THO */
{0x0dea, 0x0e4a}, /* Thai_maitri ๊ THAI CHARACTER MAI TRI */
{0x0deb, 0x0e4b}, /* Thai_maichattawa ๋ THAI CHARACTER MAI CHATTAWA */
{0x0dec, 0x0e4c}, /* Thai_thanthakhat ์ THAI CHARACTER THANTHAKHAT */
{0x0ded, 0x0e4d}, /* Thai_nikhahit ํ THAI CHARACTER NIKHAHIT */
{0x0df0, 0x0e50}, /* Thai_leksun ๐ THAI DIGIT ZERO */
{0x0df1, 0x0e51}, /* Thai_leknung ๑ THAI DIGIT ONE */
{0x0df2, 0x0e52}, /* Thai_leksong ๒ THAI DIGIT TWO */
{0x0df3, 0x0e53}, /* Thai_leksam ๓ THAI DIGIT THREE */
{0x0df4, 0x0e54}, /* Thai_leksi ๔ THAI DIGIT FOUR */
{0x0df5, 0x0e55}, /* Thai_lekha ๕ THAI DIGIT FIVE */
{0x0df6, 0x0e56}, /* Thai_lekhok ๖ THAI DIGIT SIX */
{0x0df7, 0x0e57}, /* Thai_lekchet ๗ THAI DIGIT SEVEN */
{0x0df8, 0x0e58}, /* Thai_lekpaet ๘ THAI DIGIT EIGHT */
{0x0df9, 0x0e59}, /* Thai_lekkao ๙ THAI DIGIT NINE */
{0x0ea1, 0x3131}, /* Hangul_Kiyeog ㄱ HANGUL LETTER KIYEOK */
{0x0ea2, 0x3132}, /* Hangul_SsangKiyeog ㄲ HANGUL LETTER SSANGKIYEOK */
{0x0ea3, 0x3133}, /* Hangul_KiyeogSios ㄳ HANGUL LETTER KIYEOK-SIOS */
{0x0ea4, 0x3134}, /* Hangul_Nieun ㄴ HANGUL LETTER NIEUN */
{0x0ea5, 0x3135}, /* Hangul_NieunJieuj ㄵ HANGUL LETTER NIEUN-CIEUC */
{0x0ea6, 0x3136}, /* Hangul_NieunHieuh ㄶ HANGUL LETTER NIEUN-HIEUH */
{0x0ea7, 0x3137}, /* Hangul_Dikeud ㄷ HANGUL LETTER TIKEUT */
{0x0ea8, 0x3138}, /* Hangul_SsangDikeud ㄸ HANGUL LETTER SSANGTIKEUT */
{0x0ea9, 0x3139}, /* Hangul_Rieul ㄹ HANGUL LETTER RIEUL */
{0x0eaa, 0x313a}, /* Hangul_RieulKiyeog ㄺ HANGUL LETTER RIEUL-KIYEOK */
{0x0eab, 0x313b}, /* Hangul_RieulMieum ㄻ HANGUL LETTER RIEUL-MIEUM */
{0x0eac, 0x313c}, /* Hangul_RieulPieub ㄼ HANGUL LETTER RIEUL-PIEUP */
{0x0ead, 0x313d}, /* Hangul_RieulSios ㄽ HANGUL LETTER RIEUL-SIOS */
{0x0eae, 0x313e}, /* Hangul_RieulTieut ㄾ HANGUL LETTER RIEUL-THIEUTH */
{0x0eaf, 0x313f}, /* Hangul_RieulPhieuf ㄿ HANGUL LETTER RIEUL-PHIEUPH */
{0x0eb0, 0x3140}, /* Hangul_RieulHieuh ㅀ HANGUL LETTER RIEUL-HIEUH */
{0x0eb1, 0x3141}, /* Hangul_Mieum ㅁ HANGUL LETTER MIEUM */
{0x0eb2, 0x3142}, /* Hangul_Pieub ㅂ HANGUL LETTER PIEUP */
{0x0eb3, 0x3143}, /* Hangul_SsangPieub ㅃ HANGUL LETTER SSANGPIEUP */
{0x0eb4, 0x3144}, /* Hangul_PieubSios ㅄ HANGUL LETTER PIEUP-SIOS */
{0x0eb5, 0x3145}, /* Hangul_Sios ㅅ HANGUL LETTER SIOS */
{0x0eb6, 0x3146}, /* Hangul_SsangSios ㅆ HANGUL LETTER SSANGSIOS */
{0x0eb7, 0x3147}, /* Hangul_Ieung ㅇ HANGUL LETTER IEUNG */
{0x0eb8, 0x3148}, /* Hangul_Jieuj ㅈ HANGUL LETTER CIEUC */
{0x0eb9, 0x3149}, /* Hangul_SsangJieuj ㅉ HANGUL LETTER SSANGCIEUC */
{0x0eba, 0x314a}, /* Hangul_Cieuc ㅊ HANGUL LETTER CHIEUCH */
{0x0ebb, 0x314b}, /* Hangul_Khieuq ㅋ HANGUL LETTER KHIEUKH */
{0x0ebc, 0x314c}, /* Hangul_Tieut ㅌ HANGUL LETTER THIEUTH */
{0x0ebd, 0x314d}, /* Hangul_Phieuf ㅍ HANGUL LETTER PHIEUPH */
{0x0ebe, 0x314e}, /* Hangul_Hieuh ㅎ HANGUL LETTER HIEUH */
{0x0ebf, 0x314f}, /* Hangul_A ㅏ HANGUL LETTER A */
{0x0ec0, 0x3150}, /* Hangul_AE ㅐ HANGUL LETTER AE */
{0x0ec1, 0x3151}, /* Hangul_YA ㅑ HANGUL LETTER YA */
{0x0ec2, 0x3152}, /* Hangul_YAE ㅒ HANGUL LETTER YAE */
{0x0ec3, 0x3153}, /* Hangul_EO ㅓ HANGUL LETTER EO */
{0x0ec4, 0x3154}, /* Hangul_E ㅔ HANGUL LETTER E */
{0x0ec5, 0x3155}, /* Hangul_YEO ㅕ HANGUL LETTER YEO */
{0x0ec6, 0x3156}, /* Hangul_YE ㅖ HANGUL LETTER YE */
{0x0ec7, 0x3157}, /* Hangul_O ㅗ HANGUL LETTER O */
{0x0ec8, 0x3158}, /* Hangul_WA ㅘ HANGUL LETTER WA */
{0x0ec9, 0x3159}, /* Hangul_WAE ㅙ HANGUL LETTER WAE */
{0x0eca, 0x315a}, /* Hangul_OE ㅚ HANGUL LETTER OE */
{0x0ecb, 0x315b}, /* Hangul_YO ㅛ HANGUL LETTER YO */
{0x0ecc, 0x315c}, /* Hangul_U ㅜ HANGUL LETTER U */
{0x0ecd, 0x315d}, /* Hangul_WEO ㅝ HANGUL LETTER WEO */
{0x0ece, 0x315e}, /* Hangul_WE ㅞ HANGUL LETTER WE */
{0x0ecf, 0x315f}, /* Hangul_WI ㅟ HANGUL LETTER WI */
{0x0ed0, 0x3160}, /* Hangul_YU ㅠ HANGUL LETTER YU */
{0x0ed1, 0x3161}, /* Hangul_EU ㅡ HANGUL LETTER EU */
{0x0ed2, 0x3162}, /* Hangul_YI ㅢ HANGUL LETTER YI */
{0x0ed3, 0x3163}, /* Hangul_I ㅣ HANGUL LETTER I */
{0x0ed4, 0x11a8}, /* Hangul_J_Kiyeog ᆨ HANGUL JONGSEONG KIYEOK */
{0x0ed5, 0x11a9}, /* Hangul_J_SsangKiyeog ᆩ HANGUL JONGSEONG SSANGKIYEOK */
{0x0ed6, 0x11aa}, /* Hangul_J_KiyeogSios ᆪ HANGUL JONGSEONG KIYEOK-SIOS */
{0x0ed7, 0x11ab}, /* Hangul_J_Nieun ᆫ HANGUL JONGSEONG NIEUN */
{0x0ed8, 0x11ac}, /* Hangul_J_NieunJieuj ᆬ HANGUL JONGSEONG NIEUN-CIEUC */
{0x0ed9, 0x11ad}, /* Hangul_J_NieunHieuh ᆭ HANGUL JONGSEONG NIEUN-HIEUH */
{0x0eda, 0x11ae}, /* Hangul_J_Dikeud ᆮ HANGUL JONGSEONG TIKEUT */
{0x0edb, 0x11af}, /* Hangul_J_Rieul ᆯ HANGUL JONGSEONG RIEUL */
{0x0edc, 0x11b0}, /* Hangul_J_RieulKiyeog ᆰ HANGUL JONGSEONG RIEUL-KIYEOK */
{0x0edd, 0x11b1}, /* Hangul_J_RieulMieum ᆱ HANGUL JONGSEONG RIEUL-MIEUM */
{0x0ede, 0x11b2}, /* Hangul_J_RieulPieub ᆲ HANGUL JONGSEONG RIEUL-PIEUP */
{0x0edf, 0x11b3}, /* Hangul_J_RieulSios ᆳ HANGUL JONGSEONG RIEUL-SIOS */
{0x0ee0, 0x11b4}, /* Hangul_J_RieulTieut ᆴ HANGUL JONGSEONG RIEUL-THIEUTH */
{0x0ee1, 0x11b5}, /* Hangul_J_RieulPhieuf ᆵ HANGUL JONGSEONG RIEUL-PHIEUPH */
{0x0ee2, 0x11b6}, /* Hangul_J_RieulHieuh ᆶ HANGUL JONGSEONG RIEUL-HIEUH */
{0x0ee3, 0x11b7}, /* Hangul_J_Mieum ᆷ HANGUL JONGSEONG MIEUM */
{0x0ee4, 0x11b8}, /* Hangul_J_Pieub ᆸ HANGUL JONGSEONG PIEUP */
{0x0ee5, 0x11b9}, /* Hangul_J_PieubSios ᆹ HANGUL JONGSEONG PIEUP-SIOS */
{0x0ee6, 0x11ba}, /* Hangul_J_Sios ᆺ HANGUL JONGSEONG SIOS */
{0x0ee7, 0x11bb}, /* Hangul_J_SsangSios ᆻ HANGUL JONGSEONG SSANGSIOS */
{0x0ee8, 0x11bc}, /* Hangul_J_Ieung ᆼ HANGUL JONGSEONG IEUNG */
{0x0ee9, 0x11bd}, /* Hangul_J_Jieuj ᆽ HANGUL JONGSEONG CIEUC */
{0x0eea, 0x11be}, /* Hangul_J_Cieuc ᆾ HANGUL JONGSEONG CHIEUCH */
{0x0eeb, 0x11bf}, /* Hangul_J_Khieuq ᆿ HANGUL JONGSEONG KHIEUKH */
{0x0eec, 0x11c0}, /* Hangul_J_Tieut ᇀ HANGUL JONGSEONG THIEUTH */
{0x0eed, 0x11c1}, /* Hangul_J_Phieuf ᇁ HANGUL JONGSEONG PHIEUPH */
{0x0eee, 0x11c2}, /* Hangul_J_Hieuh ᇂ HANGUL JONGSEONG HIEUH */
{0x0eef, 0x316d}, /* Hangul_RieulYeorinHieuh ㅭ HANGUL LETTER RIEUL-YEORINHIEUH */
{0x0ef0, 0x3171}, /* Hangul_SunkyeongeumMieum ㅱ HANGUL LETTER KAPYEOUNMIEUM */
{0x0ef1, 0x3178}, /* Hangul_SunkyeongeumPieub ㅸ HANGUL LETTER KAPYEOUNPIEUP */
{0x0ef2, 0x317f}, /* Hangul_PanSios ㅿ HANGUL LETTER PANSIOS */
/* 0x0ef3 Hangul_KkogjiDalrinIeung ? ??? */
{0x0ef4, 0x3184}, /* Hangul_SunkyeongeumPhieuf ㆄ HANGUL LETTER KAPYEOUNPHIEUPH */
{0x0ef5, 0x3186}, /* Hangul_YeorinHieuh ㆆ HANGUL LETTER YEORINHIEUH */
{0x0ef6, 0x318d}, /* Hangul_AraeA ㆍ HANGUL LETTER ARAEA */
{0x0ef7, 0x318e}, /* Hangul_AraeAE ㆎ HANGUL LETTER ARAEAE */
{0x0ef8, 0x11eb}, /* Hangul_J_PanSios ᇫ HANGUL JONGSEONG PANSIOS */
{0x0ef9, 0x11f0}, /* Hangul_J_KkogjiDalrinIeung ᇰ HANGUL JONGSEONG YESIEUNG */
{0x0efa, 0x11f9}, /* Hangul_J_YeorinHieuh ᇹ HANGUL JONGSEONG YEORINHIEUH */
{0x0eff, 0x20a9}, /* Korean_Won ₩ WON SIGN */
{0x13a4, 0x20ac}, /* Euro € EURO SIGN */
{0x13bc, 0x0152}, /* OE Œ LATIN CAPITAL LIGATURE OE */
{0x13bd, 0x0153}, /* oe œ LATIN SMALL LIGATURE OE */
{0x13be, 0x0178}, /* Ydiaeresis Ÿ LATIN CAPITAL LETTER Y WITH DIAERESIS */
{0x20a0, 0x20a0}, /* EcuSign ₠ EURO-CURRENCY SIGN */
{0x20a1, 0x20a1}, /* ColonSign ₡ COLON SIGN */
{0x20a2, 0x20a2}, /* CruzeiroSign ₢ CRUZEIRO SIGN */
{0x20a3, 0x20a3}, /* FFrancSign ₣ FRENCH FRANC SIGN */
{0x20a4, 0x20a4}, /* LiraSign ₤ LIRA SIGN */
{0x20a5, 0x20a5}, /* MillSign ₥ MILL SIGN */
{0x20a6, 0x20a6}, /* NairaSign ₦ NAIRA SIGN */
{0x20a7, 0x20a7}, /* PesetaSign ₧ PESETA SIGN */
{0x20a8, 0x20a8}, /* RupeeSign ₨ RUPEE SIGN */
{0x20a9, 0x20a9}, /* WonSign ₩ WON SIGN */
{0x20aa, 0x20aa}, /* NewSheqelSign ₪ NEW SHEQEL SIGN */
{0x20ab, 0x20ab}, /* DongSign ₫ DONG SIGN */
{0x20ac, 0x20ac}, /* EuroSign € EURO SIGN */
};
xkb_keysym_t
utf32_to_keysym(uint32_t ucs) {
/* first check for Latin-1 characters (1:1 mapping) */
if ((ucs >= 0x0020 && ucs <= 0x007e) || (ucs >= 0x00a0 && ucs <= 0x00ff)) return ucs;
/* special keysyms */
if ((ucs >= (XKB_KEY_BackSpace & 0x7f) && ucs <= (XKB_KEY_Clear & 0x7f)) || ucs == (XKB_KEY_Return & 0x7f) || ucs == (XKB_KEY_Escape & 0x7f))
return ucs | 0xff00;
if (ucs == (XKB_KEY_Delete & 0x7f)) return XKB_KEY_Delete;
/* Unicode non-symbols and code points outside Unicode planes */
if ((ucs >= 0xfdd0 && ucs <= 0xfdef) || ucs > 0x10ffff || (ucs & 0xfffe) == 0xfffe) return XKB_KEY_NoSymbol;
/* search main table */
for (size_t i = 0; i < sizeof(keysymtab) / sizeof(keysymtab[0]); i++)
if (keysymtab[i].ucs == ucs) return keysymtab[i].keysym;
/* Use direct encoding if everything else fails */
return ucs | 0x01000000;
}
+1138
View File
File diff suppressed because it is too large. Load diff
+108
View File
@@ -0,0 +1,108 @@
//========================================================================
// GLFW 3.4 XKB - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2018 Kovid Goyal <kovid@kovidgoyal.net>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#pragma once
#include <xkbcommon/xkbcommon.h>
#include <xkbcommon/xkbcommon-compose.h>
#ifdef _GLFW_X11
#include <xkbcommon/xkbcommon-x11.h>
#endif
#include "ibus_glfw.h"
typedef struct {
struct xkb_state *state;
struct xkb_state *clean_state;
struct xkb_state *default_state;
struct xkb_compose_state *composeState;
xkb_mod_mask_t activeUnknownModifiers;
unsigned int modifiers;
} XKBStateGroup;
typedef struct {
struct xkb_context *context;
struct xkb_keymap *keymap;
struct xkb_keymap *default_keymap;
XKBStateGroup states;
xkb_mod_index_t controlIdx;
xkb_mod_index_t altIdx;
xkb_mod_index_t shiftIdx;
xkb_mod_index_t superIdx;
xkb_mod_index_t hyperIdx;
xkb_mod_index_t metaIdx;
xkb_mod_index_t capsLockIdx;
xkb_mod_index_t numLockIdx;
xkb_mod_mask_t controlMask;
xkb_mod_mask_t altMask;
xkb_mod_mask_t shiftMask;
xkb_mod_mask_t superMask;
xkb_mod_mask_t hyperMask;
xkb_mod_mask_t metaMask;
xkb_mod_mask_t capsLockMask;
xkb_mod_mask_t numLockMask;
xkb_mod_index_t unknownModifiers[256];
_GLFWIBUSData ibus;
#ifdef _GLFW_X11
int32_t keyboard_device_id;
bool available;
bool detectable;
int majorOpcode;
int eventBase;
int errorBase;
int major;
int minor;
#endif
} _GLFWXKBData;
#ifdef _GLFW_X11
bool glfw_xkb_set_x11_events_mask(void);
bool glfw_xkb_update_x11_keyboard_id(_GLFWXKBData *xkb);
#endif
void glfw_xkb_release(_GLFWXKBData *xkb);
bool glfw_xkb_create_context(_GLFWXKBData *xkb);
bool glfw_xkb_compile_keymap(_GLFWXKBData *xkb, const char *map_str);
void glfw_xkb_update_modifiers(
_GLFWXKBData *xkb,
xkb_mod_mask_t depressed,
xkb_mod_mask_t latched,
xkb_mod_mask_t locked,
xkb_layout_index_t base_group,
xkb_layout_index_t latched_group,
xkb_layout_index_t locked_group);
bool glfw_xkb_should_repeat(_GLFWXKBData *xkb, xkb_keycode_t keycode);
const char *glfw_xkb_keysym_name(xkb_keysym_t sym);
xkb_keysym_t glfw_xkb_sym_for_key(uint32_t key);
void glfw_xkb_handle_key_event(_GLFWwindow *window, _GLFWXKBData *xkb, xkb_keycode_t keycode, int action);
int glfw_xkb_keysym_from_name(const char *name, bool case_sensitive);
void glfw_xkb_update_ime_state(_GLFWwindow *w, _GLFWXKBData *xkb, const GLFWIMEUpdateEvent *ev);
void glfw_xkb_key_from_ime(_GLFWIBUSKeyEvent *ev, bool handled_by_ime, bool failed);
void glfw_xkb_forwarded_key_from_ime(xkb_keysym_t keysym, unsigned int glfw_mods);