diff options
Diffstat (limited to 'platform/linuxbsd')
30 files changed, 11315 insertions, 0 deletions
diff --git a/platform/linuxbsd/SCsub b/platform/linuxbsd/SCsub new file mode 100644 index 0000000000..8aebd57fd2 --- /dev/null +++ b/platform/linuxbsd/SCsub @@ -0,0 +1,32 @@ +#!/usr/bin/env python + +Import("env") + +from platform_methods import run_in_subprocess +import platform_linuxbsd_builders + +common_linuxbsd = [ + "crash_handler_linuxbsd.cpp", + "os_linuxbsd.cpp", + "joypad_linux.cpp", + "freedesktop_screensaver.cpp", +] + +if "x11" in env and env["x11"]: + common_linuxbsd += [ + "context_gl_x11.cpp", + "detect_prime_x11.cpp", + "display_server_x11.cpp", + "key_mapping_x11.cpp", + ] + +if "vulkan" in env and env["vulkan"]: + common_linuxbsd.append("vulkan_context_x11.cpp") + +if "udev" in env and env["udev"]: + common_linuxbsd.append("libudev-so_wrap.c") + +prog = env.add_program("#bin/godot", ["godot_linuxbsd.cpp"] + common_linuxbsd) + +if env["debug_symbols"] and env["separate_debug_symbols"]: + env.AddPostAction(prog, run_in_subprocess(platform_linuxbsd_builders.make_debug_linuxbsd)) diff --git a/platform/linuxbsd/context_gl_x11.cpp b/platform/linuxbsd/context_gl_x11.cpp new file mode 100644 index 0000000000..1f92370ab7 --- /dev/null +++ b/platform/linuxbsd/context_gl_x11.cpp @@ -0,0 +1,257 @@ +/*************************************************************************/ +/* context_gl_x11.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#include "context_gl_x11.h" + +#ifdef X11_ENABLED +#if defined(OPENGL_ENABLED) +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +#define GLX_GLXEXT_PROTOTYPES +#include <GL/glx.h> +#include <GL/glxext.h> + +#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 +#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 + +typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *); + +struct ContextGL_X11_Private { + ::GLXContext glx_context; +}; + +void ContextGL_X11::release_current() { + glXMakeCurrent(x11_display, None, nullptr); +} + +void ContextGL_X11::make_current() { + glXMakeCurrent(x11_display, x11_window, p->glx_context); +} + +void ContextGL_X11::swap_buffers() { + glXSwapBuffers(x11_display, x11_window); +} + +static bool ctxErrorOccurred = false; +static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) { + ctxErrorOccurred = true; + return 0; +} + +static void set_class_hint(Display *p_display, Window p_window) { + XClassHint *classHint; + + /* set the name and class hints for the window manager to use */ + classHint = XAllocClassHint(); + if (classHint) { + classHint->res_name = (char *)"Godot_Engine"; + classHint->res_class = (char *)"Godot"; + } + XSetClassHint(p_display, p_window, classHint); + XFree(classHint); +} + +Error ContextGL_X11::initialize() { + //const char *extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display)); + + GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB"); + + ERR_FAIL_COND_V(!glXCreateContextAttribsARB, ERR_UNCONFIGURED); + + static int visual_attribs[] = { + GLX_RENDER_TYPE, GLX_RGBA_BIT, + GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, + GLX_DOUBLEBUFFER, true, + GLX_RED_SIZE, 1, + GLX_GREEN_SIZE, 1, + GLX_BLUE_SIZE, 1, + GLX_DEPTH_SIZE, 24, + None + }; + + static int visual_attribs_layered[] = { + GLX_RENDER_TYPE, GLX_RGBA_BIT, + GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, + GLX_DOUBLEBUFFER, true, + GLX_RED_SIZE, 8, + GLX_GREEN_SIZE, 8, + GLX_BLUE_SIZE, 8, + GLX_ALPHA_SIZE, 8, + GLX_DEPTH_SIZE, 24, + None + }; + + int fbcount; + GLXFBConfig fbconfig = 0; + XVisualInfo *vi = nullptr; + + XSetWindowAttributes swa; + swa.event_mask = StructureNotifyMask; + swa.border_pixel = 0; + unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask; + + if (OS::get_singleton()->is_layered_allowed()) { + GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs_layered, &fbcount); + ERR_FAIL_COND_V(!fbc, ERR_UNCONFIGURED); + + for (int i = 0; i < fbcount; i++) { + vi = (XVisualInfo *)glXGetVisualFromFBConfig(x11_display, fbc[i]); + if (!vi) + continue; + + XRenderPictFormat *pict_format = XRenderFindVisualFormat(x11_display, vi->visual); + if (!pict_format) { + XFree(vi); + vi = nullptr; + continue; + } + + fbconfig = fbc[i]; + if (pict_format->direct.alphaMask > 0) { + break; + } + } + XFree(fbc); + ERR_FAIL_COND_V(!fbconfig, ERR_UNCONFIGURED); + + swa.background_pixmap = None; + swa.background_pixel = 0; + swa.border_pixmap = None; + valuemask |= CWBackPixel; + + } else { + GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount); + ERR_FAIL_COND_V(!fbc, ERR_UNCONFIGURED); + + vi = glXGetVisualFromFBConfig(x11_display, fbc[0]); + + fbconfig = fbc[0]; + XFree(fbc); + } + + int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&ctxErrorHandler); + + switch (context_type) { + case GLES_2_0_COMPATIBLE: { + p->glx_context = glXCreateNewContext(x11_display, fbconfig, GLX_RGBA_TYPE, 0, true); + ERR_FAIL_COND_V(!p->glx_context, ERR_UNCONFIGURED); + } break; + } + + swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone); + x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa); + XStoreName(x11_display, x11_window, "Godot Engine"); + + ERR_FAIL_COND_V(!x11_window, ERR_UNCONFIGURED); + set_class_hint(x11_display, x11_window); + XMapWindow(x11_display, x11_window); + + XSync(x11_display, False); + XSetErrorHandler(oldHandler); + + glXMakeCurrent(x11_display, x11_window, p->glx_context); + + XFree(vi); + + return OK; +} + +int ContextGL_X11::get_window_width() { + XWindowAttributes xwa; + XGetWindowAttributes(x11_display, x11_window, &xwa); + + return xwa.width; +} + +int ContextGL_X11::get_window_height() { + XWindowAttributes xwa; + XGetWindowAttributes(x11_display, x11_window, &xwa); + + return xwa.height; +} + +void ContextGL_X11::set_use_vsync(bool p_use) { + static bool setup = false; + static PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = nullptr; + static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalMESA = nullptr; + static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = nullptr; + + if (!setup) { + setup = true; + String extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display)); + if (extensions.find("GLX_EXT_swap_control") != -1) + glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalEXT"); + if (extensions.find("GLX_MESA_swap_control") != -1) + glXSwapIntervalMESA = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalMESA"); + if (extensions.find("GLX_SGI_swap_control") != -1) + glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalSGI"); + } + int val = p_use ? 1 : 0; + if (glXSwapIntervalMESA) { + glXSwapIntervalMESA(val); + } else if (glXSwapIntervalSGI) { + glXSwapIntervalSGI(val); + } else if (glXSwapIntervalEXT) { + GLXDrawable drawable = glXGetCurrentDrawable(); + glXSwapIntervalEXT(x11_display, drawable, val); + } else + return; + use_vsync = p_use; +} + +bool ContextGL_X11::is_using_vsync() const { + return use_vsync; +} + +ContextGL_X11::ContextGL_X11(::Display *p_x11_display, ::Window &p_x11_window, const OS::VideoMode &p_default_video_mode, ContextType p_context_type) : + x11_window(p_x11_window) { + default_video_mode = p_default_video_mode; + x11_display = p_x11_display; + + context_type = p_context_type; + + double_buffer = false; + direct_render = false; + glx_minor = glx_major = 0; + p = memnew(ContextGL_X11_Private); + p->glx_context = 0; + use_vsync = false; +} + +ContextGL_X11::~ContextGL_X11() { + release_current(); + glXDestroyContext(x11_display, p->glx_context); + memdelete(p); +} + +#endif +#endif diff --git a/platform/linuxbsd/context_gl_x11.h b/platform/linuxbsd/context_gl_x11.h new file mode 100644 index 0000000000..d089886f4d --- /dev/null +++ b/platform/linuxbsd/context_gl_x11.h @@ -0,0 +1,80 @@ +/*************************************************************************/ +/* context_gl_x11.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifndef CONTEXT_GL_X11_H +#define CONTEXT_GL_X11_H + +#ifdef X11_ENABLED + +#if defined(OPENGL_ENABLED) + +#include "core/os/os.h" +#include <X11/Xlib.h> +#include <X11/extensions/Xrender.h> + +struct ContextGL_X11_Private; + +class ContextGL_X11 { +public: + enum ContextType { + GLES_2_0_COMPATIBLE, + }; + +private: + ContextGL_X11_Private *p; + OS::VideoMode default_video_mode; + ::Display *x11_display; + ::Window &x11_window; + bool double_buffer; + bool direct_render; + int glx_minor, glx_major; + bool use_vsync; + ContextType context_type; + +public: + void release_current(); + void make_current(); + void swap_buffers(); + int get_window_width(); + int get_window_height(); + + Error initialize(); + + void set_use_vsync(bool p_use); + bool is_using_vsync() const; + + ContextGL_X11(::Display *p_x11_display, ::Window &p_x11_window, const OS::VideoMode &p_default_video_mode, ContextType p_context_type); + ~ContextGL_X11(); +}; + +#endif + +#endif +#endif diff --git a/platform/linuxbsd/crash_handler_linuxbsd.cpp b/platform/linuxbsd/crash_handler_linuxbsd.cpp new file mode 100644 index 0000000000..ea0222cb19 --- /dev/null +++ b/platform/linuxbsd/crash_handler_linuxbsd.cpp @@ -0,0 +1,152 @@ +/*************************************************************************/ +/* crash_handler_linuxbsd.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#include "crash_handler_linuxbsd.h" + +#include "core/config/project_settings.h" +#include "core/os/os.h" +#include "main/main.h" + +#ifdef DEBUG_ENABLED +#define CRASH_HANDLER_ENABLED 1 +#endif + +#ifdef CRASH_HANDLER_ENABLED +#include <cxxabi.h> +#include <dlfcn.h> +#include <execinfo.h> +#include <signal.h> +#include <stdlib.h> + +static void handle_crash(int sig) { + if (OS::get_singleton() == nullptr) { + abort(); + } + + void *bt_buffer[256]; + size_t size = backtrace(bt_buffer, 256); + String _execpath = OS::get_singleton()->get_executable_path(); + + String msg; + const ProjectSettings *proj_settings = ProjectSettings::get_singleton(); + if (proj_settings) { + msg = proj_settings->get("debug/settings/crash_handler/message"); + } + + // Dump the backtrace to stderr with a message to the user + fprintf(stderr, "%s: Program crashed with signal %d\n", __FUNCTION__, sig); + + if (OS::get_singleton()->get_main_loop()) { + OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH); + } + + fprintf(stderr, "Dumping the backtrace. %s\n", msg.utf8().get_data()); + char **strings = backtrace_symbols(bt_buffer, size); + if (strings) { + for (size_t i = 1; i < size; i++) { + char fname[1024]; + Dl_info info; + + snprintf(fname, 1024, "%s", strings[i]); + + // Try to demangle the function name to provide a more readable one + if (dladdr(bt_buffer[i], &info) && info.dli_sname) { + if (info.dli_sname[0] == '_') { + int status; + char *demangled = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, &status); + + if (status == 0 && demangled) { + snprintf(fname, 1024, "%s", demangled); + } + + if (demangled) { + free(demangled); + } + } + } + + List<String> args; + + char str[1024]; + snprintf(str, 1024, "%p", bt_buffer[i]); + args.push_back(str); + args.push_back("-e"); + args.push_back(_execpath); + + String output = ""; + + // Try to get the file/line number using addr2line + int ret; + Error err = OS::get_singleton()->execute(String("addr2line"), args, &output, &ret); + if (err == OK) { + output.erase(output.length() - 1, 1); + } + + fprintf(stderr, "[%ld] %s (%s)\n", (long int)i, fname, output.utf8().get_data()); + } + + free(strings); + } + fprintf(stderr, "-- END OF BACKTRACE --\n"); + + // Abort to pass the error to the OS + abort(); +} +#endif + +CrashHandler::CrashHandler() { + disabled = false; +} + +CrashHandler::~CrashHandler() { + disable(); +} + +void CrashHandler::disable() { + if (disabled) { + return; + } + +#ifdef CRASH_HANDLER_ENABLED + signal(SIGSEGV, nullptr); + signal(SIGFPE, nullptr); + signal(SIGILL, nullptr); +#endif + + disabled = true; +} + +void CrashHandler::initialize() { +#ifdef CRASH_HANDLER_ENABLED + signal(SIGSEGV, handle_crash); + signal(SIGFPE, handle_crash); + signal(SIGILL, handle_crash); +#endif +} diff --git a/platform/linuxbsd/crash_handler_linuxbsd.h b/platform/linuxbsd/crash_handler_linuxbsd.h new file mode 100644 index 0000000000..a3dae0cc22 --- /dev/null +++ b/platform/linuxbsd/crash_handler_linuxbsd.h @@ -0,0 +1,47 @@ +/*************************************************************************/ +/* crash_handler_linuxbsd.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifndef CRASH_HANDLER_X11_H +#define CRASH_HANDLER_X11_H + +class CrashHandler { + bool disabled; + +public: + void initialize(); + + void disable(); + bool is_disabled() const { return disabled; }; + + CrashHandler(); + ~CrashHandler(); +}; + +#endif // CRASH_HANDLER_X11_H diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py new file mode 100644 index 0000000000..eba672ddcb --- /dev/null +++ b/platform/linuxbsd/detect.py @@ -0,0 +1,440 @@ +import os +import platform +import sys + + +def is_active(): + return True + + +def get_name(): + return "LinuxBSD" + + +def can_build(): + if os.name != "posix" or sys.platform == "darwin": + return False + + # Check the minimal dependencies + x11_error = os.system("pkg-config --version > /dev/null") + if x11_error: + return False + + x11_error = os.system("pkg-config x11 --modversion > /dev/null ") + if x11_error: + return False + + x11_error = os.system("pkg-config xcursor --modversion > /dev/null ") + if x11_error: + print("xcursor not found.. x11 disabled.") + return False + + x11_error = os.system("pkg-config xinerama --modversion > /dev/null ") + if x11_error: + print("xinerama not found.. x11 disabled.") + return False + + x11_error = os.system("pkg-config xext --modversion > /dev/null ") + if x11_error: + print("xext not found.. x11 disabled.") + return False + + x11_error = os.system("pkg-config xrandr --modversion > /dev/null ") + if x11_error: + print("xrandr not found.. x11 disabled.") + return False + + x11_error = os.system("pkg-config xrender --modversion > /dev/null ") + if x11_error: + print("xrender not found.. x11 disabled.") + return False + + x11_error = os.system("pkg-config xi --modversion > /dev/null ") + if x11_error: + print("xi not found.. Aborting.") + return False + + return True + + +def get_opts(): + from SCons.Variables import BoolVariable, EnumVariable + + return [ + BoolVariable("use_llvm", "Use the LLVM compiler", False), + BoolVariable("use_lld", "Use the LLD linker", False), + BoolVariable("use_thinlto", "Use ThinLTO", False), + BoolVariable("use_static_cpp", "Link libgcc and libstdc++ statically for better portability", True), + BoolVariable("use_coverage", "Test Godot coverage", False), + BoolVariable("use_ubsan", "Use LLVM/GCC compiler undefined behavior sanitizer (UBSAN)", False), + BoolVariable("use_asan", "Use LLVM/GCC compiler address sanitizer (ASAN)", False), + BoolVariable("use_lsan", "Use LLVM/GCC compiler leak sanitizer (LSAN)", False), + BoolVariable("use_tsan", "Use LLVM/GCC compiler thread sanitizer (TSAN)", False), + BoolVariable("use_msan", "Use LLVM compiler memory sanitizer (MSAN)", False), + BoolVariable("pulseaudio", "Detect and use PulseAudio", True), + BoolVariable("dbus", "Detect and use D-Bus to handle screensaver", True), + BoolVariable("udev", "Use udev for gamepad connection callbacks", True), + BoolVariable("x11", "Enable X11 display", True), + BoolVariable("debug_symbols", "Add debugging symbols to release/release_debug builds", True), + BoolVariable("separate_debug_symbols", "Create a separate file containing debugging symbols", False), + BoolVariable("touch", "Enable touch events", True), + BoolVariable("execinfo", "Use libexecinfo on systems where glibc is not available", False), + ] + + +def get_flags(): + return [] + + +def configure(env): + ## Build type + + if env["target"] == "release": + if env["optimize"] == "speed": # optimize for speed (default) + env.Prepend(CCFLAGS=["-O3"]) + elif env["optimize"] == "size": # optimize for size + env.Prepend(CCFLAGS=["-Os"]) + + if env["debug_symbols"]: + env.Prepend(CCFLAGS=["-g2"]) + + elif env["target"] == "release_debug": + if env["optimize"] == "speed": # optimize for speed (default) + env.Prepend(CCFLAGS=["-O2"]) + elif env["optimize"] == "size": # optimize for size + env.Prepend(CCFLAGS=["-Os"]) + env.Prepend(CPPDEFINES=["DEBUG_ENABLED"]) + + if env["debug_symbols"]: + env.Prepend(CCFLAGS=["-g2"]) + + elif env["target"] == "debug": + env.Prepend(CCFLAGS=["-g3"]) + env.Prepend(CPPDEFINES=["DEBUG_ENABLED"]) + env.Append(LINKFLAGS=["-rdynamic"]) + + ## Architecture + + is64 = sys.maxsize > 2 ** 32 + if env["bits"] == "default": + env["bits"] = "64" if is64 else "32" + + ## Compiler configuration + + if "CXX" in env and "clang" in os.path.basename(env["CXX"]): + # Convenience check to enforce the use_llvm overrides when CXX is clang(++) + env["use_llvm"] = True + + if env["use_llvm"]: + if "clang++" not in os.path.basename(env["CXX"]): + env["CC"] = "clang" + env["CXX"] = "clang++" + env.extra_suffix = ".llvm" + env.extra_suffix + + if env["use_lld"]: + if env["use_llvm"]: + env.Append(LINKFLAGS=["-fuse-ld=lld"]) + if env["use_thinlto"]: + # A convenience so you don't need to write use_lto too when using SCons + env["use_lto"] = True + else: + print("Using LLD with GCC is not supported yet, try compiling with 'use_llvm=yes'.") + sys.exit(255) + + if env["use_coverage"]: + env.Append(CCFLAGS=["-ftest-coverage", "-fprofile-arcs"]) + env.Append(LINKFLAGS=["-ftest-coverage", "-fprofile-arcs"]) + + if env["use_ubsan"] or env["use_asan"] or env["use_lsan"] or env["use_tsan"] or env["use_msan"]: + env.extra_suffix += "s" + + if env["use_ubsan"]: + env.Append( + CCFLAGS=[ + "-fsanitize=undefined,shift,shift-exponent,integer-divide-by-zero,unreachable,vla-bound,null,return,signed-integer-overflow,bounds,float-divide-by-zero,float-cast-overflow,nonnull-attribute,returns-nonnull-attribute,bool,enum,vptr,pointer-overflow,builtin" + ] + ) + env.Append(LINKFLAGS=["-fsanitize=undefined"]) + if env["use_llvm"]: + env.Append( + CCFLAGS=[ + "-fsanitize=nullability-return,nullability-arg,function,nullability-assign,implicit-integer-sign-change" + ] + ) + else: + env.Append(CCFLAGS=["-fsanitize=bounds-strict"]) + + if env["use_asan"]: + env.Append(CCFLAGS=["-fsanitize=address,pointer-subtract,pointer-compare"]) + env.Append(LINKFLAGS=["-fsanitize=address"]) + + if env["use_lsan"]: + env.Append(CCFLAGS=["-fsanitize=leak"]) + env.Append(LINKFLAGS=["-fsanitize=leak"]) + + if env["use_tsan"]: + env.Append(CCFLAGS=["-fsanitize=thread"]) + env.Append(LINKFLAGS=["-fsanitize=thread"]) + + if env["use_msan"] and env["use_llvm"]: + env.Append(CCFLAGS=["-fsanitize=memory"]) + env.Append(CCFLAGS=["-fsanitize-memory-track-origins"]) + env.Append(CCFLAGS=["-fsanitize-recover=memory"]) + env.Append(LINKFLAGS=["-fsanitize=memory"]) + + if env["use_lto"]: + if not env["use_llvm"] and env.GetOption("num_jobs") > 1: + env.Append(CCFLAGS=["-flto"]) + env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))]) + else: + if env["use_lld"] and env["use_thinlto"]: + env.Append(CCFLAGS=["-flto=thin"]) + env.Append(LINKFLAGS=["-flto=thin"]) + else: + env.Append(CCFLAGS=["-flto"]) + env.Append(LINKFLAGS=["-flto"]) + + if not env["use_llvm"]: + env["RANLIB"] = "gcc-ranlib" + env["AR"] = "gcc-ar" + + env.Append(CCFLAGS=["-pipe"]) + env.Append(LINKFLAGS=["-pipe"]) + + # -fpie and -no-pie is supported on GCC 6+ and Clang 4+, both below our + # minimal requirements. + env.Append(CCFLAGS=["-fpie"]) + env.Append(LINKFLAGS=["-no-pie"]) + + ## Dependencies + + env.ParseConfig("pkg-config x11 --cflags --libs") + env.ParseConfig("pkg-config xcursor --cflags --libs") + env.ParseConfig("pkg-config xinerama --cflags --libs") + env.ParseConfig("pkg-config xext --cflags --libs") + env.ParseConfig("pkg-config xrandr --cflags --libs") + env.ParseConfig("pkg-config xrender --cflags --libs") + env.ParseConfig("pkg-config xi --cflags --libs") + + if env["touch"]: + env.Append(CPPDEFINES=["TOUCH_ENABLED"]) + + # FIXME: Check for existence of the libs before parsing their flags with pkg-config + + # freetype depends on libpng and zlib, so bundling one of them while keeping others + # as shared libraries leads to weird issues + if ( + env["builtin_freetype"] + or env["builtin_libpng"] + or env["builtin_zlib"] + or env["builtin_graphite"] + or env["builtin_harfbuzz"] + ): + env["builtin_freetype"] = True + env["builtin_libpng"] = True + env["builtin_zlib"] = True + env["builtin_graphite"] = True + env["builtin_harfbuzz"] = True + + if not env["builtin_freetype"]: + env.ParseConfig("pkg-config freetype2 --cflags --libs") + + if not env["builtin_graphite"]: + env.ParseConfig("pkg-config graphite2 --cflags --libs") + + if not env["builtin_icu"]: + env.ParseConfig("pkg-config icu-uc --cflags --libs") + + if not env["builtin_harfbuzz"]: + env.ParseConfig("pkg-config harfbuzz harfbuzz-icu --cflags --libs") + + if not env["builtin_libpng"]: + env.ParseConfig("pkg-config libpng16 --cflags --libs") + + if not env["builtin_bullet"]: + # We need at least version 2.90 + min_bullet_version = "2.90" + + import subprocess + + bullet_version = subprocess.check_output(["pkg-config", "bullet", "--modversion"]).strip() + if str(bullet_version) < min_bullet_version: + # Abort as system bullet was requested but too old + print( + "Bullet: System version {0} does not match minimal requirements ({1}). Aborting.".format( + bullet_version, min_bullet_version + ) + ) + sys.exit(255) + env.ParseConfig("pkg-config bullet --cflags --libs") + + if False: # not env['builtin_assimp']: + # FIXME: Add min version check + env.ParseConfig("pkg-config assimp --cflags --libs") + + if not env["builtin_enet"]: + env.ParseConfig("pkg-config libenet --cflags --libs") + + if not env["builtin_squish"]: + env.ParseConfig("pkg-config libsquish --cflags --libs") + + if not env["builtin_zstd"]: + env.ParseConfig("pkg-config libzstd --cflags --libs") + + # Sound and video libraries + # Keep the order as it triggers chained dependencies (ogg needed by others, etc.) + + if not env["builtin_libtheora"]: + env["builtin_libogg"] = False # Needed to link against system libtheora + env["builtin_libvorbis"] = False # Needed to link against system libtheora + env.ParseConfig("pkg-config theora theoradec --cflags --libs") + else: + list_of_x86 = ["x86_64", "x86", "i386", "i586"] + if any(platform.machine() in s for s in list_of_x86): + env["x86_libtheora_opt_gcc"] = True + + if not env["builtin_libvpx"]: + env.ParseConfig("pkg-config vpx --cflags --libs") + + if not env["builtin_libvorbis"]: + env["builtin_libogg"] = False # Needed to link against system libvorbis + env.ParseConfig("pkg-config vorbis vorbisfile --cflags --libs") + + if not env["builtin_opus"]: + env["builtin_libogg"] = False # Needed to link against system opus + env.ParseConfig("pkg-config opus opusfile --cflags --libs") + + if not env["builtin_libogg"]: + env.ParseConfig("pkg-config ogg --cflags --libs") + + if not env["builtin_libwebp"]: + env.ParseConfig("pkg-config libwebp --cflags --libs") + + if not env["builtin_mbedtls"]: + # mbedTLS does not provide a pkgconfig config yet. See https://github.com/ARMmbed/mbedtls/issues/228 + env.Append(LIBS=["mbedtls", "mbedcrypto", "mbedx509"]) + + if not env["builtin_wslay"]: + env.ParseConfig("pkg-config libwslay --cflags --libs") + + if not env["builtin_miniupnpc"]: + # No pkgconfig file so far, hardcode default paths. + env.Prepend(CPPPATH=["/usr/include/miniupnpc"]) + env.Append(LIBS=["miniupnpc"]) + + # On Linux wchar_t should be 32-bits + # 16-bit library shouldn't be required due to compiler optimisations + if not env["builtin_pcre2"]: + env.ParseConfig("pkg-config libpcre2-32 --cflags --libs") + + if not env["builtin_embree"]: + # No pkgconfig file so far, hardcode expected lib name. + env.Append(LIBS=["embree3"]) + + ## Flags + + if os.system("pkg-config --exists alsa") == 0: # 0 means found + print("Enabling ALSA") + env["alsa"] = True + env.Append(CPPDEFINES=["ALSA_ENABLED", "ALSAMIDI_ENABLED"]) + else: + print("ALSA libraries not found, disabling driver") + + if env["pulseaudio"]: + if os.system("pkg-config --exists libpulse") == 0: # 0 means found + print("Enabling PulseAudio") + env.Append(CPPDEFINES=["PULSEAUDIO_ENABLED"]) + env.ParseConfig("pkg-config --cflags libpulse") + else: + print("PulseAudio development libraries not found, disabling driver") + + if env["dbus"]: + if os.system("pkg-config --exists dbus-1") == 0: # 0 means found + print("Enabling D-Bus") + env.Append(CPPDEFINES=["DBUS_ENABLED"]) + env.ParseConfig("pkg-config --cflags --libs dbus-1") + else: + print("D-Bus development libraries not found, disabling dependent features") + + if platform.system() == "Linux": + env.Append(CPPDEFINES=["JOYDEV_ENABLED"]) + if env["udev"]: + if os.system("pkg-config --exists libudev") == 0: # 0 means found + print("Enabling udev support") + env.Append(CPPDEFINES=["UDEV_ENABLED"]) + else: + print("libudev development libraries not found, disabling udev support") + else: + env["udev"] = False # Linux specific + + # Linkflags below this line should typically stay the last ones + if not env["builtin_zlib"]: + env.ParseConfig("pkg-config zlib --cflags --libs") + + env.Prepend(CPPPATH=["#platform/linuxbsd"]) + + if env["x11"]: + if not env["vulkan"]: + print("Error: X11 support requires vulkan=yes") + env.Exit(255) + env.Append(CPPDEFINES=["X11_ENABLED"]) + + env.Append(CPPDEFINES=["UNIX_ENABLED"]) + env.Append(CPPDEFINES=[("_FILE_OFFSET_BITS", 64)]) + + if env["vulkan"]: + env.Append(CPPDEFINES=["VULKAN_ENABLED"]) + if not env["builtin_vulkan"]: + env.ParseConfig("pkg-config vulkan --cflags --libs") + if not env["builtin_glslang"]: + # No pkgconfig file for glslang so far + env.Append(LIBS=["glslang", "SPIRV"]) + + # env.Append(CPPDEFINES=['OPENGL_ENABLED']) + env.Append(LIBS=["GL"]) + + env.Append(LIBS=["pthread"]) + + if platform.system() == "Linux": + env.Append(LIBS=["dl"]) + + if platform.system().find("BSD") >= 0: + env["execinfo"] = True + + if env["execinfo"]: + env.Append(LIBS=["execinfo"]) + + if not env["tools"]: + import subprocess + import re + + linker_version_str = subprocess.check_output([env.subst(env["LINK"]), "-Wl,--version"]).decode("utf-8") + gnu_ld_version = re.search("^GNU ld [^$]*(\d+\.\d+)$", linker_version_str, re.MULTILINE) + if not gnu_ld_version: + print( + "Warning: Creating template binaries enabled for PCK embedding is currently only supported with GNU ld" + ) + else: + if float(gnu_ld_version.group(1)) >= 2.30: + env.Append(LINKFLAGS=["-T", "platform/linuxbsd/pck_embed.ld"]) + else: + env.Append(LINKFLAGS=["-T", "platform/linuxbsd/pck_embed.legacy.ld"]) + + ## Cross-compilation + + if is64 and env["bits"] == "32": + env.Append(CCFLAGS=["-m32"]) + env.Append(LINKFLAGS=["-m32", "-L/usr/lib/i386-linux-gnu"]) + elif not is64 and env["bits"] == "64": + env.Append(CCFLAGS=["-m64"]) + env.Append(LINKFLAGS=["-m64", "-L/usr/lib/i686-linux-gnu"]) + + # Link those statically for portability + if env["use_static_cpp"]: + env.Append(LINKFLAGS=["-static-libgcc", "-static-libstdc++"]) + if env["use_llvm"]: + env["LINKCOM"] = env["LINKCOM"] + " -l:libatomic.a" + + else: + if env["use_llvm"]: + env.Append(LIBS=["atomic"]) diff --git a/platform/linuxbsd/detect_prime_x11.cpp b/platform/linuxbsd/detect_prime_x11.cpp new file mode 100644 index 0000000000..da1c95a593 --- /dev/null +++ b/platform/linuxbsd/detect_prime_x11.cpp @@ -0,0 +1,240 @@ +/*************************************************************************/ +/* detect_prime_x11.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifdef X11_ENABLED +#if defined(OPENGL_ENABLED) + +#include "detect_prime.h" + +#include "core/string/print_string.h" +#include "core/string/ustring.h" + +#include <stdlib.h> + +#include <GL/gl.h> +#include <GL/glx.h> +#include <X11/Xlib.h> +#include <X11/Xutil.h> + +#include <cstring> + +#include <sys/types.h> +#include <sys/wait.h> +#include <unistd.h> + +#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 +#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 + +typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *); + +struct vendor { + const char *glxvendor; + int priority = 0; +}; + +vendor vendormap[] = { + { "Advanced Micro Devices, Inc.", 30 }, + { "AMD", 30 }, + { "NVIDIA Corporation", 30 }, + { "X.Org", 30 }, + { "Intel Open Source Technology Center", 20 }, + { "Intel", 20 }, + { "nouveau", 10 }, + { "Mesa Project", 0 }, + { nullptr, 0 } +}; + +// Runs inside a child. Exiting will not quit the engine. +void create_context() { + Display *x11_display = XOpenDisplay(nullptr); + Window x11_window; + GLXContext glx_context; + + GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB"); + + static int visual_attribs[] = { + GLX_RENDER_TYPE, GLX_RGBA_BIT, + GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, + GLX_DOUBLEBUFFER, true, + GLX_RED_SIZE, 1, + GLX_GREEN_SIZE, 1, + GLX_BLUE_SIZE, 1, + GLX_DEPTH_SIZE, 24, + None + }; + + int fbcount; + GLXFBConfig fbconfig = 0; + XVisualInfo *vi = nullptr; + + XSetWindowAttributes swa; + swa.event_mask = StructureNotifyMask; + swa.border_pixel = 0; + unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask; + + GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount); + if (!fbc) + exit(1); + + vi = glXGetVisualFromFBConfig(x11_display, fbc[0]); + + fbconfig = fbc[0]; + + static int context_attribs[] = { + GLX_CONTEXT_MAJOR_VERSION_ARB, 3, + GLX_CONTEXT_MINOR_VERSION_ARB, 3, + GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, + GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, + None + }; + + glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, nullptr, true, context_attribs); + + swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone); + x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, 10, 10, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa); + + if (!x11_window) + exit(1); + + glXMakeCurrent(x11_display, x11_window, glx_context); + XFree(vi); +} + +int detect_prime() { + pid_t p; + int priorities[2] = {}; + String vendors[2]; + String renderers[2]; + + vendors[0] = "Unknown"; + vendors[1] = "Unknown"; + renderers[0] = "Unknown"; + renderers[1] = "Unknown"; + + for (int i = 0; i < 2; ++i) { + int fdset[2]; + + if (pipe(fdset) == -1) { + print_verbose("Failed to pipe(), using default GPU"); + return 0; + } + + // Fork so the driver initialization can crash without taking down the engine. + p = fork(); + + if (p > 0) { + // Main thread + + int stat_loc = 0; + char string[201]; + string[200] = '\0'; + + close(fdset[1]); + + waitpid(p, &stat_loc, 0); + + if (!stat_loc) { + // No need to do anything complicated here. Anything less than + // PIPE_BUF will be delivered in one read() call. + // Leave it 'Unknown' otherwise. + if (read(fdset[0], string, sizeof(string) - 1) > 0) { + vendors[i] = string; + renderers[i] = string + strlen(string) + 1; + } + } + + close(fdset[0]); + + } else { + // In child, exit() here will not quit the engine. + + char string[201]; + + close(fdset[0]); + + if (i) + setenv("DRI_PRIME", "1", 1); + create_context(); + + const char *vendor = (const char *)glGetString(GL_VENDOR); + const char *renderer = (const char *)glGetString(GL_RENDERER); + + unsigned int vendor_len = strlen(vendor) + 1; + unsigned int renderer_len = strlen(renderer) + 1; + + if (vendor_len + renderer_len >= sizeof(string)) { + renderer_len = 200 - vendor_len; + } + + memcpy(&string, vendor, vendor_len); + memcpy(&string[vendor_len], renderer, renderer_len); + + if (write(fdset[1], string, vendor_len + renderer_len) == -1) { + print_verbose("Couldn't write vendor/renderer string."); + } + close(fdset[1]); + exit(0); + } + } + + int preferred = 0; + int priority = 0; + + if (vendors[0] == vendors[1]) { + print_verbose("Only one GPU found, using default."); + return 0; + } + + for (int i = 1; i >= 0; --i) { + vendor *v = vendormap; + while (v->glxvendor) { + if (v->glxvendor == vendors[i]) { + priorities[i] = v->priority; + + if (v->priority >= priority) { + priority = v->priority; + preferred = i; + } + } + ++v; + } + } + + print_verbose("Found renderers:"); + for (int i = 0; i < 2; ++i) { + print_verbose("Renderer " + itos(i) + ": " + renderers[i] + " with priority: " + itos(priorities[i])); + } + + print_verbose("Using renderer: " + renderers[preferred]); + return preferred; +} + +#endif +#endif diff --git a/platform/linuxbsd/detect_prime_x11.h b/platform/linuxbsd/detect_prime_x11.h new file mode 100644 index 0000000000..0b548b849e --- /dev/null +++ b/platform/linuxbsd/detect_prime_x11.h @@ -0,0 +1,37 @@ +/*************************************************************************/ +/* detect_prime_x11.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifdef X11_ENABLED +#if defined(OPENGL_ENABLED) + +int detect_prime(); + +#endif +#endif diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp new file mode 100644 index 0000000000..fd652c0af2 --- /dev/null +++ b/platform/linuxbsd/display_server_x11.cpp @@ -0,0 +1,4375 @@ +/*************************************************************************/ +/* display_server_x11.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#include "display_server_x11.h" + +#ifdef X11_ENABLED + +#include "core/config/project_settings.h" +#include "core/string/print_string.h" +#include "detect_prime_x11.h" +#include "key_mapping_x11.h" +#include "main/main.h" +#include "scene/resources/texture.h" + +#if defined(VULKAN_ENABLED) +#include "servers/rendering/renderer_rd/renderer_compositor_rd.h" +#endif + +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include <X11/Xatom.h> +#include <X11/Xutil.h> +#include <X11/extensions/Xinerama.h> +#include <X11/extensions/shape.h> + +// ICCCM +#define WM_NormalState 1L // window normal state +#define WM_IconicState 3L // window minimized +// EWMH +#define _NET_WM_STATE_REMOVE 0L // remove/unset property +#define _NET_WM_STATE_ADD 1L // add/set property +#define _NET_WM_STATE_TOGGLE 2L // toggle property + +#include <dlfcn.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> + +//stupid linux.h +#ifdef KEY_TAB +#undef KEY_TAB +#endif + +#undef CursorShape +#include <X11/XKBlib.h> + +// 2.2 is the first release with multitouch +#define XINPUT_CLIENT_VERSION_MAJOR 2 +#define XINPUT_CLIENT_VERSION_MINOR 2 + +#define VALUATOR_ABSX 0 +#define VALUATOR_ABSY 1 +#define VALUATOR_PRESSURE 2 +#define VALUATOR_TILTX 3 +#define VALUATOR_TILTY 4 + +//#define DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED +#ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED +#define DEBUG_LOG_X11(...) printf(__VA_ARGS__) +#else +#define DEBUG_LOG_X11(...) +#endif + +static const double abs_resolution_mult = 10000.0; +static const double abs_resolution_range_mult = 10.0; + +// Hints for X11 fullscreen +struct Hints { + unsigned long flags = 0; + unsigned long functions = 0; + unsigned long decorations = 0; + long inputMode = 0; + unsigned long status = 0; +}; + +bool DisplayServerX11::has_feature(Feature p_feature) const { + switch (p_feature) { + case FEATURE_SUBWINDOWS: +#ifdef TOUCH_ENABLED + case FEATURE_TOUCHSCREEN: +#endif + case FEATURE_MOUSE: + case FEATURE_MOUSE_WARP: + case FEATURE_CLIPBOARD: + case FEATURE_CURSOR_SHAPE: + case FEATURE_CUSTOM_CURSOR_SHAPE: + case FEATURE_IME: + case FEATURE_WINDOW_TRANSPARENCY: + //case FEATURE_HIDPI: + case FEATURE_ICON: + case FEATURE_NATIVE_ICON: + case FEATURE_SWAP_BUFFERS: +#ifdef DBUS_ENABLED + case FEATURE_KEEP_SCREEN_ON: +#endif + return true; + default: { + } + } + + return false; +} + +String DisplayServerX11::get_name() const { + return "X11"; +} + +void DisplayServerX11::alert(const String &p_alert, const String &p_title) { + const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" }; + + String path = OS::get_singleton()->get_environment("PATH"); + Vector<String> path_elems = path.split(":", false); + String program; + + for (int i = 0; i < path_elems.size(); i++) { + for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) { + String tested_path = path_elems[i].plus_file(message_programs[k]); + + if (FileAccess::exists(tested_path)) { + program = tested_path; + break; + } + } + + if (program.length()) { + break; + } + } + + List<String> args; + + if (program.ends_with("zenity")) { + args.push_back("--error"); + args.push_back("--width"); + args.push_back("500"); + args.push_back("--title"); + args.push_back(p_title); + args.push_back("--text"); + args.push_back(p_alert); + } + + if (program.ends_with("kdialog")) { + args.push_back("--error"); + args.push_back(p_alert); + args.push_back("--title"); + args.push_back(p_title); + } + + if (program.ends_with("Xdialog")) { + args.push_back("--title"); + args.push_back(p_title); + args.push_back("--msgbox"); + args.push_back(p_alert); + args.push_back("0"); + args.push_back("0"); + } + + if (program.ends_with("xmessage")) { + args.push_back("-center"); + args.push_back("-title"); + args.push_back(p_title); + args.push_back(p_alert); + } + + if (program.length()) { + OS::get_singleton()->execute(program, args); + } else { + print_line(p_alert); + } +} + +void DisplayServerX11::_update_real_mouse_position(const WindowData &wd) { + Window root_return, child_return; + int root_x, root_y, win_x, win_y; + unsigned int mask_return; + + Bool xquerypointer_result = XQueryPointer(x11_display, wd.x11_window, &root_return, &child_return, &root_x, &root_y, + &win_x, &win_y, &mask_return); + + if (xquerypointer_result) { + if (win_x > 0 && win_y > 0 && win_x <= wd.size.width && win_y <= wd.size.height) { + last_mouse_pos.x = win_x; + last_mouse_pos.y = win_y; + last_mouse_pos_valid = true; + Input::get_singleton()->set_mouse_position(last_mouse_pos); + } + } +} + +bool DisplayServerX11::_refresh_device_info() { + int event_base, error_base; + + print_verbose("XInput: Refreshing devices."); + + if (!XQueryExtension(x11_display, "XInputExtension", &xi.opcode, &event_base, &error_base)) { + print_verbose("XInput extension not available. Please upgrade your distribution."); + return false; + } + + int xi_major_query = XINPUT_CLIENT_VERSION_MAJOR; + int xi_minor_query = XINPUT_CLIENT_VERSION_MINOR; + + if (XIQueryVersion(x11_display, &xi_major_query, &xi_minor_query) != Success) { + print_verbose(vformat("XInput 2 not available (server supports %d.%d).", xi_major_query, xi_minor_query)); + xi.opcode = 0; + return false; + } + + if (xi_major_query < XINPUT_CLIENT_VERSION_MAJOR || (xi_major_query == XINPUT_CLIENT_VERSION_MAJOR && xi_minor_query < XINPUT_CLIENT_VERSION_MINOR)) { + print_verbose(vformat("XInput %d.%d not available (server supports %d.%d). Touch input unavailable.", + XINPUT_CLIENT_VERSION_MAJOR, XINPUT_CLIENT_VERSION_MINOR, xi_major_query, xi_minor_query)); + } + + xi.absolute_devices.clear(); + xi.touch_devices.clear(); + + int dev_count; + XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count); + + for (int i = 0; i < dev_count; i++) { + XIDeviceInfo *dev = &info[i]; + if (!dev->enabled) { + continue; + } + if (!(dev->use == XIMasterPointer || dev->use == XIFloatingSlave)) { + continue; + } + + bool direct_touch = false; + bool absolute_mode = false; + int resolution_x = 0; + int resolution_y = 0; + double abs_x_min = 0; + double abs_x_max = 0; + double abs_y_min = 0; + double abs_y_max = 0; + double pressure_min = 0; + double pressure_max = 0; + double tilt_x_min = 0; + double tilt_x_max = 0; + double tilt_y_min = 0; + double tilt_y_max = 0; + for (int j = 0; j < dev->num_classes; j++) { +#ifdef TOUCH_ENABLED + if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) { + direct_touch = true; + } +#endif + if (dev->classes[j]->type == XIValuatorClass) { + XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)dev->classes[j]; + + if (class_info->number == VALUATOR_ABSX && class_info->mode == XIModeAbsolute) { + resolution_x = class_info->resolution; + abs_x_min = class_info->min; + abs_y_max = class_info->max; + absolute_mode = true; + } else if (class_info->number == VALUATOR_ABSY && class_info->mode == XIModeAbsolute) { + resolution_y = class_info->resolution; + abs_y_min = class_info->min; + abs_y_max = class_info->max; + absolute_mode = true; + } else if (class_info->number == VALUATOR_PRESSURE && class_info->mode == XIModeAbsolute) { + pressure_min = class_info->min; + pressure_max = class_info->max; + } else if (class_info->number == VALUATOR_TILTX && class_info->mode == XIModeAbsolute) { + tilt_x_min = class_info->min; + tilt_x_max = class_info->max; + } else if (class_info->number == VALUATOR_TILTY && class_info->mode == XIModeAbsolute) { + tilt_x_min = class_info->min; + tilt_x_max = class_info->max; + } + } + } + if (direct_touch) { + xi.touch_devices.push_back(dev->deviceid); + print_verbose("XInput: Using touch device: " + String(dev->name)); + } + if (absolute_mode) { + // If no resolution was reported, use the min/max ranges. + if (resolution_x <= 0) { + resolution_x = (abs_x_max - abs_x_min) * abs_resolution_range_mult; + } + if (resolution_y <= 0) { + resolution_y = (abs_y_max - abs_y_min) * abs_resolution_range_mult; + } + xi.absolute_devices[dev->deviceid] = Vector2(abs_resolution_mult / resolution_x, abs_resolution_mult / resolution_y); + print_verbose("XInput: Absolute pointing device: " + String(dev->name)); + } + + xi.pressure = 0; + xi.pen_pressure_range[dev->deviceid] = Vector2(pressure_min, pressure_max); + xi.pen_tilt_x_range[dev->deviceid] = Vector2(tilt_x_min, tilt_x_max); + xi.pen_tilt_y_range[dev->deviceid] = Vector2(tilt_y_min, tilt_y_max); + } + + XIFreeDeviceInfo(info); +#ifdef TOUCH_ENABLED + if (!xi.touch_devices.size()) { + print_verbose("XInput: No touch devices found."); + } +#endif + + return true; +} + +void DisplayServerX11::_flush_mouse_motion() { + // Block events polling while flushing motion events. + MutexLock mutex_lock(events_mutex); + + for (uint32_t event_index = 0; event_index < polled_events.size(); ++event_index) { + XEvent &event = polled_events[event_index]; + if (XGetEventData(x11_display, &event.xcookie) && event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { + XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; + if (event_data->evtype == XI_RawMotion) { + XFreeEventData(x11_display, &event.xcookie); + polled_events.remove(event_index--); + continue; + } + XFreeEventData(x11_display, &event.xcookie); + break; + } + } + + xi.relative_motion.x = 0; + xi.relative_motion.y = 0; +} + +void DisplayServerX11::mouse_set_mode(MouseMode p_mode) { + _THREAD_SAFE_METHOD_ + + if (p_mode == mouse_mode) { + return; + } + + if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) { + XUngrabPointer(x11_display, CurrentTime); + } + + // The only modes that show a cursor are VISIBLE and CONFINED + bool showCursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED); + + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + if (showCursor) { + XDefineCursor(x11_display, E->get().x11_window, cursors[current_cursor]); // show cursor + } else { + XDefineCursor(x11_display, E->get().x11_window, null_cursor); // hide cursor + } + } + mouse_mode = p_mode; + + if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) { + //flush pending motion events + _flush_mouse_motion(); + WindowData &main_window = windows[MAIN_WINDOW_ID]; + + if (XGrabPointer( + x11_display, main_window.x11_window, True, + ButtonPressMask | ButtonReleaseMask | PointerMotionMask, + GrabModeAsync, GrabModeAsync, windows[MAIN_WINDOW_ID].x11_window, None, CurrentTime) != GrabSuccess) { + ERR_PRINT("NO GRAB"); + } + + if (mouse_mode == MOUSE_MODE_CAPTURED) { + center.x = main_window.size.width / 2; + center.y = main_window.size.height / 2; + + XWarpPointer(x11_display, None, main_window.x11_window, + 0, 0, 0, 0, (int)center.x, (int)center.y); + + Input::get_singleton()->set_mouse_position(center); + } + } else { + do_mouse_warp = false; + } + + XFlush(x11_display); +} + +DisplayServerX11::MouseMode DisplayServerX11::mouse_get_mode() const { + return mouse_mode; +} + +void DisplayServerX11::mouse_warp_to_position(const Point2i &p_to) { + _THREAD_SAFE_METHOD_ + + if (mouse_mode == MOUSE_MODE_CAPTURED) { + last_mouse_pos = p_to; + } else { + XWarpPointer(x11_display, None, windows[MAIN_WINDOW_ID].x11_window, + 0, 0, 0, 0, (int)p_to.x, (int)p_to.y); + } +} + +Point2i DisplayServerX11::mouse_get_position() const { + int root_x, root_y; + int win_x, win_y; + unsigned int mask_return; + Window window_returned; + + Bool result = XQueryPointer(x11_display, RootWindow(x11_display, DefaultScreen(x11_display)), &window_returned, + &window_returned, &root_x, &root_y, &win_x, &win_y, + &mask_return); + if (result == True) { + return Point2i(root_x, root_y); + } + return Point2i(); +} + +Point2i DisplayServerX11::mouse_get_absolute_position() const { + int number_of_screens = XScreenCount(x11_display); + for (int i = 0; i < number_of_screens; i++) { + Window root, child; + int root_x, root_y, win_x, win_y; + unsigned int mask; + if (XQueryPointer(x11_display, XRootWindow(x11_display, i), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask)) { + XWindowAttributes root_attrs; + XGetWindowAttributes(x11_display, root, &root_attrs); + + return Vector2i(root_attrs.x + root_x, root_attrs.y + root_y); + } + } + return Vector2i(); +} + +MouseButton DisplayServerX11::mouse_get_button_state() const { + return last_button_state; +} + +void DisplayServerX11::clipboard_set(const String &p_text) { + _THREAD_SAFE_METHOD_ + + { + // The clipboard content can be accessed while polling for events. + MutexLock mutex_lock(events_mutex); + internal_clipboard = p_text; + } + + XSetSelectionOwner(x11_display, XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window, CurrentTime); + XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), windows[MAIN_WINDOW_ID].x11_window, CurrentTime); +} + +Bool DisplayServerX11::_predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg) { + if (event->type == SelectionNotify && event->xselection.requestor == *(Window *)arg) { + return True; + } else { + return False; + } +} + +Bool DisplayServerX11::_predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg) { + if (event->type == PropertyNotify && event->xproperty.state == PropertyNewValue) { + return True; + } else { + return False; + } +} + +String DisplayServerX11::_clipboard_get_impl(Atom p_source, Window x11_window, Atom target) const { + String ret; + + Window selection_owner = XGetSelectionOwner(x11_display, p_source); + if (selection_owner == x11_window) { + return internal_clipboard; + } + + if (selection_owner != None) { + // Block events polling while processing selection events. + MutexLock mutex_lock(events_mutex); + + Atom selection = XA_PRIMARY; + XConvertSelection(x11_display, p_source, target, selection, + x11_window, CurrentTime); + + XFlush(x11_display); + + // Blocking wait for predicate to be True and remove the event from the queue. + XEvent event; + XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window); + + // Do not get any data, see how much data is there. + Atom type; + int format, result; + unsigned long len, bytes_left, dummy; + unsigned char *data; + XGetWindowProperty(x11_display, x11_window, + selection, // Tricky.. + 0, 0, // offset - len + 0, // Delete 0==FALSE + AnyPropertyType, // flag + &type, // return type + &format, // return format + &len, &bytes_left, // data length + &data); + + if (data) { + XFree(data); + } + + if (type == XInternAtom(x11_display, "INCR", 0)) { + // Data is going to be received incrementally. + DEBUG_LOG_X11("INCR selection started.\n"); + + LocalVector<uint8_t> incr_data; + uint32_t data_size = 0; + bool success = false; + + // Delete INCR property to notify the owner. + XDeleteProperty(x11_display, x11_window, type); + + // Process events from the queue. + bool done = false; + while (!done) { + if (!_wait_for_events()) { + // Error or timeout, abort. + break; + } + + // Non-blocking wait for next event and remove it from the queue. + XEvent ev; + while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, nullptr)) { + result = XGetWindowProperty(x11_display, x11_window, + selection, // selection type + 0, LONG_MAX, // offset - len + True, // delete property to notify the owner + AnyPropertyType, // flag + &type, // return type + &format, // return format + &len, &bytes_left, // data length + &data); + + DEBUG_LOG_X11("PropertyNotify: len=%lu, format=%i\n", len, format); + + if (result == Success) { + if (data && (len > 0)) { + uint32_t prev_size = incr_data.size(); + if (prev_size == 0) { + // First property contains initial data size. + unsigned long initial_size = *(unsigned long *)data; + incr_data.resize(initial_size); + } else { + // New chunk, resize to be safe and append data. + incr_data.resize(MAX(data_size + len, prev_size)); + memcpy(incr_data.ptr() + data_size, data, len); + data_size += len; + } + } else { + // Last chunk, process finished. + done = true; + success = true; + } + } else { + printf("Failed to get selection data chunk.\n"); + done = true; + } + + if (data) { + XFree(data); + } + + if (done) { + break; + } + } + } + + if (success && (data_size > 0)) { + ret.parse_utf8((const char *)incr_data.ptr(), data_size); + } + } else if (bytes_left > 0) { + // Data is ready and can be processed all at once. + result = XGetWindowProperty(x11_display, x11_window, + selection, 0, bytes_left, 0, + AnyPropertyType, &type, &format, + &len, &dummy, &data); + + if (result == Success) { + ret.parse_utf8((const char *)data); + } else { + printf("Failed to get selection data.\n"); + } + + if (data) { + XFree(data); + } + } + } + + return ret; +} + +String DisplayServerX11::_clipboard_get(Atom p_source, Window x11_window) const { + String ret; + Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True); + if (utf8_atom != None) { + ret = _clipboard_get_impl(p_source, x11_window, utf8_atom); + } + if (ret.is_empty()) { + ret = _clipboard_get_impl(p_source, x11_window, XA_STRING); + } + return ret; +} + +String DisplayServerX11::clipboard_get() const { + _THREAD_SAFE_METHOD_ + + String ret; + ret = _clipboard_get(XInternAtom(x11_display, "CLIPBOARD", 0), windows[MAIN_WINDOW_ID].x11_window); + + if (ret.is_empty()) { + ret = _clipboard_get(XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window); + } + + return ret; +} + +Bool DisplayServerX11::_predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg) { + if (event->xany.window == *(Window *)arg) { + return (event->type == SelectionRequest) || + (event->type == SelectionNotify); + } else { + return False; + } +} + +void DisplayServerX11::_clipboard_transfer_ownership(Atom p_source, Window x11_window) const { + _THREAD_SAFE_METHOD_ + + Window selection_owner = XGetSelectionOwner(x11_display, p_source); + + if (selection_owner != x11_window) { + return; + } + + // Block events polling while processing selection events. + MutexLock mutex_lock(events_mutex); + + Atom clipboard_manager = XInternAtom(x11_display, "CLIPBOARD_MANAGER", False); + Atom save_targets = XInternAtom(x11_display, "SAVE_TARGETS", False); + XConvertSelection(x11_display, clipboard_manager, save_targets, None, + x11_window, CurrentTime); + + // Process events from the queue. + while (true) { + if (!_wait_for_events()) { + // Error or timeout, abort. + break; + } + + // Non-blocking wait for next event and remove it from the queue. + XEvent ev; + while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_save_targets, (XPointer)&x11_window)) { + switch (ev.type) { + case SelectionRequest: + _handle_selection_request_event(&(ev.xselectionrequest)); + break; + + case SelectionNotify: { + if (ev.xselection.target == save_targets) { + // Once SelectionNotify is received, we're done whether it succeeded or not. + return; + } + + break; + } + } + } + } +} + +int DisplayServerX11::get_screen_count() const { + _THREAD_SAFE_METHOD_ + + // Using Xinerama Extension + int event_base, error_base; + const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); + if (!ext_okay) { + return 0; + } + + int count; + XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); + XFree(xsi); + return count; +} + +Point2i DisplayServerX11::screen_get_position(int p_screen) const { + _THREAD_SAFE_METHOD_ + + if (p_screen == SCREEN_OF_MAIN_WINDOW) { + p_screen = window_get_current_screen(); + } + + // Using Xinerama Extension + int event_base, error_base; + const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); + if (!ext_okay) { + return Point2i(0, 0); + } + + int count; + XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); + + // Check if screen is valid + ERR_FAIL_INDEX_V(p_screen, count, Point2i(0, 0)); + + Point2i position = Point2i(xsi[p_screen].x_org, xsi[p_screen].y_org); + + XFree(xsi); + + return position; +} + +Size2i DisplayServerX11::screen_get_size(int p_screen) const { + return screen_get_usable_rect(p_screen).size; +} + +Rect2i DisplayServerX11::screen_get_usable_rect(int p_screen) const { + _THREAD_SAFE_METHOD_ + + if (p_screen == SCREEN_OF_MAIN_WINDOW) { + p_screen = window_get_current_screen(); + } + + // Using Xinerama Extension + int event_base, error_base; + const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); + if (!ext_okay) { + return Rect2i(0, 0, 0, 0); + } + + int count; + XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); + + // Check if screen is valid + ERR_FAIL_INDEX_V(p_screen, count, Rect2i(0, 0, 0, 0)); + + Rect2i rect = Rect2i(xsi[p_screen].x_org, xsi[p_screen].y_org, xsi[p_screen].width, xsi[p_screen].height); + XFree(xsi); + return rect; +} + +int DisplayServerX11::screen_get_dpi(int p_screen) const { + _THREAD_SAFE_METHOD_ + + if (p_screen == SCREEN_OF_MAIN_WINDOW) { + p_screen = window_get_current_screen(); + } + + //invalid screen? + ERR_FAIL_INDEX_V(p_screen, get_screen_count(), 0); + + //Get physical monitor Dimensions through XRandR and calculate dpi + Size2i sc = screen_get_size(p_screen); + if (xrandr_ext_ok) { + int count = 0; + if (xrr_get_monitors) { + xrr_monitor_info *monitors = xrr_get_monitors(x11_display, windows[MAIN_WINDOW_ID].x11_window, true, &count); + if (p_screen < count) { + double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4; + double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4; + xrr_free_monitors(monitors); + return (xdpi + ydpi) / 2; + } + xrr_free_monitors(monitors); + } else if (p_screen == 0) { + XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count); + if (sizes) { + double xdpi = sc.width / (double)sizes[0].mwidth * 25.4; + double ydpi = sc.height / (double)sizes[0].mheight * 25.4; + return (xdpi + ydpi) / 2; + } + } + } + + int width_mm = DisplayWidthMM(x11_display, p_screen); + int height_mm = DisplayHeightMM(x11_display, p_screen); + double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0); + double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0); + if (xdpi || ydpi) { + return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1); + } + + //could not get dpi + return 96; +} + +bool DisplayServerX11::screen_is_touchscreen(int p_screen) const { + _THREAD_SAFE_METHOD_ + +#ifndef _MSC_VER +#warning Need to get from proper window +#endif + + return DisplayServer::screen_is_touchscreen(p_screen); +} + +#ifdef DBUS_ENABLED +void DisplayServerX11::screen_set_keep_on(bool p_enable) { + if (screen_is_kept_on() == p_enable) { + return; + } + + if (p_enable) { + screensaver->inhibit(); + } else { + screensaver->uninhibit(); + } + + keep_screen_on = p_enable; +} + +bool DisplayServerX11::screen_is_kept_on() const { + return keep_screen_on; +} +#endif + +Vector<DisplayServer::WindowID> DisplayServerX11::get_window_list() const { + _THREAD_SAFE_METHOD_ + + Vector<int> ret; + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + ret.push_back(E->key()); + } + return ret; +} + +DisplayServer::WindowID DisplayServerX11::create_sub_window(WindowMode p_mode, uint32_t p_flags, const Rect2i &p_rect) { + _THREAD_SAFE_METHOD_ + + WindowID id = _create_window(p_mode, p_flags, p_rect); + for (int i = 0; i < WINDOW_FLAG_MAX; i++) { + if (p_flags & (1 << i)) { + window_set_flag(WindowFlags(i), true, id); + } + } + + return id; +} + +void DisplayServerX11::show_window(WindowID p_id) { + _THREAD_SAFE_METHOD_ + + WindowData &wd = windows[p_id]; + + XMapWindow(x11_display, wd.x11_window); +} + +void DisplayServerX11::delete_sub_window(WindowID p_id) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_id)); + ERR_FAIL_COND_MSG(p_id == MAIN_WINDOW_ID, "Main window can't be deleted"); //ma + + WindowData &wd = windows[p_id]; + + DEBUG_LOG_X11("delete_sub_window: %lu (%u) \n", wd.x11_window, p_id); + + while (wd.transient_children.size()) { + window_set_transient(wd.transient_children.front()->get(), INVALID_WINDOW_ID); + } + + if (wd.transient_parent != INVALID_WINDOW_ID) { + window_set_transient(p_id, INVALID_WINDOW_ID); + } + +#ifdef VULKAN_ENABLED + if (rendering_driver == "vulkan") { + context_vulkan->window_destroy(p_id); + } +#endif + XUnmapWindow(x11_display, wd.x11_window); + XDestroyWindow(x11_display, wd.x11_window); + if (wd.xic) { + XDestroyIC(wd.xic); + wd.xic = nullptr; + } + + windows.erase(p_id); +} + +void DisplayServerX11::window_attach_instance_id(ObjectID p_instance, WindowID p_window) { + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + wd.instance_id = p_instance; +} + +ObjectID DisplayServerX11::window_get_attached_instance_id(WindowID p_window) const { + ERR_FAIL_COND_V(!windows.has(p_window), ObjectID()); + const WindowData &wd = windows[p_window]; + return wd.instance_id; +} + +DisplayServerX11::WindowID DisplayServerX11::get_window_at_screen_position(const Point2i &p_position) const { + WindowID found_window = INVALID_WINDOW_ID; + WindowID parent_window = INVALID_WINDOW_ID; + unsigned int focus_order = 0; + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + const WindowData &wd = E->get(); + + // Discard windows with no focus. + if (wd.focus_order == 0) { + continue; + } + + // Find topmost window which contains the given position. + WindowID window_id = E->key(); + Rect2i win_rect = Rect2i(window_get_position(window_id), window_get_size(window_id)); + if (win_rect.has_point(p_position)) { + // For siblings, pick the window which was focused last. + if ((parent_window != wd.transient_parent) || (wd.focus_order > focus_order)) { + found_window = window_id; + parent_window = wd.transient_parent; + focus_order = wd.focus_order; + } + } + } + + return found_window; +} + +void DisplayServerX11::window_set_title(const String &p_title, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + XStoreName(x11_display, wd.x11_window, p_title.utf8().get_data()); + + Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false); + Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false); + if (_net_wm_name != None && utf8_string != None) { + XChangeProperty(x11_display, wd.x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length()); + } +} + +void DisplayServerX11::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + const WindowData &wd = windows[p_window]; + + int event_base, error_base; + const Bool ext_okay = XShapeQueryExtension(x11_display, &event_base, &error_base); + if (ext_okay) { + Region region; + if (p_region.size() == 0) { + region = XCreateRegion(); + XRectangle rect; + rect.x = 0; + rect.y = 0; + rect.width = window_get_real_size(p_window).x; + rect.height = window_get_real_size(p_window).y; + XUnionRectWithRegion(&rect, region, region); + } else { + XPoint *points = (XPoint *)memalloc(sizeof(XPoint) * p_region.size()); + for (int i = 0; i < p_region.size(); i++) { + points[i].x = p_region[i].x; + points[i].y = p_region[i].y; + } + region = XPolygonRegion(points, p_region.size(), EvenOddRule); + memfree(points); + } + XShapeCombineRegion(x11_display, wd.x11_window, ShapeInput, 0, 0, region, ShapeSet); + XDestroyRegion(region); + } +} + +void DisplayServerX11::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + wd.rect_changed_callback = p_callable; +} + +void DisplayServerX11::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + wd.event_callback = p_callable; +} + +void DisplayServerX11::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + wd.input_event_callback = p_callable; +} + +void DisplayServerX11::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + wd.input_text_callback = p_callable; +} + +void DisplayServerX11::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + wd.drop_files_callback = p_callable; +} + +int DisplayServerX11::window_get_current_screen(WindowID p_window) const { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!windows.has(p_window), -1); + const WindowData &wd = windows[p_window]; + + int x, y; + Window child; + XTranslateCoordinates(x11_display, wd.x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); + + int count = get_screen_count(); + for (int i = 0; i < count; i++) { + Point2i pos = screen_get_position(i); + Size2i size = screen_get_size(i); + if ((x >= pos.x && x < pos.x + size.width) && (y >= pos.y && y < pos.y + size.height)) { + return i; + } + } + return 0; +} + +void DisplayServerX11::window_set_current_screen(int p_screen, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + if (p_screen == SCREEN_OF_MAIN_WINDOW) { + p_screen = window_get_current_screen(); + } + + // Check if screen is valid + ERR_FAIL_INDEX(p_screen, get_screen_count()); + + if (window_get_mode(p_window) == WINDOW_MODE_FULLSCREEN) { + Point2i position = screen_get_position(p_screen); + Size2i size = screen_get_size(p_screen); + + XMoveResizeWindow(x11_display, wd.x11_window, position.x, position.y, size.x, size.y); + } else { + if (p_screen != window_get_current_screen(p_window)) { + Point2i position = screen_get_position(p_screen); + XMoveWindow(x11_display, wd.x11_window, position.x, position.y); + } + } +} + +void DisplayServerX11::window_set_transient(WindowID p_window, WindowID p_parent) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(p_window == p_parent); + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd_window = windows[p_window]; + + WindowID prev_parent = wd_window.transient_parent; + ERR_FAIL_COND(prev_parent == p_parent); + + ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient."); + if (p_parent == INVALID_WINDOW_ID) { + //remove transient + + ERR_FAIL_COND(prev_parent == INVALID_WINDOW_ID); + ERR_FAIL_COND(!windows.has(prev_parent)); + + WindowData &wd_parent = windows[prev_parent]; + + wd_window.transient_parent = INVALID_WINDOW_ID; + wd_parent.transient_children.erase(p_window); + + XSetTransientForHint(x11_display, wd_window.x11_window, None); + + // Set focus to parent sub window to avoid losing all focus with nested menus. + // RevertToPointerRoot is used to make sure we don't lose all focus in case + // a subwindow and its parent are both destroyed. + if (wd_window.menu_type && !wd_window.no_focus) { + if (!wd_parent.no_focus) { + XSetInputFocus(x11_display, wd_parent.x11_window, RevertToPointerRoot, CurrentTime); + } + } + } else { + ERR_FAIL_COND(!windows.has(p_parent)); + ERR_FAIL_COND_MSG(prev_parent != INVALID_WINDOW_ID, "Window already has a transient parent"); + WindowData &wd_parent = windows[p_parent]; + + wd_window.transient_parent = p_parent; + wd_parent.transient_children.insert(p_window); + + XSetTransientForHint(x11_display, wd_window.x11_window, wd_parent.x11_window); + } +} + +// Helper method. Assumes that the window id has already been checked and exists. +void DisplayServerX11::_update_size_hints(WindowID p_window) { + WindowData &wd = windows[p_window]; + WindowMode window_mode = window_get_mode(p_window); + XSizeHints *xsh = XAllocSizeHints(); + + // Always set the position and size hints - they should be synchronized with the actual values after the window is mapped anyway + xsh->flags |= PPosition | PSize; + xsh->x = wd.position.x; + xsh->y = wd.position.y; + xsh->width = wd.size.width; + xsh->height = wd.size.height; + + if (window_mode == WINDOW_MODE_FULLSCREEN) { + // Do not set any other hints to prevent the window manager from ignoring the fullscreen flags + } else if (window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) { + // If resizing is disabled, use the forced size + xsh->flags |= PMinSize | PMaxSize; + xsh->min_width = wd.size.x; + xsh->max_width = wd.size.x; + xsh->min_height = wd.size.y; + xsh->max_height = wd.size.y; + } else { + // Otherwise, just respect min_size and max_size + if (wd.min_size != Size2i()) { + xsh->flags |= PMinSize; + xsh->min_width = wd.min_size.x; + xsh->min_height = wd.min_size.y; + } + if (wd.max_size != Size2i()) { + xsh->flags |= PMaxSize; + xsh->max_width = wd.max_size.x; + xsh->max_height = wd.max_size.y; + } + } + + XSetWMNormalHints(x11_display, wd.x11_window, xsh); + XFree(xsh); +} + +Point2i DisplayServerX11::window_get_position(WindowID p_window) const { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!windows.has(p_window), Point2i()); + const WindowData &wd = windows[p_window]; + + return wd.position; +} + +void DisplayServerX11::window_set_position(const Point2i &p_position, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + int x = 0; + int y = 0; + if (!window_get_flag(WINDOW_FLAG_BORDERLESS, p_window)) { + //exclude window decorations + XSync(x11_display, False); + Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); + if (prop != None) { + Atom type; + int format; + unsigned long len; + unsigned long remaining; + unsigned char *data = nullptr; + if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { + if (format == 32 && len == 4 && data) { + long *extents = (long *)data; + x = extents[0]; + y = extents[2]; + } + XFree(data); + } + } + } + XMoveWindow(x11_display, wd.x11_window, p_position.x - x, p_position.y - y); + _update_real_mouse_position(wd); +} + +void DisplayServerX11::window_set_max_size(const Size2i p_size, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + if ((p_size != Size2i()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) { + ERR_PRINT("Maximum window size can't be smaller than minimum window size!"); + return; + } + wd.max_size = p_size; + + _update_size_hints(p_window); + XFlush(x11_display); +} + +Size2i DisplayServerX11::window_get_max_size(WindowID p_window) const { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!windows.has(p_window), Size2i()); + const WindowData &wd = windows[p_window]; + + return wd.max_size; +} + +void DisplayServerX11::window_set_min_size(const Size2i p_size, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + if ((p_size != Size2i()) && (wd.max_size != Size2i()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) { + ERR_PRINT("Minimum window size can't be larger than maximum window size!"); + return; + } + wd.min_size = p_size; + + _update_size_hints(p_window); + XFlush(x11_display); +} + +Size2i DisplayServerX11::window_get_min_size(WindowID p_window) const { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!windows.has(p_window), Size2i()); + const WindowData &wd = windows[p_window]; + + return wd.min_size; +} + +void DisplayServerX11::window_set_size(const Size2i p_size, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + + Size2i size = p_size; + size.x = MAX(1, size.x); + size.y = MAX(1, size.y); + + WindowData &wd = windows[p_window]; + + if (wd.size.width == size.width && wd.size.height == size.height) { + return; + } + + XWindowAttributes xwa; + XSync(x11_display, False); + XGetWindowAttributes(x11_display, wd.x11_window, &xwa); + int old_w = xwa.width; + int old_h = xwa.height; + + // Update our videomode width and height + wd.size = size; + + // Update the size hints first to make sure the window size can be set + _update_size_hints(p_window); + + // Resize the window + XResizeWindow(x11_display, wd.x11_window, size.x, size.y); + + for (int timeout = 0; timeout < 50; ++timeout) { + XSync(x11_display, False); + XGetWindowAttributes(x11_display, wd.x11_window, &xwa); + + if (old_w != xwa.width || old_h != xwa.height) { + break; + } + + usleep(10000); + } +} + +Size2i DisplayServerX11::window_get_size(WindowID p_window) const { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!windows.has(p_window), Size2i()); + const WindowData &wd = windows[p_window]; + return wd.size; +} + +Size2i DisplayServerX11::window_get_real_size(WindowID p_window) const { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!windows.has(p_window), Size2i()); + const WindowData &wd = windows[p_window]; + + XWindowAttributes xwa; + XSync(x11_display, False); + XGetWindowAttributes(x11_display, wd.x11_window, &xwa); + int w = xwa.width; + int h = xwa.height; + Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); + if (prop != None) { + Atom type; + int format; + unsigned long len; + unsigned long remaining; + unsigned char *data = nullptr; + if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { + if (format == 32 && len == 4 && data) { + long *extents = (long *)data; + w += extents[0] + extents[1]; // left, right + h += extents[2] + extents[3]; // top, bottom + } + XFree(data); + } + } + return Size2i(w, h); +} + +// Just a helper to reduce code duplication in `window_is_maximize_allowed` +// and `_set_wm_maximized`. +bool DisplayServerX11::_window_maximize_check(WindowID p_window, const char *p_atom_name) const { + ERR_FAIL_COND_V(!windows.has(p_window), false); + const WindowData &wd = windows[p_window]; + + Atom property = XInternAtom(x11_display, p_atom_name, False); + Atom type; + int format; + unsigned long len; + unsigned long remaining; + unsigned char *data = nullptr; + bool retval = false; + + if (property == None) { + return false; + } + + int result = XGetWindowProperty( + x11_display, + wd.x11_window, + property, + 0, + 1024, + False, + XA_ATOM, + &type, + &format, + &len, + &remaining, + &data); + + if (result == Success && data) { + Atom *atoms = (Atom *)data; + Atom wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False); + Atom wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False); + bool found_wm_act_max_horz = false; + bool found_wm_act_max_vert = false; + + for (uint64_t i = 0; i < len; i++) { + if (atoms[i] == wm_act_max_horz) { + found_wm_act_max_horz = true; + } + if (atoms[i] == wm_act_max_vert) { + found_wm_act_max_vert = true; + } + + if (found_wm_act_max_horz || found_wm_act_max_vert) { + retval = true; + break; + } + } + + XFree(data); + } + + return retval; +} + +bool DisplayServerX11::window_is_maximize_allowed(WindowID p_window) const { + _THREAD_SAFE_METHOD_ + return _window_maximize_check(p_window, "_NET_WM_ALLOWED_ACTIONS"); +} + +void DisplayServerX11::_set_wm_maximized(WindowID p_window, bool p_enabled) { + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + // Using EWMH -- Extended Window Manager Hints + XEvent xev; + Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); + Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False); + Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False); + + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.xclient.window = wd.x11_window; + xev.xclient.message_type = wm_state; + xev.xclient.format = 32; + xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; + xev.xclient.data.l[1] = wm_max_horz; + xev.xclient.data.l[2] = wm_max_vert; + + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + + if (p_enabled && window_is_maximize_allowed(p_window)) { + // Wait for effective resizing (so the GLX context is too). + // Give up after 0.5s, it's not going to happen on this WM. + // https://github.com/godotengine/godot/issues/19978 + for (int attempt = 0; window_get_mode(p_window) != WINDOW_MODE_MAXIMIZED && attempt < 50; attempt++) { + usleep(10000); + } + } +} + +void DisplayServerX11::_set_wm_fullscreen(WindowID p_window, bool p_enabled) { + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + if (p_enabled && !window_get_flag(WINDOW_FLAG_BORDERLESS, p_window)) { + // remove decorations if the window is not already borderless + Hints hints; + Atom property; + hints.flags = 2; + hints.decorations = 0; + property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); + if (property != None) { + XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); + } + } + + if (p_enabled) { + // Set the window as resizable to prevent window managers to ignore the fullscreen state flag. + _update_size_hints(p_window); + } + + // Using EWMH -- Extended Window Manager Hints + XEvent xev; + Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); + Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False); + + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.xclient.window = wd.x11_window; + xev.xclient.message_type = wm_state; + xev.xclient.format = 32; + xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; + xev.xclient.data.l[1] = wm_fullscreen; + xev.xclient.data.l[2] = 0; + + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + + // set bypass compositor hint + Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False); + unsigned long compositing_disable_on = p_enabled ? 1 : 0; + if (bypass_compositor != None) { + XChangeProperty(x11_display, wd.x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1); + } + + XFlush(x11_display); + + if (!p_enabled) { + // Reset the non-resizable flags if we un-set these before. + _update_size_hints(p_window); + + // put back or remove decorations according to the last set borderless state + Hints hints; + Atom property; + hints.flags = 2; + hints.decorations = window_get_flag(WINDOW_FLAG_BORDERLESS, p_window) ? 0 : 1; + property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); + if (property != None) { + XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); + } + } +} + +void DisplayServerX11::window_set_mode(WindowMode p_mode, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + WindowMode old_mode = window_get_mode(p_window); + if (old_mode == p_mode) { + return; // do nothing + } + //remove all "extra" modes + + switch (old_mode) { + case WINDOW_MODE_WINDOWED: { + //do nothing + } break; + case WINDOW_MODE_MINIMIZED: { + //Un-Minimize + // Using ICCCM -- Inter-Client Communication Conventions Manual + XEvent xev; + Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False); + + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.xclient.window = wd.x11_window; + xev.xclient.message_type = wm_change; + xev.xclient.format = 32; + xev.xclient.data.l[0] = WM_NormalState; + + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + + Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); + Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False); + + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.xclient.window = wd.x11_window; + xev.xclient.message_type = wm_state; + xev.xclient.format = 32; + xev.xclient.data.l[0] = _NET_WM_STATE_ADD; + xev.xclient.data.l[1] = wm_hidden; + + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + } break; + case WINDOW_MODE_FULLSCREEN: { + //Remove full-screen + wd.fullscreen = false; + + _set_wm_fullscreen(p_window, false); + + //un-maximize required for always on top + bool on_top = window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window); + + window_set_position(wd.last_position_before_fs, p_window); + + if (on_top) { + _set_wm_maximized(p_window, false); + } + + } break; + case WINDOW_MODE_MAXIMIZED: { + _set_wm_maximized(p_window, false); + } break; + } + + switch (p_mode) { + case WINDOW_MODE_WINDOWED: { + //do nothing + } break; + case WINDOW_MODE_MINIMIZED: { + // Using ICCCM -- Inter-Client Communication Conventions Manual + XEvent xev; + Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False); + + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.xclient.window = wd.x11_window; + xev.xclient.message_type = wm_change; + xev.xclient.format = 32; + xev.xclient.data.l[0] = WM_IconicState; + + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + + Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); + Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False); + + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.xclient.window = wd.x11_window; + xev.xclient.message_type = wm_state; + xev.xclient.format = 32; + xev.xclient.data.l[0] = _NET_WM_STATE_ADD; + xev.xclient.data.l[1] = wm_hidden; + + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + } break; + case WINDOW_MODE_FULLSCREEN: { + wd.last_position_before_fs = wd.position; + + if (window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window)) { + _set_wm_maximized(p_window, true); + } + + wd.fullscreen = true; + _set_wm_fullscreen(p_window, true); + } break; + case WINDOW_MODE_MAXIMIZED: { + _set_wm_maximized(p_window, true); + } break; + } +} + +DisplayServer::WindowMode DisplayServerX11::window_get_mode(WindowID p_window) const { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED); + const WindowData &wd = windows[p_window]; + + if (wd.fullscreen) { //if fullscreen, it's not in another mode + return WINDOW_MODE_FULLSCREEN; + } + + // Test maximized. + // Using EWMH -- Extended Window Manager Hints + if (_window_maximize_check(p_window, "_NET_WM_STATE")) { + return WINDOW_MODE_MAXIMIZED; + } + + { // Test minimized. + // Using ICCCM -- Inter-Client Communication Conventions Manual + Atom property = XInternAtom(x11_display, "WM_STATE", True); + if (property == None) { + return WINDOW_MODE_WINDOWED; + } + + Atom type; + int format; + unsigned long len; + unsigned long remaining; + unsigned char *data = nullptr; + + int result = XGetWindowProperty( + x11_display, + wd.x11_window, + property, + 0, + 32, + False, + AnyPropertyType, + &type, + &format, + &len, + &remaining, + &data); + + if (result == Success && data) { + long *state = (long *)data; + if (state[0] == WM_IconicState) { + XFree(data); + return WINDOW_MODE_MINIMIZED; + } + XFree(data); + } + } + + // All other discarded, return windowed. + + return WINDOW_MODE_WINDOWED; +} + +void DisplayServerX11::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + switch (p_flag) { + case WINDOW_FLAG_RESIZE_DISABLED: { + wd.resize_disabled = p_enabled; + + _update_size_hints(p_window); + + XFlush(x11_display); + } break; + case WINDOW_FLAG_BORDERLESS: { + Hints hints; + Atom property; + hints.flags = 2; + hints.decorations = p_enabled ? 0 : 1; + property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); + if (property != None) { + XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); + } + + // Preserve window size + window_set_size(window_get_size(p_window), p_window); + + wd.borderless = p_enabled; + } break; + case WINDOW_FLAG_ALWAYS_ON_TOP: { + ERR_FAIL_COND_MSG(wd.transient_parent != INVALID_WINDOW_ID, "Can't make a window transient if the 'on top' flag is active."); + if (p_enabled && wd.fullscreen) { + _set_wm_maximized(p_window, true); + } + + Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); + Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False); + + XClientMessageEvent xev; + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.window = wd.x11_window; + xev.message_type = wm_state; + xev.format = 32; + xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; + xev.data.l[1] = wm_above; + xev.data.l[3] = 1; + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev); + + if (!p_enabled && !wd.fullscreen) { + _set_wm_maximized(p_window, false); + } + wd.on_top = p_enabled; + + } break; + case WINDOW_FLAG_TRANSPARENT: { + //todo reimplement + } break; + default: { + } + } +} + +bool DisplayServerX11::window_get_flag(WindowFlags p_flag, WindowID p_window) const { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!windows.has(p_window), false); + const WindowData &wd = windows[p_window]; + + switch (p_flag) { + case WINDOW_FLAG_RESIZE_DISABLED: { + return wd.resize_disabled; + } break; + case WINDOW_FLAG_BORDERLESS: { + bool borderless = wd.borderless; + Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); + if (prop != None) { + Atom type; + int format; + unsigned long len; + unsigned long remaining; + unsigned char *data = nullptr; + if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { + if (data && (format == 32) && (len >= 5)) { + borderless = !((Hints *)data)->decorations; + } + if (data) { + XFree(data); + } + } + } + return borderless; + } break; + case WINDOW_FLAG_ALWAYS_ON_TOP: { + return wd.on_top; + } break; + case WINDOW_FLAG_TRANSPARENT: { + //todo reimplement + } break; + default: { + } + } + + return false; +} + +void DisplayServerX11::window_request_attention(WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + // Using EWMH -- Extended Window Manager Hints + // + // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE + // Will be unset by the window manager after user react on the request for attention + + XEvent xev; + Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); + Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False); + + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.xclient.window = wd.x11_window; + xev.xclient.message_type = wm_state; + xev.xclient.format = 32; + xev.xclient.data.l[0] = _NET_WM_STATE_ADD; + xev.xclient.data.l[1] = wm_attention; + + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + XFlush(x11_display); +} + +void DisplayServerX11::window_move_to_foreground(WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + XEvent xev; + Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False); + + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.xclient.window = wd.x11_window; + xev.xclient.message_type = net_active_window; + xev.xclient.format = 32; + xev.xclient.data.l[0] = 1; + xev.xclient.data.l[1] = CurrentTime; + + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + XFlush(x11_display); +} + +bool DisplayServerX11::window_can_draw(WindowID p_window) const { + //this seems to be all that is provided by X11 + return window_get_mode(p_window) != WINDOW_MODE_MINIMIZED; +} + +bool DisplayServerX11::can_any_window_draw() const { + _THREAD_SAFE_METHOD_ + + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + if (window_get_mode(E->key()) != WINDOW_MODE_MINIMIZED) { + return true; + } + } + + return false; +} + +void DisplayServerX11::window_set_ime_active(const bool p_active, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + wd.im_active = p_active; + + if (!wd.xic) { + return; + } + + // Block events polling while changing input focus + // because it triggers some event polling internally. + if (p_active) { + { + MutexLock mutex_lock(events_mutex); + XSetICFocus(wd.xic); + } + window_set_ime_position(wd.im_position, p_window); + } else { + MutexLock mutex_lock(events_mutex); + XUnsetICFocus(wd.xic); + } +} + +void DisplayServerX11::window_set_ime_position(const Point2i &p_pos, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + + wd.im_position = p_pos; + + if (!wd.xic) { + return; + } + + ::XPoint spot; + spot.x = short(p_pos.x); + spot.y = short(p_pos.y); + XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, nullptr); + + { + // Block events polling during this call + // because it triggers some event polling internally. + MutexLock mutex_lock(events_mutex); + XSetICValues(wd.xic, XNPreeditAttributes, preedit_attr, nullptr); + } + + XFree(preedit_attr); +} + +void DisplayServerX11::cursor_set_shape(CursorShape p_shape) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_INDEX(p_shape, CURSOR_MAX); + + if (p_shape == current_cursor) { + return; + } + + if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { + if (cursors[p_shape] != None) { + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + XDefineCursor(x11_display, E->get().x11_window, cursors[p_shape]); + } + } else if (cursors[CURSOR_ARROW] != None) { + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + XDefineCursor(x11_display, E->get().x11_window, cursors[CURSOR_ARROW]); + } + } + } + + current_cursor = p_shape; +} + +DisplayServerX11::CursorShape DisplayServerX11::cursor_get_shape() const { + return current_cursor; +} + +void DisplayServerX11::cursor_set_custom_image(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { + _THREAD_SAFE_METHOD_ + + if (p_cursor.is_valid()) { + Map<CursorShape, Vector<Variant>>::Element *cursor_c = cursors_cache.find(p_shape); + + if (cursor_c) { + if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) { + cursor_set_shape(p_shape); + return; + } + + cursors_cache.erase(p_shape); + } + + Ref<Texture2D> texture = p_cursor; + Ref<AtlasTexture> atlas_texture = p_cursor; + Ref<Image> image; + Size2i texture_size; + Rect2i atlas_rect; + + if (texture.is_valid()) { + image = texture->get_image(); + } + + if (!image.is_valid() && atlas_texture.is_valid()) { + texture = atlas_texture->get_atlas(); + + atlas_rect.size.width = texture->get_width(); + atlas_rect.size.height = texture->get_height(); + atlas_rect.position.x = atlas_texture->get_region().position.x; + atlas_rect.position.y = atlas_texture->get_region().position.y; + + texture_size.width = atlas_texture->get_region().size.x; + texture_size.height = atlas_texture->get_region().size.y; + } else if (image.is_valid()) { + texture_size.width = texture->get_width(); + texture_size.height = texture->get_height(); + } + + ERR_FAIL_COND(!texture.is_valid()); + ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0); + ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256); + ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height); + + image = texture->get_image(); + + ERR_FAIL_COND(!image.is_valid()); + + // Create the cursor structure + XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height); + XcursorUInt image_size = texture_size.width * texture_size.height; + XcursorDim size = sizeof(XcursorPixel) * image_size; + + cursor_image->version = 1; + cursor_image->size = size; + cursor_image->xhot = p_hotspot.x; + cursor_image->yhot = p_hotspot.y; + + // allocate memory to contain the whole file + cursor_image->pixels = (XcursorPixel *)memalloc(size); + + for (XcursorPixel index = 0; index < image_size; index++) { + int row_index = floor(index / texture_size.width) + atlas_rect.position.y; + int column_index = (index % int(texture_size.width)) + atlas_rect.position.x; + + if (atlas_texture.is_valid()) { + column_index = MIN(column_index, atlas_rect.size.width - 1); + row_index = MIN(row_index, atlas_rect.size.height - 1); + } + + *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32(); + } + + ERR_FAIL_COND(cursor_image->pixels == nullptr); + + // Save it for a further usage + cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image); + + Vector<Variant> params; + params.push_back(p_cursor); + params.push_back(p_hotspot); + cursors_cache.insert(p_shape, params); + + if (p_shape == current_cursor) { + if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + XDefineCursor(x11_display, E->get().x11_window, cursors[p_shape]); + } + } + } + + memfree(cursor_image->pixels); + XcursorImageDestroy(cursor_image); + } else { + // Reset to default system cursor + if (img[p_shape]) { + cursors[p_shape] = XcursorImageLoadCursor(x11_display, img[p_shape]); + } + + CursorShape c = current_cursor; + current_cursor = CURSOR_MAX; + cursor_set_shape(c); + + cursors_cache.erase(p_shape); + } +} + +int DisplayServerX11::keyboard_get_layout_count() const { + int _group_count = 0; + XkbDescRec *kbd = XkbAllocKeyboard(); + if (kbd) { + kbd->dpy = x11_display; + XkbGetControls(x11_display, XkbAllControlsMask, kbd); + XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); + + const Atom *groups = kbd->names->groups; + if (kbd->ctrls != nullptr) { + _group_count = kbd->ctrls->num_groups; + } else { + while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { + _group_count++; + } + } + XkbFreeKeyboard(kbd, 0, true); + } + return _group_count; +} + +int DisplayServerX11::keyboard_get_current_layout() const { + XkbStateRec state; + XkbGetState(x11_display, XkbUseCoreKbd, &state); + return state.group; +} + +void DisplayServerX11::keyboard_set_current_layout(int p_index) { + ERR_FAIL_INDEX(p_index, keyboard_get_layout_count()); + XkbLockGroup(x11_display, XkbUseCoreKbd, p_index); +} + +String DisplayServerX11::keyboard_get_layout_language(int p_index) const { + String ret; + XkbDescRec *kbd = XkbAllocKeyboard(); + if (kbd) { + kbd->dpy = x11_display; + XkbGetControls(x11_display, XkbAllControlsMask, kbd); + XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); + XkbGetNames(x11_display, XkbGroupNamesMask, kbd); + + int _group_count = 0; + const Atom *groups = kbd->names->groups; + if (kbd->ctrls != nullptr) { + _group_count = kbd->ctrls->num_groups; + } else { + while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { + _group_count++; + } + } + + Atom names = kbd->names->symbols; + if (names != None) { + char *name = XGetAtomName(x11_display, names); + Vector<String> info = String(name).split("+"); + if (p_index >= 0 && p_index < _group_count) { + if (p_index + 1 < info.size()) { + ret = info[p_index + 1]; // Skip "pc" at the start and "inet"/"group" at the end of symbols. + } else { + ret = "en"; // No symbol for layout fallback to "en". + } + } else { + ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); + } + XFree(name); + } + XkbFreeKeyboard(kbd, 0, true); + } + return ret.substr(0, 2); +} + +String DisplayServerX11::keyboard_get_layout_name(int p_index) const { + String ret; + XkbDescRec *kbd = XkbAllocKeyboard(); + if (kbd) { + kbd->dpy = x11_display; + XkbGetControls(x11_display, XkbAllControlsMask, kbd); + XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); + XkbGetNames(x11_display, XkbGroupNamesMask, kbd); + + int _group_count = 0; + const Atom *groups = kbd->names->groups; + if (kbd->ctrls != nullptr) { + _group_count = kbd->ctrls->num_groups; + } else { + while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { + _group_count++; + } + } + + if (p_index >= 0 && p_index < _group_count) { + char *full_name = XGetAtomName(x11_display, groups[p_index]); + ret.parse_utf8(full_name); + XFree(full_name); + } else { + ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); + } + XkbFreeKeyboard(kbd, 0, true); + } + return ret; +} + +DisplayServerX11::Property DisplayServerX11::_read_property(Display *p_display, Window p_window, Atom p_property) { + Atom actual_type = None; + int actual_format = 0; + unsigned long nitems = 0; + unsigned long bytes_after = 0; + unsigned char *ret = nullptr; + + int read_bytes = 1024; + + // Keep trying to read the property until there are no bytes unread. + if (p_property != None) { + do { + if (ret != nullptr) { + XFree(ret); + } + + XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType, + &actual_type, &actual_format, &nitems, &bytes_after, + &ret); + + read_bytes *= 2; + + } while (bytes_after != 0); + } + + Property p = { ret, actual_format, (int)nitems, actual_type }; + + return p; +} + +static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) { + static const char *target_type = "text/uri-list"; + + for (int i = 0; i < p_count; i++) { + Atom atom = p_list[i]; + + if (atom != None && String(XGetAtomName(p_display, atom)) == target_type) { + return atom; + } + } + return None; +} + +static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) { + static const char *target_type = "text/uri-list"; + if (p_t1 != None && String(XGetAtomName(p_disp, p_t1)) == target_type) { + return p_t1; + } + + if (p_t2 != None && String(XGetAtomName(p_disp, p_t2)) == target_type) { + return p_t2; + } + + if (p_t3 != None && String(XGetAtomName(p_disp, p_t3)) == target_type) { + return p_t3; + } + + return None; +} + +void DisplayServerX11::_get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) { + state->set_shift_pressed((p_x11_state & ShiftMask)); + state->set_ctrl_pressed((p_x11_state & ControlMask)); + state->set_alt_pressed((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt + state->set_meta_pressed((p_x11_state & Mod4Mask)); +} + +MouseButton DisplayServerX11::_get_mouse_button_state(MouseButton p_x11_button, int p_x11_type) { + MouseButton mask = MouseButton(1 << (p_x11_button - 1)); + + if (p_x11_type == ButtonPress) { + last_button_state |= mask; + } else { + last_button_state &= MouseButton(~mask); + } + + return last_button_state; +} + +void DisplayServerX11::_handle_key_event(WindowID p_window, XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) { + WindowData wd = windows[p_window]; + // X11 functions don't know what const is + XKeyEvent *xkeyevent = p_event; + + // This code was pretty difficult to write. + // The docs stink and every toolkit seems to + // do it in a different way. + + /* Phase 1, obtain a proper keysym */ + + // This was also very difficult to figure out. + // You'd expect you could just use Keysym provided by + // XKeycodeToKeysym to obtain internationalized + // input.. WRONG!! + // you must use XLookupString (???) which not only wastes + // cycles generating an unnecessary string, but also + // still works in half the cases. (won't handle deadkeys) + // For more complex input methods (deadkeys and more advanced) + // you have to use XmbLookupString (??). + // So.. then you have to chosse which of both results + // you want to keep. + // This is a real bizarreness and cpu waster. + + KeySym keysym_keycode = 0; // keysym used to find a keycode + KeySym keysym_unicode = 0; // keysym used to find unicode + + // XLookupString returns keysyms usable as nice keycodes. + char str[256 + 1]; + XKeyEvent xkeyevent_no_mod = *xkeyevent; + xkeyevent_no_mod.state &= ~ShiftMask; + xkeyevent_no_mod.state &= ~ControlMask; + XLookupString(xkeyevent, str, 256, &keysym_unicode, nullptr); + XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_keycode, nullptr); + + // Meanwhile, XLookupString returns keysyms useful for unicode. + + if (!xmbstring) { + // keep a temporary buffer for the string + xmbstring = (char *)memalloc(sizeof(char) * 8); + xmblen = 8; + } + + if (xkeyevent->type == KeyPress && wd.xic) { + Status status; +#ifdef X_HAVE_UTF8_STRING + int utf8len = 8; + char *utf8string = (char *)memalloc(sizeof(char) * utf8len); + int utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string, + utf8len - 1, &keysym_unicode, &status); + if (status == XBufferOverflow) { + utf8len = utf8bytes + 1; + utf8string = (char *)memrealloc(utf8string, utf8len); + utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string, + utf8len - 1, &keysym_unicode, &status); + } + utf8string[utf8bytes] = '\0'; + + if (status == XLookupChars) { + bool keypress = xkeyevent->type == KeyPress; + unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); + unsigned int physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode); + + if (keycode >= 'a' && keycode <= 'z') { + keycode -= 'a' - 'A'; + } + + String tmp; + tmp.parse_utf8(utf8string, utf8bytes); + for (int i = 0; i < tmp.length(); i++) { + Ref<InputEventKey> k; + k.instantiate(); + if (physical_keycode == 0 && keycode == 0 && tmp[i] == 0) { + continue; + } + + if (keycode == 0) { + keycode = physical_keycode; + } + + _get_key_modifier_state(xkeyevent->state, k); + + k->set_window_id(p_window); + k->set_unicode(tmp[i]); + + k->set_pressed(keypress); + + k->set_keycode(keycode); + + k->set_physical_keycode(physical_keycode); + + k->set_echo(false); + + if (k->get_keycode() == KEY_BACKTAB) { + //make it consistent across platforms. + k->set_keycode(KEY_TAB); + k->set_physical_keycode(KEY_TAB); + k->set_shift_pressed(true); + } + + Input::get_singleton()->accumulate_input_event(k); + } + memfree(utf8string); + return; + } + memfree(utf8string); +#else + do { + int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status); + xmbstring[mnbytes] = '\0'; + + if (status == XBufferOverflow) { + xmblen = mnbytes + 1; + xmbstring = (char *)memrealloc(xmbstring, xmblen); + } + } while (status == XBufferOverflow); +#endif + } + + /* Phase 2, obtain a Godot keycode from the keysym */ + + // KeyMappingX11 just translated the X11 keysym to a PIGUI + // keysym, so it works in all platforms the same. + + unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); + unsigned int physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode); + + /* Phase 3, obtain a unicode character from the keysym */ + + // KeyMappingX11 also translates keysym to unicode. + // It does a binary search on a table to translate + // most properly. + unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0; + + /* Phase 4, determine if event must be filtered */ + + // This seems to be a side-effect of using XIM. + // XFilterEvent looks like a core X11 function, + // but it's actually just used to see if we must + // ignore a deadkey, or events XIM determines + // must not reach the actual gui. + // Guess it was a design problem of the extension + + bool keypress = xkeyevent->type == KeyPress; + + if (physical_keycode == 0 && keycode == 0 && unicode == 0) { + return; + } + + if (keycode == 0) { + keycode = physical_keycode; + } + + /* Phase 5, determine modifier mask */ + + // No problems here, except I had no way to + // know Mod1 was ALT and Mod4 was META (applekey/winkey) + // just tried Mods until i found them. + + //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask)); + + Ref<InputEventKey> k; + k.instantiate(); + k->set_window_id(p_window); + + _get_key_modifier_state(xkeyevent->state, k); + + /* Phase 6, determine echo character */ + + // Echo characters in X11 are a keyrelease and a keypress + // one after the other with the (almot) same timestamp. + // To detect them, i compare to the next event in list and + // check that their difference in time is below a threshold. + + if (xkeyevent->type != KeyPress) { + p_echo = false; + + // make sure there are events pending, + // so this call won't block. + if (p_event_index + 1 < p_events.size()) { + XEvent &peek_event = p_events[p_event_index + 1]; + + // I'm using a threshold of 5 msecs, + // since sometimes there seems to be a little + // jitter. I'm still not convinced that all this approach + // is correct, but the xorg developers are + // not very helpful today. + +#define ABSDIFF(x, y) (((x) < (y)) ? ((y) - (x)) : ((x) - (y))) + ::Time threshold = ABSDIFF(peek_event.xkey.time, xkeyevent->time); +#undef ABSDIFF + if (peek_event.type == KeyPress && threshold < 5) { + KeySym rk; + XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, nullptr); + if (rk == keysym_keycode) { + // Consume to next event. + ++p_event_index; + _handle_key_event(p_window, (XKeyEvent *)&peek_event, p_events, p_event_index, true); + return; //ignore current, echo next + } + } + + // use the time from peek_event so it always works + } + + // save the time to check for echo when keypress happens + } + + /* Phase 7, send event to Window */ + + k->set_pressed(keypress); + + if (keycode >= 'a' && keycode <= 'z') { + keycode -= 'a' - 'A'; + } + + k->set_keycode(keycode); + k->set_physical_keycode(physical_keycode); + k->set_unicode(unicode); + k->set_echo(p_echo); + + if (k->get_keycode() == KEY_BACKTAB) { + //make it consistent across platforms. + k->set_keycode(KEY_TAB); + k->set_physical_keycode(KEY_TAB); + k->set_shift_pressed(true); + } + + //don't set mod state if modifier keys are released by themselves + //else event.is_action() will not work correctly here + if (!k->is_pressed()) { + if (k->get_keycode() == KEY_SHIFT) { + k->set_shift_pressed(false); + } else if (k->get_keycode() == KEY_CTRL) { + k->set_ctrl_pressed(false); + } else if (k->get_keycode() == KEY_ALT) { + k->set_alt_pressed(false); + } else if (k->get_keycode() == KEY_META) { + k->set_meta_pressed(false); + } + } + + bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_keycode()); + if (k->is_pressed()) { + if (last_is_pressed) { + k->set_echo(true); + } + } + + Input::get_singleton()->accumulate_input_event(k); +} + +Atom DisplayServerX11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property) const { + if (p_target == XInternAtom(x11_display, "TARGETS", 0)) { + // Request to list all supported targets. + Atom data[9]; + data[0] = XInternAtom(x11_display, "TARGETS", 0); + data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0); + data[2] = XInternAtom(x11_display, "MULTIPLE", 0); + data[3] = XInternAtom(x11_display, "UTF8_STRING", 0); + data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0); + data[5] = XInternAtom(x11_display, "TEXT", 0); + data[6] = XA_STRING; + data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0); + data[8] = XInternAtom(x11_display, "text/plain", 0); + + XChangeProperty(x11_display, + p_requestor, + p_property, + XA_ATOM, + 32, + PropModeReplace, + (unsigned char *)&data, + sizeof(data) / sizeof(data[0])); + return p_property; + } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) { + // Request to check if SAVE_TARGETS is supported, nothing special to do. + XChangeProperty(x11_display, + p_requestor, + p_property, + XInternAtom(x11_display, "NULL", False), + 32, + PropModeReplace, + nullptr, + 0); + return p_property; + } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) || + p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) || + p_target == XInternAtom(x11_display, "TEXT", 0) || + p_target == XA_STRING || + p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) || + p_target == XInternAtom(x11_display, "text/plain", 0)) { + // Directly using internal clipboard because we know our window + // is the owner during a selection request. + CharString clip = internal_clipboard.utf8(); + XChangeProperty(x11_display, + p_requestor, + p_property, + p_target, + 8, + PropModeReplace, + (unsigned char *)clip.get_data(), + clip.length()); + return p_property; + } else { + char *target_name = XGetAtomName(x11_display, p_target); + printf("Target '%s' not supported.\n", target_name); + if (target_name) { + XFree(target_name); + } + return None; + } +} + +void DisplayServerX11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const { + XEvent respond; + if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) { + // Request for multiple target conversions at once. + Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False); + respond.xselection.property = None; + + Atom type; + int format; + unsigned long len; + unsigned long remaining; + unsigned char *data = nullptr; + if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) { + if ((len >= 2) && data) { + Atom *targets = (Atom *)data; + for (uint64_t i = 0; i < len; i += 2) { + Atom target = targets[i]; + Atom &property = targets[i + 1]; + property = _process_selection_request_target(target, p_event->requestor, property); + } + + XChangeProperty(x11_display, + p_event->requestor, + p_event->property, + atom_pair, + 32, + PropModeReplace, + (unsigned char *)targets, + len); + + respond.xselection.property = p_event->property; + } + XFree(data); + } + } else { + // Request for target conversion. + respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property); + } + + respond.xselection.type = SelectionNotify; + respond.xselection.display = p_event->display; + respond.xselection.requestor = p_event->requestor; + respond.xselection.selection = p_event->selection; + respond.xselection.target = p_event->target; + respond.xselection.time = p_event->time; + + XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond); + XFlush(x11_display); +} + +void DisplayServerX11::_xim_destroy_callback(::XIM im, ::XPointer client_data, + ::XPointer call_data) { + WARN_PRINT("Input method stopped"); + DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data); + ds->xim = nullptr; + + for (Map<WindowID, WindowData>::Element *E = ds->windows.front(); E; E = E->next()) { + E->get().xic = nullptr; + } +} + +void DisplayServerX11::_window_changed(XEvent *event) { + WindowID window_id = MAIN_WINDOW_ID; + + // Assign the event to the relevant window + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + if (event->xany.window == E->get().x11_window) { + window_id = E->key(); + break; + } + } + + Rect2i new_rect; + + WindowData &wd = windows[window_id]; + if (wd.x11_window != event->xany.window) { // Check if the correct window, in case it was not main window or anything else + return; + } + + { + //the position in xconfigure is not useful here, obtain it manually + int x, y; + Window child; + XTranslateCoordinates(x11_display, wd.x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); + new_rect.position.x = x; + new_rect.position.y = y; + + new_rect.size.width = event->xconfigure.width; + new_rect.size.height = event->xconfigure.height; + } + + if (new_rect == Rect2i(wd.position, wd.size)) { + return; + } + if (wd.xic) { + // Not portable. + window_set_ime_position(Point2(0, 1)); + } + + wd.position = new_rect.position; + wd.size = new_rect.size; + +#if defined(VULKAN_ENABLED) + if (rendering_driver == "vulkan") { + context_vulkan->window_resize(window_id, wd.size.width, wd.size.height); + } +#endif + + if (!wd.rect_changed_callback.is_null()) { + Rect2i r = new_rect; + + Variant rect = r; + + Variant *rectp = ▭ + Variant ret; + Callable::CallError ce; + wd.rect_changed_callback.call((const Variant **)&rectp, 1, ret, ce); + } +} + +void DisplayServerX11::_dispatch_input_events(const Ref<InputEvent> &p_event) { + ((DisplayServerX11 *)(get_singleton()))->_dispatch_input_event(p_event); +} + +void DisplayServerX11::_dispatch_input_event(const Ref<InputEvent> &p_event) { + Variant ev = p_event; + Variant *evp = &ev; + Variant ret; + Callable::CallError ce; + + Ref<InputEventFromWindow> event_from_window = p_event; + if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) { + //send to a window + ERR_FAIL_COND(!windows.has(event_from_window->get_window_id())); + Callable callable = windows[event_from_window->get_window_id()].input_event_callback; + if (callable.is_null()) { + return; + } + callable.call((const Variant **)&evp, 1, ret, ce); + } else { + //send to all windows + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + Callable callable = E->get().input_event_callback; + if (callable.is_null()) { + continue; + } + callable.call((const Variant **)&evp, 1, ret, ce); + } + } +} + +void DisplayServerX11::_send_window_event(const WindowData &wd, WindowEvent p_event) { + if (!wd.event_callback.is_null()) { + Variant event = int(p_event); + Variant *eventp = &event; + Variant ret; + Callable::CallError ce; + wd.event_callback.call((const Variant **)&eventp, 1, ret, ce); + } +} + +void DisplayServerX11::_poll_events_thread(void *ud) { + DisplayServerX11 *display_server = (DisplayServerX11 *)ud; + display_server->_poll_events(); +} + +Bool DisplayServerX11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) { + // Just accept all events. + return True; +} + +bool DisplayServerX11::_wait_for_events() const { + int x11_fd = ConnectionNumber(x11_display); + fd_set in_fds; + + XFlush(x11_display); + + FD_ZERO(&in_fds); + FD_SET(x11_fd, &in_fds); + + struct timeval tv; + tv.tv_usec = 0; + tv.tv_sec = 1; + + // Wait for next event or timeout. + int num_ready_fds = select(x11_fd + 1, &in_fds, nullptr, nullptr, &tv); + + if (num_ready_fds > 0) { + // Event received. + return true; + } else { + // Error or timeout. + if (num_ready_fds < 0) { + ERR_PRINT("_wait_for_events: select error: " + itos(errno)); + } + return false; + } +} + +void DisplayServerX11::_poll_events() { + while (!events_thread_done.is_set()) { + _wait_for_events(); + + // Process events from the queue. + { + MutexLock mutex_lock(events_mutex); + + // Non-blocking wait for next event and remove it from the queue. + XEvent ev; + while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, nullptr)) { + // Check if the input manager wants to process the event. + if (XFilterEvent(&ev, None)) { + // Event has been filtered by the Input Manager, + // it has to be ignored and a new one will be received. + continue; + } + + // Handle selection request events directly in the event thread, because + // communication through the x server takes several events sent back and forth + // and we don't want to block other programs while processing only one each frame. + if (ev.type == SelectionRequest) { + _handle_selection_request_event(&(ev.xselectionrequest)); + continue; + } + + polled_events.push_back(ev); + } + } + } +} + +void DisplayServerX11::process_events() { + _THREAD_SAFE_METHOD_ + +#ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED + static int frame = 0; + ++frame; +#endif + + if (app_focused) { + //verify that one of the windows has focus, else send focus out notification + bool focus_found = false; + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + if (E->get().focused) { + focus_found = true; + break; + } + } + + if (!focus_found) { + uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_no_focus; + + if (delta > 250) { + //X11 can go between windows and have no focus for a while, when creating them or something else. Use this as safety to avoid unnecessary focus in/outs. + if (OS::get_singleton()->get_main_loop()) { + DEBUG_LOG_X11("All focus lost, triggering NOTIFICATION_APPLICATION_FOCUS_OUT\n"); + OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT); + } + app_focused = false; + } + } else { + time_since_no_focus = OS::get_singleton()->get_ticks_msec(); + } + } + + do_mouse_warp = false; + + // Is the current mouse mode one where it needs to be grabbed. + bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN; + + xi.pressure = 0; + xi.tilt = Vector2(); + xi.pressure_supported = false; + + LocalVector<XEvent> events; + { + // Block events polling while flushing events. + MutexLock mutex_lock(events_mutex); + events = polled_events; + polled_events.clear(); + } + + for (uint32_t event_index = 0; event_index < events.size(); ++event_index) { + XEvent &event = events[event_index]; + + WindowID window_id = MAIN_WINDOW_ID; + + // Assign the event to the relevant window + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + if (event.xany.window == E->get().x11_window) { + window_id = E->key(); + break; + } + } + + if (XGetEventData(x11_display, &event.xcookie)) { + if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { + XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; + int index = event_data->detail; + Vector2 pos = Vector2(event_data->event_x, event_data->event_y); + + switch (event_data->evtype) { + case XI_HierarchyChanged: + case XI_DeviceChanged: { + _refresh_device_info(); + } break; + case XI_RawMotion: { + XIRawEvent *raw_event = (XIRawEvent *)event_data; + int device_id = raw_event->deviceid; + + // Determine the axis used (called valuators in XInput for some forsaken reason) + // Mask is a bitmask indicating which axes are involved. + // We are interested in the values of axes 0 and 1. + if (raw_event->valuators.mask_len <= 0) { + break; + } + + const double *values = raw_event->raw_values; + + double rel_x = 0.0; + double rel_y = 0.0; + + if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) { + rel_x = *values; + values++; + } + + if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) { + rel_y = *values; + values++; + } + + if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) { + Map<int, Vector2>::Element *pen_pressure = xi.pen_pressure_range.find(device_id); + if (pen_pressure) { + Vector2 pen_pressure_range = pen_pressure->value(); + if (pen_pressure_range != Vector2()) { + xi.pressure_supported = true; + xi.pressure = (*values - pen_pressure_range[0]) / + (pen_pressure_range[1] - pen_pressure_range[0]); + } + } + + values++; + } + + if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) { + Map<int, Vector2>::Element *pen_tilt_x = xi.pen_tilt_x_range.find(device_id); + if (pen_tilt_x) { + Vector2 pen_tilt_x_range = pen_tilt_x->value(); + if (pen_tilt_x_range != Vector2()) { + xi.tilt.x = ((*values - pen_tilt_x_range[0]) / (pen_tilt_x_range[1] - pen_tilt_x_range[0])) * 2 - 1; + } + } + + values++; + } + + if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) { + Map<int, Vector2>::Element *pen_tilt_y = xi.pen_tilt_y_range.find(device_id); + if (pen_tilt_y) { + Vector2 pen_tilt_y_range = pen_tilt_y->value(); + if (pen_tilt_y_range != Vector2()) { + xi.tilt.y = ((*values - pen_tilt_y_range[0]) / (pen_tilt_y_range[1] - pen_tilt_y_range[0])) * 2 - 1; + } + } + + values++; + } + + // https://bugs.freedesktop.org/show_bug.cgi?id=71609 + // http://lists.libsdl.org/pipermail/commits-libsdl.org/2015-June/000282.html + if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) { + break; // Flush duplicate to avoid overly fast motion + } + + xi.old_raw_pos.x = xi.raw_pos.x; + xi.old_raw_pos.y = xi.raw_pos.y; + xi.raw_pos.x = rel_x; + xi.raw_pos.y = rel_y; + + Map<int, Vector2>::Element *abs_info = xi.absolute_devices.find(device_id); + + if (abs_info) { + // Absolute mode device + Vector2 mult = abs_info->value(); + + xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x; + xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y; + } else { + // Relative mode device + xi.relative_motion.x = xi.raw_pos.x; + xi.relative_motion.y = xi.raw_pos.y; + } + + xi.last_relative_time = raw_event->time; + } break; +#ifdef TOUCH_ENABLED + case XI_TouchBegin: // Fall-through + // Disabled hand-in-hand with the grabbing + //XIAllowTouchEvents(x11_display, event_data->deviceid, event_data->detail, x11_window, XIAcceptTouch); + + case XI_TouchEnd: { + bool is_begin = event_data->evtype == XI_TouchBegin; + + Ref<InputEventScreenTouch> st; + st.instantiate(); + st->set_window_id(window_id); + st->set_index(index); + st->set_position(pos); + st->set_pressed(is_begin); + + if (is_begin) { + if (xi.state.has(index)) { // Defensive + break; + } + xi.state[index] = pos; + if (xi.state.size() == 1) { + // X11 may send a motion event when a touch gesture begins, that would result + // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out + xi.mouse_pos_to_filter = pos; + } + Input::get_singleton()->accumulate_input_event(st); + } else { + if (!xi.state.has(index)) { // Defensive + break; + } + xi.state.erase(index); + Input::get_singleton()->accumulate_input_event(st); + } + } break; + + case XI_TouchUpdate: { + Map<int, Vector2>::Element *curr_pos_elem = xi.state.find(index); + if (!curr_pos_elem) { // Defensive + break; + } + + if (curr_pos_elem->value() != pos) { + Ref<InputEventScreenDrag> sd; + sd.instantiate(); + sd->set_window_id(window_id); + sd->set_index(index); + sd->set_position(pos); + sd->set_relative(pos - curr_pos_elem->value()); + Input::get_singleton()->accumulate_input_event(sd); + + curr_pos_elem->value() = pos; + } + } break; +#endif + } + } + } + XFreeEventData(x11_display, &event.xcookie); + + switch (event.type) { + case MapNotify: { + DEBUG_LOG_X11("[%u] MapNotify window=%lu (%u) \n", frame, event.xmap.window, window_id); + + const WindowData &wd = windows[window_id]; + + // Set focus when menu window is started. + // RevertToPointerRoot is used to make sure we don't lose all focus in case + // a subwindow and its parent are both destroyed. + if (wd.menu_type && !wd.no_focus) { + XSetInputFocus(x11_display, wd.x11_window, RevertToPointerRoot, CurrentTime); + } + } break; + + case Expose: { + DEBUG_LOG_X11("[%u] Expose window=%lu (%u), count='%u' \n", frame, event.xexpose.window, window_id, event.xexpose.count); + + Main::force_redraw(); + } break; + + case NoExpose: { + DEBUG_LOG_X11("[%u] NoExpose drawable=%lu (%u) \n", frame, event.xnoexpose.drawable, window_id); + + windows[window_id].minimized = true; + } break; + + case VisibilityNotify: { + DEBUG_LOG_X11("[%u] VisibilityNotify window=%lu (%u), state=%u \n", frame, event.xvisibility.window, window_id, event.xvisibility.state); + + XVisibilityEvent *visibility = (XVisibilityEvent *)&event; + windows[window_id].minimized = (visibility->state == VisibilityFullyObscured); + } break; + + case LeaveNotify: { + DEBUG_LOG_X11("[%u] LeaveNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode); + + if (!mouse_mode_grab) { + _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT); + } + + } break; + + case EnterNotify: { + DEBUG_LOG_X11("[%u] EnterNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode); + + if (!mouse_mode_grab) { + _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER); + } + } break; + + case FocusIn: { + DEBUG_LOG_X11("[%u] FocusIn window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode); + + WindowData &wd = windows[window_id]; + + wd.focused = true; + + if (wd.xic) { + // Block events polling while changing input focus + // because it triggers some event polling internally. + MutexLock mutex_lock(events_mutex); + XSetICFocus(wd.xic); + } + + // Keep track of focus order for overlapping windows. + static unsigned int focus_order = 0; + wd.focus_order = ++focus_order; + + _send_window_event(wd, WINDOW_EVENT_FOCUS_IN); + + if (mouse_mode_grab) { + // Show and update the cursor if confined and the window regained focus. + + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + if (mouse_mode == MOUSE_MODE_CONFINED) { + XUndefineCursor(x11_display, E->get().x11_window); + } else if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) { // Or re-hide it. + XDefineCursor(x11_display, E->get().x11_window, null_cursor); + } + + XGrabPointer( + x11_display, E->get().x11_window, True, + ButtonPressMask | ButtonReleaseMask | PointerMotionMask, + GrabModeAsync, GrabModeAsync, E->get().x11_window, None, CurrentTime); + } + } +#ifdef TOUCH_ENABLED + // Grab touch devices to avoid OS gesture interference + /*for (int i = 0; i < xi.touch_devices.size(); ++i) { + XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); + }*/ +#endif + + if (!app_focused) { + if (OS::get_singleton()->get_main_loop()) { + OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN); + } + app_focused = true; + } + } break; + + case FocusOut: { + DEBUG_LOG_X11("[%u] FocusOut window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode); + + WindowData &wd = windows[window_id]; + + wd.focused = false; + + if (wd.xic) { + // Block events polling while changing input focus + // because it triggers some event polling internally. + MutexLock mutex_lock(events_mutex); + XUnsetICFocus(wd.xic); + } + + Input::get_singleton()->release_pressed_events(); + _send_window_event(wd, WINDOW_EVENT_FOCUS_OUT); + + if (mouse_mode_grab) { + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + //dear X11, I try, I really try, but you never work, you do whathever you want. + if (mouse_mode == MOUSE_MODE_CAPTURED) { + // Show the cursor if we're in captured mode so it doesn't look weird. + XUndefineCursor(x11_display, E->get().x11_window); + } + } + XUngrabPointer(x11_display, CurrentTime); + } +#ifdef TOUCH_ENABLED + // Ungrab touch devices so input works as usual while we are unfocused + /*for (int i = 0; i < xi.touch_devices.size(); ++i) { + XIUngrabDevice(x11_display, xi.touch_devices[i], CurrentTime); + }*/ + + // Release every pointer to avoid sticky points + for (Map<int, Vector2>::Element *E = xi.state.front(); E; E = E->next()) { + Ref<InputEventScreenTouch> st; + st.instantiate(); + st->set_index(E->key()); + st->set_window_id(window_id); + st->set_position(E->get()); + Input::get_singleton()->accumulate_input_event(st); + } + xi.state.clear(); +#endif + } break; + + case ConfigureNotify: { + DEBUG_LOG_X11("[%u] ConfigureNotify window=%lu (%u), event=%lu, above=%lu, override_redirect=%u \n", frame, event.xconfigure.window, window_id, event.xconfigure.event, event.xconfigure.above, event.xconfigure.override_redirect); + + const WindowData &wd = windows[window_id]; + + // Set focus when menu window is re-used. + // RevertToPointerRoot is used to make sure we don't lose all focus in case + // a subwindow and its parent are both destroyed. + if (wd.menu_type && !wd.no_focus) { + XSetInputFocus(x11_display, wd.x11_window, RevertToPointerRoot, CurrentTime); + } + + _window_changed(&event); + } break; + + case ButtonPress: + case ButtonRelease: { + /* exit in case of a mouse button press */ + last_timestamp = event.xbutton.time; + if (mouse_mode == MOUSE_MODE_CAPTURED) { + event.xbutton.x = last_mouse_pos.x; + event.xbutton.y = last_mouse_pos.y; + } + + Ref<InputEventMouseButton> mb; + mb.instantiate(); + + mb->set_window_id(window_id); + _get_key_modifier_state(event.xbutton.state, mb); + mb->set_button_index((MouseButton)event.xbutton.button); + if (mb->get_button_index() == MOUSE_BUTTON_RIGHT) { + mb->set_button_index(MOUSE_BUTTON_MIDDLE); + } else if (mb->get_button_index() == MOUSE_BUTTON_MIDDLE) { + mb->set_button_index(MOUSE_BUTTON_RIGHT); + } + mb->set_button_mask(_get_mouse_button_state(mb->get_button_index(), event.xbutton.type)); + mb->set_position(Vector2(event.xbutton.x, event.xbutton.y)); + mb->set_global_position(mb->get_position()); + + mb->set_pressed((event.type == ButtonPress)); + + const WindowData &wd = windows[window_id]; + + if (event.type == ButtonPress) { + DEBUG_LOG_X11("[%u] ButtonPress window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index()); + + // Ensure window focus on click. + // RevertToPointerRoot is used to make sure we don't lose all focus in case + // a subwindow and its parent are both destroyed. + if (!wd.no_focus) { + XSetInputFocus(x11_display, wd.x11_window, RevertToPointerRoot, CurrentTime); + } + + uint64_t diff = OS::get_singleton()->get_ticks_usec() / 1000 - last_click_ms; + + if (mb->get_button_index() == last_click_button_index) { + if (diff < 400 && Vector2(last_click_pos).distance_to(Vector2(event.xbutton.x, event.xbutton.y)) < 5) { + last_click_ms = 0; + last_click_pos = Point2i(-100, -100); + last_click_button_index = -1; + mb->set_double_click(true); + } + + } else if (mb->get_button_index() < 4 || mb->get_button_index() > 7) { + last_click_button_index = mb->get_button_index(); + } + + if (!mb->is_double_click()) { + last_click_ms += diff; + last_click_pos = Point2i(event.xbutton.x, event.xbutton.y); + } + } else { + DEBUG_LOG_X11("[%u] ButtonRelease window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index()); + + if (!wd.focused) { + // Propagate the event to the focused window, + // because it's received only on the topmost window. + // Note: This is needed for drag & drop to work between windows, + // because the engine expects events to keep being processed + // on the same window dragging started. + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + const WindowData &wd_other = E->get(); + WindowID window_id_other = E->key(); + if (wd_other.focused) { + if (window_id_other != window_id) { + int x, y; + Window child; + XTranslateCoordinates(x11_display, wd.x11_window, wd_other.x11_window, event.xbutton.x, event.xbutton.y, &x, &y, &child); + + mb->set_window_id(window_id_other); + mb->set_position(Vector2(x, y)); + mb->set_global_position(mb->get_position()); + Input::get_singleton()->accumulate_input_event(mb); + } + break; + } + } + } + } + + Input::get_singleton()->accumulate_input_event(mb); + + } break; + case MotionNotify: { + // The X11 API requires filtering one-by-one through the motion + // notify events, in order to figure out which event is the one + // generated by warping the mouse pointer. + + while (true) { + if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == windows[MAIN_WINDOW_ID].size.width / 2 && event.xmotion.y == windows[MAIN_WINDOW_ID].size.height / 2) { + //this is likely the warp event since it was warped here + center = Vector2(event.xmotion.x, event.xmotion.y); + break; + } + + if (event_index + 1 < events.size()) { + const XEvent &next_event = events[event_index + 1]; + if (next_event.type == MotionNotify) { + ++event_index; + event = next_event; + } else { + break; + } + } else { + break; + } + } + + last_timestamp = event.xmotion.time; + + // Motion is also simple. + // A little hack is in order + // to be able to send relative motion events. + Point2i pos(event.xmotion.x, event.xmotion.y); + + // Avoidance of spurious mouse motion (see handling of touch) + bool filter = false; + // Adding some tolerance to match better Point2i to Vector2 + if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) { + filter = true; + } + // Invalidate to avoid filtering a possible legitimate similar event coming later + xi.mouse_pos_to_filter = Vector2(1e10, 1e10); + if (filter) { + break; + } + + const WindowData &wd = windows[window_id]; + bool focused = wd.focused; + + if (mouse_mode == MOUSE_MODE_CAPTURED) { + if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) { + break; + } + + Point2i new_center = pos; + pos = last_mouse_pos + xi.relative_motion; + center = new_center; + do_mouse_warp = focused; // warp the cursor if we're focused in + } + + if (!last_mouse_pos_valid) { + last_mouse_pos = pos; + last_mouse_pos_valid = true; + } + + // Hackish but relative mouse motion is already handled in the RawMotion event. + // RawMotion does not provide the absolute mouse position (whereas MotionNotify does). + // Therefore, RawMotion cannot be the authority on absolute mouse position. + // RawMotion provides more precision than MotionNotify, which doesn't sense subpixel motion. + // Therefore, MotionNotify cannot be the authority on relative mouse motion. + // This means we need to take a combined approach... + Point2i rel; + + // Only use raw input if in capture mode. Otherwise use the classic behavior. + if (mouse_mode == MOUSE_MODE_CAPTURED) { + rel = xi.relative_motion; + } else { + rel = pos - last_mouse_pos; + } + + // Reset to prevent lingering motion + xi.relative_motion.x = 0; + xi.relative_motion.y = 0; + + if (mouse_mode == MOUSE_MODE_CAPTURED) { + pos = Point2i(windows[MAIN_WINDOW_ID].size.width / 2, windows[MAIN_WINDOW_ID].size.height / 2); + } + + Ref<InputEventMouseMotion> mm; + mm.instantiate(); + + mm->set_window_id(window_id); + if (xi.pressure_supported) { + mm->set_pressure(xi.pressure); + } else { + mm->set_pressure((mouse_get_button_state() & MOUSE_BUTTON_MASK_LEFT) ? 1.0f : 0.0f); + } + mm->set_tilt(xi.tilt); + + _get_key_modifier_state(event.xmotion.state, mm); + mm->set_button_mask(mouse_get_button_state()); + mm->set_position(pos); + mm->set_global_position(pos); + Input::get_singleton()->set_mouse_position(pos); + mm->set_speed(Input::get_singleton()->get_last_mouse_speed()); + + mm->set_relative(rel); + + last_mouse_pos = pos; + + // printf("rel: %d,%d\n", rel.x, rel.y ); + // Don't propagate the motion event unless we have focus + // this is so that the relative motion doesn't get messed up + // after we regain focus. + if (focused) { + Input::get_singleton()->accumulate_input_event(mm); + } else { + // Propagate the event to the focused window, + // because it's received only on the topmost window. + // Note: This is needed for drag & drop to work between windows, + // because the engine expects events to keep being processed + // on the same window dragging started. + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + const WindowData &wd_other = E->get(); + if (wd_other.focused) { + int x, y; + Window child; + XTranslateCoordinates(x11_display, wd.x11_window, wd_other.x11_window, event.xmotion.x, event.xmotion.y, &x, &y, &child); + + Point2i pos_focused(x, y); + + mm->set_window_id(E->key()); + mm->set_position(pos_focused); + mm->set_global_position(pos_focused); + mm->set_speed(Input::get_singleton()->get_last_mouse_speed()); + Input::get_singleton()->accumulate_input_event(mm); + + break; + } + } + } + + } break; + case KeyPress: + case KeyRelease: { + last_timestamp = event.xkey.time; + + // key event is a little complex, so + // it will be handled in its own function. + _handle_key_event(window_id, (XKeyEvent *)&event, events, event_index); + } break; + + case SelectionNotify: + + if (event.xselection.target == requested) { + Property p = _read_property(x11_display, windows[window_id].x11_window, XInternAtom(x11_display, "PRIMARY", 0)); + + Vector<String> files = String((char *)p.data).split("\n", false); + for (int i = 0; i < files.size(); i++) { + files.write[i] = files[i].replace("file://", "").uri_decode().strip_edges(); + } + + if (!windows[window_id].drop_files_callback.is_null()) { + Variant v = files; + Variant *vp = &v; + Variant ret; + Callable::CallError ce; + windows[window_id].drop_files_callback.call((const Variant **)&vp, 1, ret, ce); + } + + //Reply that all is well. + XClientMessageEvent m; + memset(&m, 0, sizeof(m)); + m.type = ClientMessage; + m.display = x11_display; + m.window = xdnd_source_window; + m.message_type = xdnd_finished; + m.format = 32; + m.data.l[0] = windows[window_id].x11_window; + m.data.l[1] = 1; + m.data.l[2] = xdnd_action_copy; //We only ever copy. + + XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m); + } + break; + + case ClientMessage: + + if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete) { + _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST); + } + + else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) { + //File(s) have been dragged over the window, check for supported target (text/uri-list) + xdnd_version = (event.xclient.data.l[1] >> 24); + Window source = event.xclient.data.l[0]; + bool more_than_3 = event.xclient.data.l[1] & 1; + if (more_than_3) { + Property p = _read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False)); + requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems); + } else { + requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]); + } + } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) { + //xdnd position event, reply with an XDND status message + //just depending on type of data for now + XClientMessageEvent m; + memset(&m, 0, sizeof(m)); + m.type = ClientMessage; + m.display = event.xclient.display; + m.window = event.xclient.data.l[0]; + m.message_type = xdnd_status; + m.format = 32; + m.data.l[0] = windows[window_id].x11_window; + m.data.l[1] = (requested != None); + m.data.l[2] = 0; //empty rectangle + m.data.l[3] = 0; + m.data.l[4] = xdnd_action_copy; + + XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); + XFlush(x11_display); + } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) { + if (requested != None) { + xdnd_source_window = event.xclient.data.l[0]; + if (xdnd_version >= 1) { + XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, event.xclient.data.l[2]); + } else { + XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, CurrentTime); + } + } else { + //Reply that we're not interested. + XClientMessageEvent m; + memset(&m, 0, sizeof(m)); + m.type = ClientMessage; + m.display = event.xclient.display; + m.window = event.xclient.data.l[0]; + m.message_type = xdnd_finished; + m.format = 32; + m.data.l[0] = windows[window_id].x11_window; + m.data.l[1] = 0; + m.data.l[2] = None; //Failed. + XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); + } + } + break; + default: + break; + } + } + + XFlush(x11_display); + + if (do_mouse_warp) { + XWarpPointer(x11_display, None, windows[MAIN_WINDOW_ID].x11_window, + 0, 0, 0, 0, (int)windows[MAIN_WINDOW_ID].size.width / 2, (int)windows[MAIN_WINDOW_ID].size.height / 2); + + /* + Window root, child; + int root_x, root_y; + int win_x, win_y; + unsigned int mask; + XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask ); + + printf("Root: %d,%d\n", root_x, root_y); + printf("Win: %d,%d\n", win_x, win_y); + */ + } + + Input::get_singleton()->flush_accumulated_events(); +} + +void DisplayServerX11::release_rendering_thread() { +} + +void DisplayServerX11::make_rendering_thread() { +} + +void DisplayServerX11::swap_buffers() { +} + +void DisplayServerX11::_update_context(WindowData &wd) { + XClassHint *classHint = XAllocClassHint(); + + if (classHint) { + CharString name_str; + switch (context) { + case CONTEXT_EDITOR: + name_str = "Godot_Editor"; + break; + case CONTEXT_PROJECTMAN: + name_str = "Godot_ProjectList"; + break; + case CONTEXT_ENGINE: + name_str = "Godot_Engine"; + break; + } + + CharString class_str; + if (context == CONTEXT_ENGINE) { + String config_name = GLOBAL_GET("application/config/name"); + if (config_name.length() == 0) { + class_str = "Godot_Engine"; + } else { + class_str = config_name.utf8(); + } + } else { + class_str = "Godot"; + } + + classHint->res_class = class_str.ptrw(); + classHint->res_name = name_str.ptrw(); + + XSetClassHint(x11_display, wd.x11_window, classHint); + XFree(classHint); + } +} + +void DisplayServerX11::set_context(Context p_context) { + _THREAD_SAFE_METHOD_ + + context = p_context; + + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + _update_context(E->get()); + } +} + +void DisplayServerX11::set_native_icon(const String &p_filename) { + WARN_PRINT("Native icon not supported by this display server."); +} + +bool g_set_icon_error = false; +int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) { + g_set_icon_error = true; + return 0; +} + +void DisplayServerX11::set_icon(const Ref<Image> &p_icon) { + _THREAD_SAFE_METHOD_ + + WindowData &wd = windows[MAIN_WINDOW_ID]; + + int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler); + + Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False); + + if (p_icon.is_valid()) { + Ref<Image> img = p_icon->duplicate(); + img->convert(Image::FORMAT_RGBA8); + + while (true) { + int w = img->get_width(); + int h = img->get_height(); + + if (g_set_icon_error) { + g_set_icon_error = false; + + WARN_PRINT("Icon too large, attempting to resize icon."); + + int new_width, new_height; + if (w > h) { + new_width = w / 2; + new_height = h * new_width / w; + } else { + new_height = h / 2; + new_width = w * new_height / h; + } + + w = new_width; + h = new_height; + + if (!w || !h) { + WARN_PRINT("Unable to set icon."); + break; + } + + img->resize(w, h, Image::INTERPOLATE_CUBIC); + } + + // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits + Vector<long> pd; + + pd.resize(2 + w * h); + + pd.write[0] = w; + pd.write[1] = h; + + const uint8_t *r = img->get_data().ptr(); + + long *wr = &pd.write[2]; + uint8_t const *pr = r; + + for (int i = 0; i < w * h; i++) { + long v = 0; + // A R G B + v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2]; + *wr++ = v; + pr += 4; + } + + if (net_wm_icon != None) { + XChangeProperty(x11_display, wd.x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size()); + } + + if (!g_set_icon_error) { + break; + } + } + } else { + XDeleteProperty(x11_display, wd.x11_window, net_wm_icon); + } + + XFlush(x11_display); + XSetErrorHandler(oldHandler); +} + +Vector<String> DisplayServerX11::get_rendering_drivers_func() { + Vector<String> drivers; + +#ifdef VULKAN_ENABLED + drivers.push_back("vulkan"); +#endif +#ifdef OPENGL_ENABLED + drivers.push_back("opengl"); +#endif + + return drivers; +} + +DisplayServer *DisplayServerX11::create_func(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) { + DisplayServer *ds = memnew(DisplayServerX11(p_rendering_driver, p_mode, p_flags, p_resolution, r_error)); + if (r_error != OK) { + ds->alert("Your video card driver does not support any of the supported Vulkan versions.\n" + "Please update your drivers or if you have a very old or integrated GPU upgrade it.", + "Unable to initialize Video driver"); + } + return ds; +} + +DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, uint32_t p_flags, const Rect2i &p_rect) { + //Create window + + long visualMask = VisualScreenMask; + int numberOfVisuals; + XVisualInfo vInfoTemplate = {}; + vInfoTemplate.screen = DefaultScreen(x11_display); + XVisualInfo *visualInfo = XGetVisualInfo(x11_display, visualMask, &vInfoTemplate, &numberOfVisuals); + + Colormap colormap = XCreateColormap(x11_display, RootWindow(x11_display, vInfoTemplate.screen), visualInfo->visual, AllocNone); + + XSetWindowAttributes windowAttributes = {}; + windowAttributes.colormap = colormap; + windowAttributes.background_pixel = 0xFFFFFFFF; + windowAttributes.border_pixel = 0; + windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask; + + unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask; + + WindowID id = window_id_counter++; + WindowData &wd = windows[id]; + + if ((id != MAIN_WINDOW_ID) && (p_flags & WINDOW_FLAG_BORDERLESS_BIT)) { + wd.menu_type = true; + } + + if (p_flags & WINDOW_FLAG_NO_FOCUS_BIT) { + wd.menu_type = true; + wd.no_focus = true; + } + + // Setup for menu subwindows: + // - override_redirect forces the WM not to interfere with the window, to avoid delays due to + // handling decorations and placement. + // On the other hand, focus changes need to be handled manually when this is set. + // - save_under is a hint for the WM to keep the content of windows behind to avoid repaint. + if (wd.menu_type) { + windowAttributes.override_redirect = True; + windowAttributes.save_under = True; + valuemask |= CWOverrideRedirect | CWSaveUnder; + } + + { + wd.x11_window = XCreateWindow(x11_display, RootWindow(x11_display, visualInfo->screen), p_rect.position.x, p_rect.position.y, p_rect.size.width > 0 ? p_rect.size.width : 1, p_rect.size.height > 0 ? p_rect.size.height : 1, 0, visualInfo->depth, InputOutput, visualInfo->visual, valuemask, &windowAttributes); + + // Enable receiving notification when the window is initialized (MapNotify) + // so the focus can be set at the right time. + if (wd.menu_type && !wd.no_focus) { + XSelectInput(x11_display, wd.x11_window, StructureNotifyMask); + } + + //associate PID + // make PID known to X11 + { + const long pid = OS::get_singleton()->get_process_id(); + Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False); + if (net_wm_pid != None) { + XChangeProperty(x11_display, wd.x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1); + } + } + + long im_event_mask = 0; + + { + XIEventMask all_event_mask; + XSetWindowAttributes new_attr; + + new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | + ButtonReleaseMask | EnterWindowMask | + LeaveWindowMask | PointerMotionMask | + Button1MotionMask | + Button2MotionMask | Button3MotionMask | + Button4MotionMask | Button5MotionMask | + ButtonMotionMask | KeymapStateMask | + ExposureMask | VisibilityChangeMask | + StructureNotifyMask | + SubstructureNotifyMask | SubstructureRedirectMask | + FocusChangeMask | PropertyChangeMask | + ColormapChangeMask | OwnerGrabButtonMask | + im_event_mask; + + XChangeWindowAttributes(x11_display, wd.x11_window, CWEventMask, &new_attr); + + static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; + + all_event_mask.deviceid = XIAllDevices; + all_event_mask.mask_len = sizeof(all_mask_data); + all_event_mask.mask = all_mask_data; + + XISetMask(all_event_mask.mask, XI_HierarchyChanged); + +#ifdef TOUCH_ENABLED + if (xi.touch_devices.size()) { + XISetMask(all_event_mask.mask, XI_TouchBegin); + XISetMask(all_event_mask.mask, XI_TouchUpdate); + XISetMask(all_event_mask.mask, XI_TouchEnd); + XISetMask(all_event_mask.mask, XI_TouchOwnership); + } +#endif + + XISelectEvents(x11_display, wd.x11_window, &all_event_mask, 1); + } + + /* set the titlebar name */ + XStoreName(x11_display, wd.x11_window, "Godot"); + XSetWMProtocols(x11_display, wd.x11_window, &wm_delete, 1); + if (xdnd_aware != None) { + XChangeProperty(x11_display, wd.x11_window, xdnd_aware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&xdnd_version, 1); + } + + if (xim && xim_style) { + // Block events polling while changing input focus + // because it triggers some event polling internally. + MutexLock mutex_lock(events_mutex); + + wd.xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, wd.x11_window, XNFocusWindow, wd.x11_window, (char *)nullptr); + if (XGetICValues(wd.xic, XNFilterEvents, &im_event_mask, nullptr) != nullptr) { + WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value"); + XDestroyIC(wd.xic); + wd.xic = nullptr; + } + if (wd.xic) { + XUnsetICFocus(wd.xic); + } else { + WARN_PRINT("XCreateIC couldn't create wd.xic"); + } + } else { + wd.xic = nullptr; + WARN_PRINT("XCreateIC couldn't create wd.xic"); + } + + _update_context(wd); + + if (p_flags & WINDOW_FLAG_BORDERLESS_BIT) { + Hints hints; + Atom property; + hints.flags = 2; + hints.decorations = 0; + property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); + if (property != None) { + XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); + } + } + + if (wd.menu_type) { + // Set Utility type to disable fade animations. + Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_UTILITY", False); + Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False); + if (wt_atom != None && type_atom != None) { + XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1); + } + } else { + Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_NORMAL", False); + Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False); + + if (wt_atom != None && type_atom != None) { + XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1); + } + } + + _update_size_hints(id); + +#if defined(VULKAN_ENABLED) + if (context_vulkan) { + Error err = context_vulkan->window_create(id, wd.x11_window, x11_display, p_rect.size.width, p_rect.size.height); + ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a Vulkan window"); + } +#endif + + //set_class_hint(x11_display, wd.x11_window); + XFlush(x11_display); + + XSync(x11_display, False); + //XSetErrorHandler(oldHandler); + + XFree(visualInfo); + } + + window_set_mode(p_mode, id); + + //sync size + { + XWindowAttributes xwa; + + XSync(x11_display, False); + XGetWindowAttributes(x11_display, wd.x11_window, &xwa); + + wd.position.x = xwa.x; + wd.position.y = xwa.y; + wd.size.width = xwa.width; + wd.size.height = xwa.height; + } + + //set cursor + if (cursors[current_cursor] != None) { + XDefineCursor(x11_display, wd.x11_window, cursors[current_cursor]); + } + + return id; +} + +DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) { + Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events); + + r_error = OK; + + current_cursor = CURSOR_ARROW; + mouse_mode = MOUSE_MODE_VISIBLE; + + for (int i = 0; i < CURSOR_MAX; i++) { + cursors[i] = None; + img[i] = nullptr; + } + + xmbstring = nullptr; + + last_click_ms = 0; + last_click_button_index = -1; + last_click_pos = Point2i(-100, -100); + + last_timestamp = 0; + last_mouse_pos_valid = false; + last_keyrelease_time = 0; + + XInitThreads(); //always use threads + + /** XLIB INITIALIZATION **/ + x11_display = XOpenDisplay(nullptr); + + if (!x11_display) { + ERR_PRINT("X11 Display is not available"); + r_error = ERR_UNAVAILABLE; + return; + } + + char *modifiers = nullptr; + Bool xkb_dar = False; + XAutoRepeatOn(x11_display); + xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, nullptr); + + // Try to support IME if detectable auto-repeat is supported + if (xkb_dar == True) { +#ifdef X_HAVE_UTF8_STRING + // Xutf8LookupString will be used later instead of XmbLookupString before + // the multibyte sequences can be converted to unicode string. + modifiers = XSetLocaleModifiers(""); +#endif + } + + if (modifiers == nullptr) { + if (OS::get_singleton()->is_stdout_verbose()) { + WARN_PRINT("IME is disabled"); + } + XSetLocaleModifiers("@im=none"); + WARN_PRINT("Error setting locale modifiers"); + } + + const char *err; + xrr_get_monitors = nullptr; + xrr_free_monitors = nullptr; + int xrandr_major = 0; + int xrandr_minor = 0; + int event_base, error_base; + xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base); + xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY); + if (!xrandr_handle) { + err = dlerror(); + // For some arcane reason, NetBSD now ships libXrandr.so.3 while the rest of the world has libXrandr.so.2... + // In case this happens for other X11 platforms in the future, let's give it a try too before failing. + xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY); + if (!xrandr_handle) { + fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err); + } + } else { + XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor); + if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) { + xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors"); + if (!xrr_get_monitors) { + err = dlerror(); + fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err); + } else { + xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors"); + if (!xrr_free_monitors) { + err = dlerror(); + fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err); + xrr_get_monitors = nullptr; + } + } + } + } + + if (!_refresh_device_info()) { + alert("Your system does not support XInput 2.\n" + "Please upgrade your distribution.", + "Unable to initialize XInput"); + r_error = ERR_UNAVAILABLE; + return; + } + + xim = XOpenIM(x11_display, nullptr, nullptr, nullptr); + + if (xim == nullptr) { + WARN_PRINT("XOpenIM failed"); + xim_style = 0L; + } else { + ::XIMCallback im_destroy_callback; + im_destroy_callback.client_data = (::XPointer)(this); + im_destroy_callback.callback = (::XIMProc)(_xim_destroy_callback); + if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback, + nullptr) != nullptr) { + WARN_PRINT("Error setting XIM destroy callback"); + } + + ::XIMStyles *xim_styles = nullptr; + xim_style = 0L; + char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, nullptr); + if (imvalret != nullptr || xim_styles == nullptr) { + fprintf(stderr, "Input method doesn't support any styles\n"); + } + + if (xim_styles) { + xim_style = 0L; + for (int i = 0; i < xim_styles->count_styles; i++) { + if (xim_styles->supported_styles[i] == + (XIMPreeditNothing | XIMStatusNothing)) { + xim_style = xim_styles->supported_styles[i]; + break; + } + } + + XFree(xim_styles); + } + XFree(imvalret); + } + + /* Atorm internment */ + wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true); + //Set Xdnd (drag & drop) support + xdnd_aware = XInternAtom(x11_display, "XdndAware", False); + xdnd_version = 5; + xdnd_enter = XInternAtom(x11_display, "XdndEnter", False); + xdnd_position = XInternAtom(x11_display, "XdndPosition", False); + xdnd_status = XInternAtom(x11_display, "XdndStatus", False); + xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False); + xdnd_drop = XInternAtom(x11_display, "XdndDrop", False); + xdnd_finished = XInternAtom(x11_display, "XdndFinished", False); + xdnd_selection = XInternAtom(x11_display, "XdndSelection", False); + + //!!!!!!!!!!!!!!!!!!!!!!!!!! + //TODO - do Vulkan and GLES2 support checks, driver selection and fallback + rendering_driver = p_rendering_driver; + +#ifndef _MSC_VER +#warning Forcing vulkan rendering driver because OpenGL not implemented yet +#endif + rendering_driver = "vulkan"; + +#if defined(VULKAN_ENABLED) + if (rendering_driver == "vulkan") { + context_vulkan = memnew(VulkanContextX11); + if (context_vulkan->initialize() != OK) { + memdelete(context_vulkan); + context_vulkan = nullptr; + r_error = ERR_CANT_CREATE; + ERR_FAIL_MSG("Could not initialize Vulkan"); + } + } +#endif + // Init context and rendering device +#if defined(OPENGL_ENABLED) + if (rendering_driver == "opengl_es") { + if (getenv("DRI_PRIME") == nullptr) { + int use_prime = -1; + + if (getenv("PRIMUS_DISPLAY") || + getenv("PRIMUS_libGLd") || + getenv("PRIMUS_libGLa") || + getenv("PRIMUS_libGL") || + getenv("PRIMUS_LOAD_GLOBAL") || + getenv("BUMBLEBEE_SOCKET")) { + print_verbose("Optirun/primusrun detected. Skipping GPU detection"); + use_prime = 0; + } + + // Some tools use fake libGL libraries and have them override the real one using + // LD_LIBRARY_PATH, so we skip them. *But* Steam also sets LD_LIBRARY_PATH for its + // runtime and includes system `/lib` and `/lib64`... so ignore Steam. + if (use_prime == -1 && getenv("LD_LIBRARY_PATH") && !getenv("STEAM_RUNTIME_LIBRARY_PATH")) { + String ld_library_path(getenv("LD_LIBRARY_PATH")); + Vector<String> libraries = ld_library_path.split(":"); + + for (int i = 0; i < libraries.size(); ++i) { + if (FileAccess::exists(libraries[i] + "/libGL.so.1") || + FileAccess::exists(libraries[i] + "/libGL.so")) { + print_verbose("Custom libGL override detected. Skipping GPU detection"); + use_prime = 0; + } + } + } + + if (use_prime == -1) { + print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic."); + use_prime = detect_prime(); + } + + if (use_prime) { + print_line("Found discrete GPU, setting DRI_PRIME=1 to use it."); + print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU."); + setenv("DRI_PRIME", "1", 1); + } + } + + ContextGL_X11::ContextType opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; + + context_gles2 = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type)); + + if (context_gles2->initialize() != OK) { + memdelete(context_gles2); + context_gles2 = nullptr; + ERR_FAIL_V(ERR_UNAVAILABLE); + } + + context_gles2->set_use_vsync(current_videomode.use_vsync); + + if (RasterizerGLES2::is_viable() == OK) { + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + } else { + memdelete(context_gles2); + context_gles2 = nullptr; + ERR_FAIL_V(ERR_UNAVAILABLE); + } + } +#endif + Point2i window_position( + (screen_get_size(0).width - p_resolution.width) / 2, + (screen_get_size(0).height - p_resolution.height) / 2); + WindowID main_window = _create_window(p_mode, p_flags, Rect2i(window_position, p_resolution)); + if (main_window == INVALID_WINDOW_ID) { + r_error = ERR_CANT_CREATE; + return; + } + for (int i = 0; i < WINDOW_FLAG_MAX; i++) { + if (p_flags & (1 << i)) { + window_set_flag(WindowFlags(i), true, main_window); + } + } + show_window(main_window); + +//create RenderingDevice if used +#if defined(VULKAN_ENABLED) + if (rendering_driver == "vulkan") { + //temporary + rendering_device_vulkan = memnew(RenderingDeviceVulkan); + rendering_device_vulkan->initialize(context_vulkan); + + RendererCompositorRD::make_current(); + } +#endif + + /* + rendering_server = memnew(RenderingServerDefault); + if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { + rendering_server = memnew(RenderingServerWrapMT(rendering_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); + } + */ + + { + //set all event master mask + XIEventMask all_master_event_mask; + static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; + all_master_event_mask.deviceid = XIAllMasterDevices; + all_master_event_mask.mask_len = sizeof(all_master_mask_data); + all_master_event_mask.mask = all_master_mask_data; + XISetMask(all_master_event_mask.mask, XI_DeviceChanged); + XISetMask(all_master_event_mask.mask, XI_RawMotion); + XISelectEvents(x11_display, DefaultRootWindow(x11_display), &all_master_event_mask, 1); + } + + // Disabled by now since grabbing also blocks mouse events + // (they are received as extended events instead of standard events) + /*XIClearMask(xi.touch_event_mask.mask, XI_TouchOwnership); + + // Grab touch devices to avoid OS gesture interference + for (int i = 0; i < xi.touch_devices.size(); ++i) { + XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); + }*/ + + cursor_size = XcursorGetDefaultSize(x11_display); + cursor_theme = XcursorGetTheme(x11_display); + + if (!cursor_theme) { + print_verbose("XcursorGetTheme could not get cursor theme"); + cursor_theme = "default"; + } + + for (int i = 0; i < CURSOR_MAX; i++) { + static const char *cursor_file[] = { + "left_ptr", + "xterm", + "hand2", + "cross", + "watch", + "left_ptr_watch", + "fleur", + "dnd-move", + "crossed_circle", + "v_double_arrow", + "h_double_arrow", + "size_bdiag", + "size_fdiag", + "move", + "row_resize", + "col_resize", + "question_arrow" + }; + + img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size); + if (!img[i]) { + const char *fallback = nullptr; + + switch (i) { + case CURSOR_POINTING_HAND: + fallback = "pointer"; + break; + case CURSOR_CROSS: + fallback = "crosshair"; + break; + case CURSOR_WAIT: + fallback = "wait"; + break; + case CURSOR_BUSY: + fallback = "progress"; + break; + case CURSOR_DRAG: + fallback = "grabbing"; + break; + case CURSOR_CAN_DROP: + fallback = "hand1"; + break; + case CURSOR_FORBIDDEN: + fallback = "forbidden"; + break; + case CURSOR_VSIZE: + fallback = "ns-resize"; + break; + case CURSOR_HSIZE: + fallback = "ew-resize"; + break; + case CURSOR_BDIAGSIZE: + fallback = "fd_double_arrow"; + break; + case CURSOR_FDIAGSIZE: + fallback = "bd_double_arrow"; + break; + case CURSOR_MOVE: + img[i] = img[CURSOR_DRAG]; + break; + case CURSOR_VSPLIT: + fallback = "sb_v_double_arrow"; + break; + case CURSOR_HSPLIT: + fallback = "sb_h_double_arrow"; + break; + case CURSOR_HELP: + fallback = "help"; + break; + } + if (fallback != nullptr) { + img[i] = XcursorLibraryLoadImage(fallback, cursor_theme, cursor_size); + } + } + if (img[i]) { + cursors[i] = XcursorImageLoadCursor(x11_display, img[i]); + } else { + print_verbose("Failed loading custom cursor: " + String(cursor_file[i])); + } + } + + { + // Creating an empty/transparent cursor + + // Create 1x1 bitmap + Pixmap cursormask = XCreatePixmap(x11_display, + RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1); + + // Fill with zero + XGCValues xgc; + xgc.function = GXclear; + GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc); + XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1); + + // Color value doesn't matter. Mask zero means no foreground or background will be drawn + XColor col = {}; + + Cursor cursor = XCreatePixmapCursor(x11_display, + cursormask, // source (using cursor mask as placeholder, since it'll all be ignored) + cursormask, // mask + &col, &col, 0, 0); + + XFreePixmap(x11_display, cursormask); + XFreeGC(x11_display, gc); + + if (cursor == None) { + ERR_PRINT("FAILED CREATING CURSOR"); + } + + null_cursor = cursor; + } + cursor_set_shape(CURSOR_BUSY); + + requested = None; + + /*if (p_desired.layered) { + set_window_per_pixel_transparency_enabled(true); + }*/ + + XEvent xevent; + while (XPending(x11_display) > 0) { + XNextEvent(x11_display, &xevent); + if (xevent.type == ConfigureNotify) { + _window_changed(&xevent); + } + } + + events_thread.start(_poll_events_thread, this); + + _update_real_mouse_position(windows[MAIN_WINDOW_ID]); + +#ifdef DBUS_ENABLED + screensaver = memnew(FreeDesktopScreenSaver); + screen_set_keep_on(GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true)); +#endif + + r_error = OK; +} + +DisplayServerX11::~DisplayServerX11() { + // Send owned clipboard data to clipboard manager before exit. + Window x11_main_window = windows[MAIN_WINDOW_ID].x11_window; + _clipboard_transfer_ownership(XA_PRIMARY, x11_main_window); + _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_main_window); + + events_thread_done.set(); + events_thread.wait_to_finish(); + + //destroy all windows + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { +#ifdef VULKAN_ENABLED + if (rendering_driver == "vulkan") { + context_vulkan->window_destroy(E->key()); + } +#endif + + WindowData &wd = E->get(); + if (wd.xic) { + XDestroyIC(wd.xic); + wd.xic = nullptr; + } + XUnmapWindow(x11_display, wd.x11_window); + XDestroyWindow(x11_display, wd.x11_window); + } + + //destroy drivers +#if defined(VULKAN_ENABLED) + if (rendering_driver == "vulkan") { + if (rendering_device_vulkan) { + rendering_device_vulkan->finalize(); + memdelete(rendering_device_vulkan); + } + + if (context_vulkan) { + memdelete(context_vulkan); + } + } +#endif + + if (xrandr_handle) { + dlclose(xrandr_handle); + } + + for (int i = 0; i < CURSOR_MAX; i++) { + if (cursors[i] != None) { + XFreeCursor(x11_display, cursors[i]); + } + if (img[i] != nullptr) { + XcursorImageDestroy(img[i]); + } + }; + + if (xim) { + XCloseIM(xim); + } + + XCloseDisplay(x11_display); + if (xmbstring) { + memfree(xmbstring); + } + +#ifdef DBUS_ENABLED + memdelete(screensaver); +#endif +} + +void DisplayServerX11::register_x11_driver() { + register_create_function("x11", create_func, get_rendering_drivers_func); +} + +#endif // X11 enabled diff --git a/platform/linuxbsd/display_server_x11.h b/platform/linuxbsd/display_server_x11.h new file mode 100644 index 0000000000..707775a1da --- /dev/null +++ b/platform/linuxbsd/display_server_x11.h @@ -0,0 +1,397 @@ +/*************************************************************************/ +/* display_server_x11.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifndef DISPLAY_SERVER_X11_H +#define DISPLAY_SERVER_X11_H + +#ifdef X11_ENABLED + +#include "servers/display_server.h" + +#include "core/input/input.h" +#include "core/templates/local_vector.h" +#include "drivers/alsa/audio_driver_alsa.h" +#include "drivers/alsamidi/midi_driver_alsamidi.h" +#include "drivers/pulseaudio/audio_driver_pulseaudio.h" +#include "drivers/unix/os_unix.h" +#include "joypad_linux.h" +#include "servers/audio_server.h" +#include "servers/rendering/renderer_compositor.h" +#include "servers/rendering_server.h" + +#if defined(OPENGL_ENABLED) +#include "context_gl_x11.h" +#endif + +#if defined(VULKAN_ENABLED) +#include "drivers/vulkan/rendering_device_vulkan.h" +#include "platform/linuxbsd/vulkan_context_x11.h" +#endif + +#if defined(DBUS_ENABLED) +#include "freedesktop_screensaver.h" +#endif + +#include <X11/Xcursor/Xcursor.h> +#include <X11/Xlib.h> +#include <X11/extensions/XInput2.h> +#include <X11/extensions/Xrandr.h> +#include <X11/keysym.h> + +typedef struct _xrr_monitor_info { + Atom name; + Bool primary = false; + Bool automatic = false; + int noutput = 0; + int x = 0; + int y = 0; + int width = 0; + int height = 0; + int mwidth = 0; + int mheight = 0; + RROutput *outputs = nullptr; +} xrr_monitor_info; + +#undef CursorShape + +class DisplayServerX11 : public DisplayServer { + //No need to register, it's platform-specific and nothing is added + //GDCLASS(DisplayServerX11, DisplayServer) + + _THREAD_SAFE_CLASS_ + + Atom wm_delete; + Atom xdnd_enter; + Atom xdnd_position; + Atom xdnd_status; + Atom xdnd_action_copy; + Atom xdnd_drop; + Atom xdnd_finished; + Atom xdnd_selection; + Atom xdnd_aware; + Atom requested; + int xdnd_version; + +#if defined(OPENGL_ENABLED) + ContextGL_X11 *context_gles2; +#endif +#if defined(VULKAN_ENABLED) + VulkanContextX11 *context_vulkan; + RenderingDeviceVulkan *rendering_device_vulkan; +#endif + +#if defined(DBUS_ENABLED) + FreeDesktopScreenSaver *screensaver; + bool keep_screen_on = false; +#endif + + struct WindowData { + Window x11_window; + ::XIC xic; + + Size2i min_size; + Size2i max_size; + Point2i position; + Size2i size; + Point2i im_position; + bool im_active = false; + Callable rect_changed_callback; + Callable event_callback; + Callable input_event_callback; + Callable input_text_callback; + Callable drop_files_callback; + + WindowID transient_parent = INVALID_WINDOW_ID; + Set<WindowID> transient_children; + + ObjectID instance_id; + + bool menu_type = false; + bool no_focus = false; + + //better to guess on the fly, given WM can change it + //WindowMode mode; + bool fullscreen = false; //OS can't exit from this mode + bool on_top = false; + bool borderless = false; + bool resize_disabled = false; + Vector2i last_position_before_fs; + bool focused = false; + bool minimized = false; + + unsigned int focus_order = 0; + }; + + Map<WindowID, WindowData> windows; + + WindowID window_id_counter = MAIN_WINDOW_ID; + WindowID _create_window(WindowMode p_mode, uint32_t p_flags, const Rect2i &p_rect); + + String internal_clipboard; + Window xdnd_source_window; + ::Display *x11_display; + char *xmbstring; + int xmblen; + unsigned long last_timestamp; + ::Time last_keyrelease_time; + ::XIM xim; + ::XIMStyle xim_style; + static void _xim_destroy_callback(::XIM im, ::XPointer client_data, + ::XPointer call_data); + + Point2i last_mouse_pos; + bool last_mouse_pos_valid; + Point2i last_click_pos; + uint64_t last_click_ms; + int last_click_button_index; + MouseButton last_button_state = MOUSE_BUTTON_NONE; + bool app_focused = false; + uint64_t time_since_no_focus = 0; + + struct { + int opcode; + Vector<int> touch_devices; + Map<int, Vector2> absolute_devices; + Map<int, Vector2> pen_pressure_range; + Map<int, Vector2> pen_tilt_x_range; + Map<int, Vector2> pen_tilt_y_range; + XIEventMask all_event_mask; + Map<int, Vector2> state; + double pressure; + bool pressure_supported; + Vector2 tilt; + Vector2 mouse_pos_to_filter; + Vector2 relative_motion; + Vector2 raw_pos; + Vector2 old_raw_pos; + ::Time last_relative_time; + } xi; + + bool _refresh_device_info(); + + MouseButton _get_mouse_button_state(MouseButton p_x11_button, int p_x11_type); + void _get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state); + void _flush_mouse_motion(); + + MouseMode mouse_mode; + Point2i center; + + void _handle_key_event(WindowID p_window, XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo = false); + + Atom _process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property) const; + void _handle_selection_request_event(XSelectionRequestEvent *p_event) const; + + String _clipboard_get_impl(Atom p_source, Window x11_window, Atom target) const; + String _clipboard_get(Atom p_source, Window x11_window) const; + void _clipboard_transfer_ownership(Atom p_source, Window x11_window) const; + + //bool minimized; + //bool window_has_focus; + bool do_mouse_warp; + + const char *cursor_theme; + int cursor_size; + XcursorImage *img[CURSOR_MAX]; + Cursor cursors[CURSOR_MAX]; + Cursor null_cursor; + CursorShape current_cursor; + Map<CursorShape, Vector<Variant>> cursors_cache; + + bool layered_window; + + String rendering_driver; + //bool window_focused; + //void set_wm_border(bool p_enabled); + void set_wm_fullscreen(bool p_enabled); + void set_wm_above(bool p_enabled); + + typedef xrr_monitor_info *(*xrr_get_monitors_t)(Display *dpy, Window window, Bool get_active, int *nmonitors); + typedef void (*xrr_free_monitors_t)(xrr_monitor_info *monitors); + xrr_get_monitors_t xrr_get_monitors; + xrr_free_monitors_t xrr_free_monitors; + void *xrandr_handle; + Bool xrandr_ext_ok; + + struct Property { + unsigned char *data; + int format, nitems; + Atom type; + }; + static Property _read_property(Display *p_display, Window p_window, Atom p_property); + + void _update_real_mouse_position(const WindowData &wd); + bool _window_maximize_check(WindowID p_window, const char *p_atom_name) const; + void _update_size_hints(WindowID p_window); + void _set_wm_fullscreen(WindowID p_window, bool p_enabled); + void _set_wm_maximized(WindowID p_window, bool p_enabled); + + void _update_context(WindowData &wd); + + Context context = CONTEXT_ENGINE; + + void _send_window_event(const WindowData &wd, WindowEvent p_event); + static void _dispatch_input_events(const Ref<InputEvent> &p_event); + void _dispatch_input_event(const Ref<InputEvent> &p_event); + + mutable Mutex events_mutex; + Thread events_thread; + SafeFlag events_thread_done; + LocalVector<XEvent> polled_events; + static void _poll_events_thread(void *ud); + bool _wait_for_events() const; + void _poll_events(); + + static Bool _predicate_all_events(Display *display, XEvent *event, XPointer arg); + static Bool _predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg); + static Bool _predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg); + static Bool _predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg); + +protected: + void _window_changed(XEvent *event); + +public: + virtual bool has_feature(Feature p_feature) const; + virtual String get_name() const; + + virtual void alert(const String &p_alert, const String &p_title = "ALERT!"); + + virtual void mouse_set_mode(MouseMode p_mode); + virtual MouseMode mouse_get_mode() const; + + virtual void mouse_warp_to_position(const Point2i &p_to); + virtual Point2i mouse_get_position() const; + virtual Point2i mouse_get_absolute_position() const; + virtual MouseButton mouse_get_button_state() const; + + virtual void clipboard_set(const String &p_text); + virtual String clipboard_get() const; + + virtual int get_screen_count() const; + virtual Point2i screen_get_position(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + virtual Size2i screen_get_size(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + virtual Rect2i screen_get_usable_rect(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + virtual int screen_get_dpi(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + virtual bool screen_is_touchscreen(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + +#if defined(DBUS_ENABLED) + virtual void screen_set_keep_on(bool p_enable); + virtual bool screen_is_kept_on() const; +#endif + + virtual Vector<DisplayServer::WindowID> get_window_list() const; + + virtual WindowID create_sub_window(WindowMode p_mode, uint32_t p_flags, const Rect2i &p_rect = Rect2i()); + virtual void show_window(WindowID p_id); + virtual void delete_sub_window(WindowID p_id); + + virtual WindowID get_window_at_screen_position(const Point2i &p_position) const; + + virtual void window_attach_instance_id(ObjectID p_instance, WindowID p_window = MAIN_WINDOW_ID); + virtual ObjectID window_get_attached_instance_id(WindowID p_window = MAIN_WINDOW_ID) const; + + virtual void window_set_title(const String &p_title, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window = MAIN_WINDOW_ID); + + virtual void window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_window_event_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_input_event_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_input_text_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_drop_files_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + + virtual int window_get_current_screen(WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_set_current_screen(int p_screen, WindowID p_window = MAIN_WINDOW_ID); + + virtual Point2i window_get_position(WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_set_position(const Point2i &p_position, WindowID p_window = MAIN_WINDOW_ID); + + virtual void window_set_max_size(const Size2i p_size, WindowID p_window = MAIN_WINDOW_ID); + virtual Size2i window_get_max_size(WindowID p_window = MAIN_WINDOW_ID) const; + + virtual void window_set_transient(WindowID p_window, WindowID p_parent); + + virtual void window_set_min_size(const Size2i p_size, WindowID p_window = MAIN_WINDOW_ID); + virtual Size2i window_get_min_size(WindowID p_window = MAIN_WINDOW_ID) const; + + virtual void window_set_size(const Size2i p_size, WindowID p_window = MAIN_WINDOW_ID); + virtual Size2i window_get_size(WindowID p_window = MAIN_WINDOW_ID) const; + virtual Size2i window_get_real_size(WindowID p_window = MAIN_WINDOW_ID) const; + + virtual void window_set_mode(WindowMode p_mode, WindowID p_window = MAIN_WINDOW_ID); + virtual WindowMode window_get_mode(WindowID p_window = MAIN_WINDOW_ID) const; + + virtual bool window_is_maximize_allowed(WindowID p_window = MAIN_WINDOW_ID) const; + + virtual void window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window = MAIN_WINDOW_ID); + virtual bool window_get_flag(WindowFlags p_flag, WindowID p_window = MAIN_WINDOW_ID) const; + + virtual void window_request_attention(WindowID p_window = MAIN_WINDOW_ID); + + virtual void window_move_to_foreground(WindowID p_window = MAIN_WINDOW_ID); + + virtual bool window_can_draw(WindowID p_window = MAIN_WINDOW_ID) const; + + virtual bool can_any_window_draw() const; + + virtual void window_set_ime_active(const bool p_active, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_ime_position(const Point2i &p_pos, WindowID p_window = MAIN_WINDOW_ID); + + virtual void cursor_set_shape(CursorShape p_shape); + virtual CursorShape cursor_get_shape() const; + virtual void cursor_set_custom_image(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot); + + virtual int keyboard_get_layout_count() const; + virtual int keyboard_get_current_layout() const; + virtual void keyboard_set_current_layout(int p_index); + virtual String keyboard_get_layout_language(int p_index) const; + virtual String keyboard_get_layout_name(int p_index) const; + + virtual void process_events(); + + virtual void release_rendering_thread(); + virtual void make_rendering_thread(); + virtual void swap_buffers(); + + virtual void set_context(Context p_context); + + virtual void set_native_icon(const String &p_filename); + virtual void set_icon(const Ref<Image> &p_icon); + + static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error); + static Vector<String> get_rendering_drivers_func(); + + static void register_x11_driver(); + + DisplayServerX11(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error); + ~DisplayServerX11(); +}; + +#endif // X11 enabled + +#endif // DISPLAY_SERVER_X11_H diff --git a/platform/linuxbsd/export/export.cpp b/platform/linuxbsd/export/export.cpp new file mode 100644 index 0000000000..5c6be2d7d4 --- /dev/null +++ b/platform/linuxbsd/export/export.cpp @@ -0,0 +1,166 @@ +/*************************************************************************/ +/* export.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#include "export.h" + +#include "core/io/file_access.h" +#include "editor/editor_export.h" +#include "platform/linuxbsd/logo.gen.h" +#include "scene/resources/texture.h" + +static Error fixup_embedded_pck(const String &p_path, int64_t p_embedded_start, int64_t p_embedded_size); + +void register_linuxbsd_exporter() { + Ref<EditorExportPlatformPC> platform; + platform.instantiate(); + + Ref<Image> img = memnew(Image(_linuxbsd_logo)); + Ref<ImageTexture> logo; + logo.instantiate(); + logo->create_from_image(img); + platform->set_logo(logo); + platform->set_name("Linux/X11"); + platform->set_extension("x86"); + platform->set_extension("x86_64", "binary_format/64_bits"); + platform->set_release_32("linux_x11_32_release"); + platform->set_debug_32("linux_x11_32_debug"); + platform->set_release_64("linux_x11_64_release"); + platform->set_debug_64("linux_x11_64_debug"); + platform->set_os_name("X11"); + platform->set_chmod_flags(0755); + platform->set_fixup_embedded_pck_func(&fixup_embedded_pck); + + EditorExport::get_singleton()->add_export_platform(platform); +} + +static Error fixup_embedded_pck(const String &p_path, int64_t p_embedded_start, int64_t p_embedded_size) { + // Patch the header of the "pck" section in the ELF file so that it corresponds to the embedded data + + FileAccess *f = FileAccess::open(p_path, FileAccess::READ_WRITE); + if (!f) { + return ERR_CANT_OPEN; + } + + // Read and check ELF magic number + { + uint32_t magic = f->get_32(); + if (magic != 0x464c457f) { // 0x7F + "ELF" + f->close(); + return ERR_FILE_CORRUPT; + } + } + + // Read program architecture bits from class field + + int bits = f->get_8() * 32; + + if (bits == 32 && p_embedded_size >= 0x100000000) { + f->close(); + ERR_FAIL_V_MSG(ERR_INVALID_DATA, "32-bit executables cannot have embedded data >= 4 GiB."); + } + + // Get info about the section header table + + int64_t section_table_pos; + int64_t section_header_size; + if (bits == 32) { + section_header_size = 40; + f->seek(0x20); + section_table_pos = f->get_32(); + f->seek(0x30); + } else { // 64 + section_header_size = 64; + f->seek(0x28); + section_table_pos = f->get_64(); + f->seek(0x3c); + } + int num_sections = f->get_16(); + int string_section_idx = f->get_16(); + + // Load the strings table + uint8_t *strings; + { + // Jump to the strings section header + f->seek(section_table_pos + string_section_idx * section_header_size); + + // Read strings data size and offset + int64_t string_data_pos; + int64_t string_data_size; + if (bits == 32) { + f->seek(f->get_position() + 0x10); + string_data_pos = f->get_32(); + string_data_size = f->get_32(); + } else { // 64 + f->seek(f->get_position() + 0x18); + string_data_pos = f->get_64(); + string_data_size = f->get_64(); + } + + // Read strings data + f->seek(string_data_pos); + strings = (uint8_t *)memalloc(string_data_size); + if (!strings) { + f->close(); + return ERR_OUT_OF_MEMORY; + } + f->get_buffer(strings, string_data_size); + } + + // Search for the "pck" section + + bool found = false; + for (int i = 0; i < num_sections; ++i) { + int64_t section_header_pos = section_table_pos + i * section_header_size; + f->seek(section_header_pos); + + uint32_t name_offset = f->get_32(); + if (strcmp((char *)strings + name_offset, "pck") == 0) { + // "pck" section found, let's patch! + + if (bits == 32) { + f->seek(section_header_pos + 0x10); + f->store_32(p_embedded_start); + f->store_32(p_embedded_size); + } else { // 64 + f->seek(section_header_pos + 0x18); + f->store_64(p_embedded_start); + f->store_64(p_embedded_size); + } + + found = true; + break; + } + } + + memfree(strings); + f->close(); + + return found ? OK : ERR_FILE_CORRUPT; +} diff --git a/platform/linuxbsd/export/export.h b/platform/linuxbsd/export/export.h new file mode 100644 index 0000000000..61e96aa2f6 --- /dev/null +++ b/platform/linuxbsd/export/export.h @@ -0,0 +1,36 @@ +/*************************************************************************/ +/* export.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifndef LINUXBSD_EXPORT_H +#define LINUXBSD_EXPORT_H + +void register_linuxbsd_exporter(); + +#endif // LINUXBSD_EXPORT_H diff --git a/platform/linuxbsd/freedesktop_screensaver.cpp b/platform/linuxbsd/freedesktop_screensaver.cpp new file mode 100644 index 0000000000..23093698ba --- /dev/null +++ b/platform/linuxbsd/freedesktop_screensaver.cpp @@ -0,0 +1,124 @@ +/*************************************************************************/ +/* freedesktop_screensaver.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#include "freedesktop_screensaver.h" + +#ifdef DBUS_ENABLED + +#include "core/config/project_settings.h" + +#include <dbus/dbus.h> + +#define BUS_OBJECT_NAME "org.freedesktop.ScreenSaver" +#define BUS_OBJECT_PATH "/org/freedesktop/ScreenSaver" +#define BUS_INTERFACE "org.freedesktop.ScreenSaver" + +void FreeDesktopScreenSaver::inhibit() { + if (unsupported) { + return; + } + + DBusError error; + dbus_error_init(&error); + + DBusConnection *bus = dbus_bus_get(DBUS_BUS_SESSION, &error); + if (dbus_error_is_set(&error)) { + unsupported = true; + return; + } + + String app_name_string = ProjectSettings::get_singleton()->get("application/config/name"); + const char *app_name = app_name_string.is_empty() ? "Godot Engine" : app_name_string.utf8().get_data(); + + const char *reason = "Running Godot Engine project"; + + DBusMessage *message = dbus_message_new_method_call( + BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE, + "Inhibit"); + dbus_message_append_args( + message, + DBUS_TYPE_STRING, &app_name, + DBUS_TYPE_STRING, &reason, + DBUS_TYPE_INVALID); + + DBusMessage *reply = dbus_connection_send_with_reply_and_block(bus, message, 50, &error); + dbus_message_unref(message); + if (dbus_error_is_set(&error)) { + dbus_connection_unref(bus); + unsupported = false; + return; + } + + DBusMessageIter reply_iter; + dbus_message_iter_init(reply, &reply_iter); + dbus_message_iter_get_basic(&reply_iter, &cookie); + print_verbose("FreeDesktopScreenSaver: Acquired screensaver inhibition cookie: " + uitos(cookie)); + + dbus_message_unref(reply); + dbus_connection_unref(bus); +} + +void FreeDesktopScreenSaver::uninhibit() { + if (unsupported) { + return; + } + + DBusError error; + dbus_error_init(&error); + + DBusConnection *bus = dbus_bus_get(DBUS_BUS_SESSION, &error); + if (dbus_error_is_set(&error)) { + unsupported = true; + return; + } + + DBusMessage *message = dbus_message_new_method_call( + BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE, + "UnInhibit"); + dbus_message_append_args( + message, + DBUS_TYPE_UINT32, &cookie, + DBUS_TYPE_INVALID); + + DBusMessage *reply = dbus_connection_send_with_reply_and_block(bus, message, 50, &error); + if (dbus_error_is_set(&error)) { + dbus_connection_unref(bus); + unsupported = true; + return; + } + + print_verbose("FreeDesktopScreenSaver: Released screensaver inhibition cookie: " + uitos(cookie)); + + dbus_message_unref(message); + dbus_message_unref(reply); + dbus_connection_unref(bus); +} + +#endif // DBUS_ENABLED diff --git a/platform/linuxbsd/freedesktop_screensaver.h b/platform/linuxbsd/freedesktop_screensaver.h new file mode 100644 index 0000000000..f27e60fce4 --- /dev/null +++ b/platform/linuxbsd/freedesktop_screensaver.h @@ -0,0 +1,47 @@ +/*************************************************************************/ +/* freedesktop_screensaver.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifdef DBUS_ENABLED + +#include <dbus/dbus.h> +#include <stdint.h> + +class FreeDesktopScreenSaver { +private: + uint32_t cookie = 0; + bool unsupported = false; + +public: + FreeDesktopScreenSaver() {} + void inhibit(); + void uninhibit(); +}; + +#endif // DBUS_ENABLED diff --git a/platform/linuxbsd/godot_linuxbsd.cpp b/platform/linuxbsd/godot_linuxbsd.cpp new file mode 100644 index 0000000000..6f5c46b59c --- /dev/null +++ b/platform/linuxbsd/godot_linuxbsd.cpp @@ -0,0 +1,70 @@ +/*************************************************************************/ +/* godot_linuxbsd.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#include <limits.h> +#include <locale.h> +#include <stdlib.h> +#include <unistd.h> + +#include "main/main.h" +#include "os_linuxbsd.h" + +int main(int argc, char *argv[]) { + OS_LinuxBSD os; + + setlocale(LC_CTYPE, ""); + + // We must override main when testing is enabled + TEST_MAIN_OVERRIDE + + char *cwd = (char *)malloc(PATH_MAX); + ERR_FAIL_COND_V(!cwd, ERR_OUT_OF_MEMORY); + char *ret = getcwd(cwd, PATH_MAX); + + Error err = Main::setup(argv[0], argc - 1, &argv[1]); + if (err != OK) { + free(cwd); + return 255; + } + + if (Main::start()) { + os.run(); // it is actually the OS that decides how to run + } + Main::cleanup(); + + if (ret) { // Previous getcwd was successful + if (chdir(cwd) != 0) { + ERR_PRINT("Couldn't return to previous working directory."); + } + } + free(cwd); + + return os.get_exit_code(); +} diff --git a/platform/linuxbsd/joypad_linux.cpp b/platform/linuxbsd/joypad_linux.cpp new file mode 100644 index 0000000000..8b6dbc4c20 --- /dev/null +++ b/platform/linuxbsd/joypad_linux.cpp @@ -0,0 +1,551 @@ +/*************************************************************************/ +/* joypad_linux.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifdef JOYDEV_ENABLED + +#include "joypad_linux.h" + +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <linux/input.h> +#include <unistd.h> + +#ifdef UDEV_ENABLED +#include "libudev-so_wrap.h" +#endif + +#define LONG_BITS (sizeof(long) * 8) +#define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0) +#define NBITS(x) ((((x)-1) / LONG_BITS) + 1) + +#ifdef UDEV_ENABLED +static const char *ignore_str = "/dev/input/js"; +#endif + +JoypadLinux::Joypad::~Joypad() { + for (int i = 0; i < MAX_ABS; i++) { + if (abs_info[i]) { + memdelete(abs_info[i]); + } + } +} + +void JoypadLinux::Joypad::reset() { + dpad = 0; + fd = -1; + + Input::JoyAxisValue jx; + jx.min = -1; + jx.value = 0.0f; + for (int i = 0; i < MAX_ABS; i++) { + abs_map[i] = -1; + curr_axis[i] = jx; + } +} + +JoypadLinux::JoypadLinux(Input *in) { +#ifdef UDEV_ENABLED +#ifdef DEBUG_ENABLED + int dylibloader_verbose = 1; +#else + int dylibloader_verbose = 0; +#endif + use_udev = initialize_libudev(dylibloader_verbose) == 0; + if (use_udev) { + print_verbose("JoypadLinux: udev enabled and loaded successfully."); + } else { + print_verbose("JoypadLinux: udev enabled, but couldn't be loaded. Falling back to /dev/input to detect joypads."); + } +#else + print_verbose("JoypadLinux: udev disabled, parsing /dev/input to detect joypads."); +#endif + input = in; + joy_thread.start(joy_thread_func, this); +} + +JoypadLinux::~JoypadLinux() { + exit_monitor.set(); + joy_thread.wait_to_finish(); + close_joypad(); +} + +void JoypadLinux::joy_thread_func(void *p_user) { + if (p_user) { + JoypadLinux *joy = (JoypadLinux *)p_user; + joy->run_joypad_thread(); + } +} + +void JoypadLinux::run_joypad_thread() { +#ifdef UDEV_ENABLED + if (use_udev) { + udev *_udev = udev_new(); + if (!_udev) { + use_udev = false; + ERR_PRINT("Failed getting an udev context, falling back to parsing /dev/input."); + monitor_joypads(); + } else { + enumerate_joypads(_udev); + monitor_joypads(_udev); + udev_unref(_udev); + } + } else { + monitor_joypads(); + } +#else + monitor_joypads(); +#endif +} + +#ifdef UDEV_ENABLED +void JoypadLinux::enumerate_joypads(udev *p_udev) { + udev_enumerate *enumerate; + udev_list_entry *devices, *dev_list_entry; + udev_device *dev; + + enumerate = udev_enumerate_new(p_udev); + udev_enumerate_add_match_subsystem(enumerate, "input"); + + udev_enumerate_scan_devices(enumerate); + devices = udev_enumerate_get_list_entry(enumerate); + udev_list_entry_foreach(dev_list_entry, devices) { + const char *path = udev_list_entry_get_name(dev_list_entry); + dev = udev_device_new_from_syspath(p_udev, path); + const char *devnode = udev_device_get_devnode(dev); + + if (devnode) { + String devnode_str = devnode; + if (devnode_str.find(ignore_str) == -1) { + MutexLock lock(joy_mutex); + open_joypad(devnode); + } + } + udev_device_unref(dev); + } + udev_enumerate_unref(enumerate); +} + +void JoypadLinux::monitor_joypads(udev *p_udev) { + udev_device *dev = nullptr; + udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev"); + udev_monitor_filter_add_match_subsystem_devtype(mon, "input", nullptr); + udev_monitor_enable_receiving(mon); + int fd = udev_monitor_get_fd(mon); + + while (!exit_monitor.is_set()) { + fd_set fds; + struct timeval tv; + int ret; + + FD_ZERO(&fds); + FD_SET(fd, &fds); + tv.tv_sec = 0; + tv.tv_usec = 0; + + ret = select(fd + 1, &fds, nullptr, nullptr, &tv); + + /* Check if our file descriptor has received data. */ + if (ret > 0 && FD_ISSET(fd, &fds)) { + /* Make the call to receive the device. + select() ensured that this will not block. */ + dev = udev_monitor_receive_device(mon); + + if (dev && udev_device_get_devnode(dev) != nullptr) { + MutexLock lock(joy_mutex); + String action = udev_device_get_action(dev); + const char *devnode = udev_device_get_devnode(dev); + if (devnode) { + String devnode_str = devnode; + if (devnode_str.find(ignore_str) == -1) { + if (action == "add") { + open_joypad(devnode); + } else if (String(action) == "remove") { + close_joypad(get_joy_from_path(devnode)); + } + } + } + + udev_device_unref(dev); + } + } + usleep(50000); + } + udev_monitor_unref(mon); +} +#endif + +void JoypadLinux::monitor_joypads() { + while (!exit_monitor.is_set()) { + { + MutexLock lock(joy_mutex); + + DIR *input_directory; + input_directory = opendir("/dev/input"); + if (input_directory) { + struct dirent *current; + char fname[64]; + + while ((current = readdir(input_directory)) != nullptr) { + if (strncmp(current->d_name, "event", 5) != 0) { + continue; + } + sprintf(fname, "/dev/input/%.*s", 16, current->d_name); + if (attached_devices.find(fname) == -1) { + open_joypad(fname); + } + } + } + closedir(input_directory); + } + usleep(1000000); // 1s + } +} + +int JoypadLinux::get_joy_from_path(String p_path) const { + for (int i = 0; i < JOYPADS_MAX; i++) { + if (joypads[i].devpath == p_path) { + return i; + } + } + return -2; +} + +void JoypadLinux::close_joypad(int p_id) { + if (p_id == -1) { + for (int i = 0; i < JOYPADS_MAX; i++) { + close_joypad(i); + }; + return; + } else if (p_id < 0) { + return; + } + + Joypad &joy = joypads[p_id]; + + if (joy.fd != -1) { + close(joy.fd); + joy.fd = -1; + attached_devices.remove(attached_devices.find(joy.devpath)); + input->joy_connection_changed(p_id, false, ""); + }; +} + +static String _hex_str(uint8_t p_byte) { + static const char *dict = "0123456789abcdef"; + char ret[3]; + ret[2] = 0; + + ret[0] = dict[p_byte >> 4]; + ret[1] = dict[p_byte & 0xF]; + + return ret; +} + +void JoypadLinux::setup_joypad_properties(int p_id) { + Joypad *joy = &joypads[p_id]; + + unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; + unsigned long absbit[NBITS(ABS_MAX)] = { 0 }; + + int num_buttons = 0; + int num_axes = 0; + + if ((ioctl(joy->fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) || + (ioctl(joy->fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) { + return; + } + for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) { + if (test_bit(i, keybit)) { + joy->key_map[i] = num_buttons++; + } + } + for (int i = BTN_MISC; i < BTN_JOYSTICK; ++i) { + if (test_bit(i, keybit)) { + joy->key_map[i] = num_buttons++; + } + } + for (int i = 0; i < ABS_MISC; ++i) { + /* Skip hats */ + if (i == ABS_HAT0X) { + i = ABS_HAT3Y; + continue; + } + if (test_bit(i, absbit)) { + joy->abs_map[i] = num_axes++; + joy->abs_info[i] = memnew(input_absinfo); + if (ioctl(joy->fd, EVIOCGABS(i), joy->abs_info[i]) < 0) { + memdelete(joy->abs_info[i]); + joy->abs_info[i] = nullptr; + } + } + } + + joy->force_feedback = false; + joy->ff_effect_timestamp = 0; + unsigned long ffbit[NBITS(FF_CNT)]; + if (ioctl(joy->fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) != -1) { + if (test_bit(FF_RUMBLE, ffbit)) { + joy->force_feedback = true; + } + } +} + +void JoypadLinux::open_joypad(const char *p_path) { + int joy_num = input->get_unused_joy_id(); + int fd = open(p_path, O_RDWR | O_NONBLOCK); + if (fd != -1 && joy_num != -1) { + unsigned long evbit[NBITS(EV_MAX)] = { 0 }; + unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; + unsigned long absbit[NBITS(ABS_MAX)] = { 0 }; + + // add to attached devices so we don't try to open it again + attached_devices.push_back(String(p_path)); + + if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) || + (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) || + (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) { + close(fd); + return; + } + + // Check if the device supports basic gamepad events + if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) && + test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit))) { + close(fd); + return; + } + + char uid[128]; + char namebuf[128]; + String name = ""; + input_id inpid; + if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) { + name = namebuf; + } + + if (ioctl(fd, EVIOCGID, &inpid) < 0) { + close(fd); + return; + } + + joypads[joy_num].reset(); + + Joypad &joy = joypads[joy_num]; + joy.fd = fd; + joy.devpath = String(p_path); + setup_joypad_properties(joy_num); + sprintf(uid, "%04x%04x", BSWAP16(inpid.bustype), 0); + if (inpid.vendor && inpid.product && inpid.version) { + uint16_t vendor = BSWAP16(inpid.vendor); + uint16_t product = BSWAP16(inpid.product); + uint16_t version = BSWAP16(inpid.version); + + sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor, 0, product, 0, version, 0); + input->joy_connection_changed(joy_num, true, name, uid); + } else { + String uidname = uid; + int uidlen = MIN(name.length(), 11); + for (int i = 0; i < uidlen; i++) { + uidname = uidname + _hex_str(name[i]); + } + uidname += "00"; + input->joy_connection_changed(joy_num, true, name, uidname); + } + } +} + +void JoypadLinux::joypad_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) { + Joypad &joy = joypads[p_id]; + if (!joy.force_feedback || joy.fd == -1 || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) { + return; + } + if (joy.ff_effect_id != -1) { + joypad_vibration_stop(p_id, p_timestamp); + } + + struct ff_effect effect; + effect.type = FF_RUMBLE; + effect.id = -1; + effect.u.rumble.weak_magnitude = floor(p_weak_magnitude * (float)0xffff); + effect.u.rumble.strong_magnitude = floor(p_strong_magnitude * (float)0xffff); + effect.replay.length = floor(p_duration * 1000); + effect.replay.delay = 0; + + if (ioctl(joy.fd, EVIOCSFF, &effect) < 0) { + return; + } + + struct input_event play; + play.type = EV_FF; + play.code = effect.id; + play.value = 1; + if (write(joy.fd, (const void *)&play, sizeof(play)) == -1) { + print_verbose("Couldn't write to Joypad device."); + } + + joy.ff_effect_id = effect.id; + joy.ff_effect_timestamp = p_timestamp; +} + +void JoypadLinux::joypad_vibration_stop(int p_id, uint64_t p_timestamp) { + Joypad &joy = joypads[p_id]; + if (!joy.force_feedback || joy.fd == -1 || joy.ff_effect_id == -1) { + return; + } + + if (ioctl(joy.fd, EVIOCRMFF, joy.ff_effect_id) < 0) { + return; + } + + joy.ff_effect_id = -1; + joy.ff_effect_timestamp = p_timestamp; +} + +Input::JoyAxisValue JoypadLinux::axis_correct(const input_absinfo *p_abs, int p_value) const { + int min = p_abs->minimum; + int max = p_abs->maximum; + Input::JoyAxisValue jx; + + if (min < 0) { + jx.min = -1; + if (p_value < 0) { + jx.value = (float)-p_value / min; + } else { + jx.value = (float)p_value / max; + } + } else if (min == 0) { + jx.min = 0; + jx.value = 0.0f + (float)p_value / max; + } + return jx; +} + +void JoypadLinux::process_joypads() { + if (joy_mutex.try_lock() != OK) { + return; + } + for (int i = 0; i < JOYPADS_MAX; i++) { + if (joypads[i].fd == -1) { + continue; + } + + input_event events[32]; + Joypad *joy = &joypads[i]; + + int len; + + while ((len = read(joy->fd, events, (sizeof events))) > 0) { + len /= sizeof(events[0]); + for (int j = 0; j < len; j++) { + input_event &ev = events[j]; + + // ev may be tainted and out of MAX_KEY range, which will cause + // joy->key_map[ev.code] to crash + if (ev.code >= MAX_KEY) { + return; + } + + switch (ev.type) { + case EV_KEY: + input->joy_button(i, (JoyButton)joy->key_map[ev.code], ev.value); + break; + + case EV_ABS: + + switch (ev.code) { + case ABS_HAT0X: + if (ev.value != 0) { + if (ev.value < 0) { + joy->dpad = (HatMask)((joy->dpad | HatMask::HAT_MASK_LEFT) & ~HatMask::HAT_MASK_RIGHT); + } else { + joy->dpad = (HatMask)((joy->dpad | HatMask::HAT_MASK_RIGHT) & ~HatMask::HAT_MASK_LEFT); + } + } else { + joy->dpad &= ~(HatMask::HAT_MASK_LEFT | HatMask::HAT_MASK_RIGHT); + } + + input->joy_hat(i, (HatMask)joy->dpad); + break; + + case ABS_HAT0Y: + if (ev.value != 0) { + if (ev.value < 0) { + joy->dpad = (HatMask)((joy->dpad | HatMask::HAT_MASK_UP) & ~HatMask::HAT_MASK_DOWN); + } else { + joy->dpad = (HatMask)((joy->dpad | HatMask::HAT_MASK_DOWN) & ~HatMask::HAT_MASK_UP); + } + } else { + joy->dpad &= ~(HatMask::HAT_MASK_UP | HatMask::HAT_MASK_DOWN); + } + + input->joy_hat(i, (HatMask)joy->dpad); + break; + + default: + if (ev.code >= MAX_ABS) { + return; + } + if (joy->abs_map[ev.code] != -1 && joy->abs_info[ev.code]) { + Input::JoyAxisValue value = axis_correct(joy->abs_info[ev.code], ev.value); + joy->curr_axis[joy->abs_map[ev.code]] = value; + } + break; + } + break; + } + } + } + for (int j = 0; j < MAX_ABS; j++) { + int index = joy->abs_map[j]; + if (index != -1) { + input->joy_axis(i, (JoyAxis)index, joy->curr_axis[index]); + } + } + if (len == 0 || (len < 0 && errno != EAGAIN)) { + close_joypad(i); + }; + + if (joy->force_feedback) { + uint64_t timestamp = input->get_joy_vibration_timestamp(i); + if (timestamp > joy->ff_effect_timestamp) { + Vector2 strength = input->get_joy_vibration_strength(i); + float duration = input->get_joy_vibration_duration(i); + if (strength.x == 0 && strength.y == 0) { + joypad_vibration_stop(i, timestamp); + } else { + joypad_vibration_start(i, strength.x, strength.y, duration, timestamp); + } + } + } + } + joy_mutex.unlock(); +} +#endif diff --git a/platform/linuxbsd/joypad_linux.h b/platform/linuxbsd/joypad_linux.h new file mode 100644 index 0000000000..177d7a51ce --- /dev/null +++ b/platform/linuxbsd/joypad_linux.h @@ -0,0 +1,104 @@ +/*************************************************************************/ +/* joypad_linux.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +//author: Andreas Haas <hondres, liugam3@gmail.com> +#ifndef JOYPAD_LINUX_H +#define JOYPAD_LINUX_H + +#ifdef JOYDEV_ENABLED +#include "core/input/input.h" +#include "core/os/mutex.h" +#include "core/os/thread.h" + +struct input_absinfo; + +class JoypadLinux { +public: + JoypadLinux(Input *in); + ~JoypadLinux(); + void process_joypads(); + +private: + enum { + JOYPADS_MAX = 16, + MAX_ABS = 63, + MAX_KEY = 767, // Hack because <linux/input.h> can't be included here + }; + + struct Joypad { + Input::JoyAxisValue curr_axis[MAX_ABS]; + int key_map[MAX_KEY]; + int abs_map[MAX_ABS]; + int dpad = 0; + int fd = -1; + + String devpath; + input_absinfo *abs_info[MAX_ABS] = {}; + + bool force_feedback = false; + int ff_effect_id = 0; + uint64_t ff_effect_timestamp = 0; + + ~Joypad(); + void reset(); + }; + +#ifdef UDEV_ENABLED + bool use_udev = false; +#endif + SafeFlag exit_monitor; + Mutex joy_mutex; + Thread joy_thread; + Input *input = nullptr; + Joypad joypads[JOYPADS_MAX]; + Vector<String> attached_devices; + + static void joy_thread_func(void *p_user); + + int get_joy_from_path(String p_path) const; + + void setup_joypad_properties(int p_id); + void close_joypad(int p_id = -1); +#ifdef UDEV_ENABLED + void enumerate_joypads(struct udev *p_udev); + void monitor_joypads(struct udev *p_udev); +#endif + void monitor_joypads(); + void run_joypad_thread(); + void open_joypad(const char *p_path); + + void joypad_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp); + void joypad_vibration_stop(int p_id, uint64_t p_timestamp); + + Input::JoyAxisValue axis_correct(const input_absinfo *p_abs, int p_value) const; +}; + +#endif +#endif // JOYPAD_LINUX_H diff --git a/platform/linuxbsd/key_mapping_x11.cpp b/platform/linuxbsd/key_mapping_x11.cpp new file mode 100644 index 0000000000..74257a7e61 --- /dev/null +++ b/platform/linuxbsd/key_mapping_x11.cpp @@ -0,0 +1,1943 @@ +/*************************************************************************/ +/* key_mapping_x11.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#include "key_mapping_x11.h" + +/***** SCAN CODE CONVERSION ******/ + +struct _XTranslatePair { + KeySym keysym; + unsigned int keycode; +}; + +static _XTranslatePair _xkeysym_to_keycode[] = { + // misc keys + + { XK_Escape, KEY_ESCAPE }, + { XK_Tab, KEY_TAB }, + { XK_ISO_Left_Tab, KEY_BACKTAB }, + { XK_BackSpace, KEY_BACKSPACE }, + { XK_Return, KEY_ENTER }, + { XK_Insert, KEY_INSERT }, + { XK_Delete, KEY_DELETE }, + { XK_Clear, KEY_DELETE }, + { XK_Pause, KEY_PAUSE }, + { XK_Print, KEY_PRINT }, + { XK_Home, KEY_HOME }, + { XK_End, KEY_END }, + { XK_Left, KEY_LEFT }, + { XK_Up, KEY_UP }, + { XK_Right, KEY_RIGHT }, + { XK_Down, KEY_DOWN }, + { XK_Prior, KEY_PAGEUP }, + { XK_Next, KEY_PAGEDOWN }, + { XK_Shift_L, KEY_SHIFT }, + { XK_Shift_R, KEY_SHIFT }, + { XK_Shift_Lock, KEY_SHIFT }, + { XK_Control_L, KEY_CTRL }, + { XK_Control_R, KEY_CTRL }, + { XK_Meta_L, KEY_META }, + { XK_Meta_R, KEY_META }, + { XK_Alt_L, KEY_ALT }, + { XK_Alt_R, KEY_ALT }, + { XK_Caps_Lock, KEY_CAPSLOCK }, + { XK_Num_Lock, KEY_NUMLOCK }, + { XK_Scroll_Lock, KEY_SCROLLLOCK }, + { XK_Super_L, KEY_SUPER_L }, + { XK_Super_R, KEY_SUPER_R }, + { XK_Menu, KEY_MENU }, + { XK_Hyper_L, KEY_HYPER_L }, + { XK_Hyper_R, KEY_HYPER_R }, + { XK_Help, KEY_HELP }, + { XK_KP_Space, KEY_SPACE }, + { XK_KP_Tab, KEY_TAB }, + { XK_KP_Enter, KEY_KP_ENTER }, + { XK_Home, KEY_HOME }, + { XK_Left, KEY_LEFT }, + { XK_Up, KEY_UP }, + { XK_Right, KEY_RIGHT }, + { XK_Down, KEY_DOWN }, + { XK_Prior, KEY_PAGEUP }, + { XK_Next, KEY_PAGEDOWN }, + { XK_End, KEY_END }, + { XK_Begin, KEY_CLEAR }, + { XK_Insert, KEY_INSERT }, + { XK_Delete, KEY_DELETE }, + //{ XK_KP_Equal, KEY_EQUAL }, + //{ XK_KP_Separator, KEY_COMMA }, + { XK_KP_Decimal, KEY_KP_PERIOD }, + { XK_KP_Delete, KEY_KP_PERIOD }, + { XK_KP_Multiply, KEY_KP_MULTIPLY }, + { XK_KP_Divide, KEY_KP_DIVIDE }, + { XK_KP_Subtract, KEY_KP_SUBTRACT }, + { XK_KP_Add, KEY_KP_ADD }, + { XK_KP_0, KEY_KP_0 }, + { XK_KP_1, KEY_KP_1 }, + { XK_KP_2, KEY_KP_2 }, + { XK_KP_3, KEY_KP_3 }, + { XK_KP_4, KEY_KP_4 }, + { XK_KP_5, KEY_KP_5 }, + { XK_KP_6, KEY_KP_6 }, + { XK_KP_7, KEY_KP_7 }, + { XK_KP_8, KEY_KP_8 }, + { XK_KP_9, KEY_KP_9 }, + // same but with numlock + { XK_KP_Insert, KEY_KP_0 }, + { XK_KP_End, KEY_KP_1 }, + { XK_KP_Down, KEY_KP_2 }, + { XK_KP_Page_Down, KEY_KP_3 }, + { XK_KP_Left, KEY_KP_4 }, + { XK_KP_Begin, KEY_KP_5 }, + { XK_KP_Right, KEY_KP_6 }, + { XK_KP_Home, KEY_KP_7 }, + { XK_KP_Up, KEY_KP_8 }, + { XK_KP_Page_Up, KEY_KP_9 }, + { XK_F1, KEY_F1 }, + { XK_F2, KEY_F2 }, + { XK_F3, KEY_F3 }, + { XK_F4, KEY_F4 }, + { XK_F5, KEY_F5 }, + { XK_F6, KEY_F6 }, + { XK_F7, KEY_F7 }, + { XK_F8, KEY_F8 }, + { XK_F9, KEY_F9 }, + { XK_F10, KEY_F10 }, + { XK_F11, KEY_F11 }, + { XK_F12, KEY_F12 }, + { XK_F13, KEY_F13 }, + { XK_F14, KEY_F14 }, + { XK_F15, KEY_F15 }, + { XK_F16, KEY_F16 }, + + // media keys + { XF86XK_Back, KEY_BACK }, + { XF86XK_Forward, KEY_FORWARD }, + { XF86XK_Stop, KEY_STOP }, + { XF86XK_Refresh, KEY_REFRESH }, + { XF86XK_Favorites, KEY_FAVORITES }, + { XF86XK_AudioMedia, KEY_LAUNCHMEDIA }, + { XF86XK_OpenURL, KEY_OPENURL }, + { XF86XK_HomePage, KEY_HOMEPAGE }, + { XF86XK_Search, KEY_SEARCH }, + { XF86XK_AudioLowerVolume, KEY_VOLUMEDOWN }, + { XF86XK_AudioMute, KEY_VOLUMEMUTE }, + { XF86XK_AudioRaiseVolume, KEY_VOLUMEUP }, + { XF86XK_AudioPlay, KEY_MEDIAPLAY }, + { XF86XK_AudioStop, KEY_MEDIASTOP }, + { XF86XK_AudioPrev, KEY_MEDIAPREVIOUS }, + { XF86XK_AudioNext, KEY_MEDIANEXT }, + { XF86XK_AudioRecord, KEY_MEDIARECORD }, + + // launch keys + { XF86XK_Mail, KEY_LAUNCHMAIL }, + { XF86XK_MyComputer, KEY_LAUNCH0 }, + { XF86XK_Calculator, KEY_LAUNCH1 }, + { XF86XK_Standby, KEY_STANDBY }, + + { XF86XK_Launch0, KEY_LAUNCH2 }, + { XF86XK_Launch1, KEY_LAUNCH3 }, + { XF86XK_Launch2, KEY_LAUNCH4 }, + { XF86XK_Launch3, KEY_LAUNCH5 }, + { XF86XK_Launch4, KEY_LAUNCH6 }, + { XF86XK_Launch5, KEY_LAUNCH7 }, + { XF86XK_Launch6, KEY_LAUNCH8 }, + { XF86XK_Launch7, KEY_LAUNCH9 }, + { XF86XK_Launch8, KEY_LAUNCHA }, + { XF86XK_Launch9, KEY_LAUNCHB }, + { XF86XK_LaunchA, KEY_LAUNCHC }, + { XF86XK_LaunchB, KEY_LAUNCHD }, + { XF86XK_LaunchC, KEY_LAUNCHE }, + { XF86XK_LaunchD, KEY_LAUNCHF }, + + { 0, 0 } +}; + +struct _TranslatePair { + unsigned int keysym; + unsigned int keycode; +}; + +static _TranslatePair _scancode_to_keycode[] = { + { KEY_ESCAPE, 0x09 }, + { KEY_1, 0x0A }, + { KEY_2, 0x0B }, + { KEY_3, 0x0C }, + { KEY_4, 0x0D }, + { KEY_5, 0x0E }, + { KEY_6, 0x0F }, + { KEY_7, 0x10 }, + { KEY_8, 0x11 }, + { KEY_9, 0x12 }, + { KEY_0, 0x13 }, + { KEY_MINUS, 0x14 }, + { KEY_EQUAL, 0x15 }, + { KEY_BACKSPACE, 0x16 }, + { KEY_TAB, 0x17 }, + { KEY_Q, 0x18 }, + { KEY_W, 0x19 }, + { KEY_E, 0x1A }, + { KEY_R, 0x1B }, + { KEY_T, 0x1C }, + { KEY_Y, 0x1D }, + { KEY_U, 0x1E }, + { KEY_I, 0x1F }, + { KEY_O, 0x20 }, + { KEY_P, 0x21 }, + { KEY_BRACELEFT, 0x22 }, + { KEY_BRACERIGHT, 0x23 }, + { KEY_ENTER, 0x24 }, + { KEY_CTRL, 0x25 }, + { KEY_A, 0x26 }, + { KEY_S, 0x27 }, + { KEY_D, 0x28 }, + { KEY_F, 0x29 }, + { KEY_G, 0x2A }, + { KEY_H, 0x2B }, + { KEY_J, 0x2C }, + { KEY_K, 0x2D }, + { KEY_L, 0x2E }, + { KEY_SEMICOLON, 0x2F }, + { KEY_APOSTROPHE, 0x30 }, + { KEY_QUOTELEFT, 0x31 }, + { KEY_SHIFT, 0x32 }, + { KEY_BACKSLASH, 0x33 }, + { KEY_Z, 0x34 }, + { KEY_X, 0x35 }, + { KEY_C, 0x36 }, + { KEY_V, 0x37 }, + { KEY_B, 0x38 }, + { KEY_N, 0x39 }, + { KEY_M, 0x3A }, + { KEY_COMMA, 0x3B }, + { KEY_PERIOD, 0x3C }, + { KEY_SLASH, 0x3D }, + { KEY_SHIFT, 0x3E }, + { KEY_KP_MULTIPLY, 0x3F }, + { KEY_ALT, 0x40 }, + { KEY_SPACE, 0x41 }, + { KEY_CAPSLOCK, 0x42 }, + { KEY_F1, 0x43 }, + { KEY_F2, 0x44 }, + { KEY_F3, 0x45 }, + { KEY_F4, 0x46 }, + { KEY_F5, 0x47 }, + { KEY_F6, 0x48 }, + { KEY_F7, 0x49 }, + { KEY_F8, 0x4A }, + { KEY_F9, 0x4B }, + { KEY_F10, 0x4C }, + { KEY_NUMLOCK, 0x4D }, + { KEY_SCROLLLOCK, 0x4E }, + { KEY_KP_7, 0x4F }, + { KEY_KP_8, 0x50 }, + { KEY_KP_9, 0x51 }, + { KEY_KP_SUBTRACT, 0x52 }, + { KEY_KP_4, 0x53 }, + { KEY_KP_5, 0x54 }, + { KEY_KP_6, 0x55 }, + { KEY_KP_ADD, 0x56 }, + { KEY_KP_1, 0x57 }, + { KEY_KP_2, 0x58 }, + { KEY_KP_3, 0x59 }, + { KEY_KP_0, 0x5A }, + { KEY_KP_PERIOD, 0x5B }, + //{ KEY_???, 0x5E }, //NON US BACKSLASH + { KEY_F11, 0x5F }, + { KEY_F12, 0x60 }, + { KEY_KP_ENTER, 0x68 }, + { KEY_CTRL, 0x69 }, + { KEY_KP_DIVIDE, 0x6A }, + { KEY_PRINT, 0x6B }, + { KEY_ALT, 0x6C }, + { KEY_ENTER, 0x6D }, + { KEY_HOME, 0x6E }, + { KEY_UP, 0x6F }, + { KEY_PAGEUP, 0x70 }, + { KEY_LEFT, 0x71 }, + { KEY_RIGHT, 0x72 }, + { KEY_END, 0x73 }, + { KEY_DOWN, 0x74 }, + { KEY_PAGEDOWN, 0x75 }, + { KEY_INSERT, 0x76 }, + { KEY_DELETE, 0x77 }, + { KEY_VOLUMEMUTE, 0x79 }, + { KEY_VOLUMEDOWN, 0x7A }, + { KEY_VOLUMEUP, 0x7B }, + { KEY_PAUSE, 0x7F }, + { KEY_SUPER_L, 0x85 }, + { KEY_SUPER_R, 0x86 }, + { KEY_MENU, 0x87 }, + { KEY_UNKNOWN, 0 } +}; + +unsigned int KeyMappingX11::get_scancode(unsigned int p_code) { + unsigned int keycode = KEY_UNKNOWN; + for (int i = 0; _scancode_to_keycode[i].keysym != KEY_UNKNOWN; i++) { + if (_scancode_to_keycode[i].keycode == p_code) { + keycode = _scancode_to_keycode[i].keysym; + break; + } + } + + return keycode; +} + +unsigned int KeyMappingX11::get_keycode(KeySym p_keysym) { + // kinda bruteforce.. could optimize. + + if (p_keysym < 0x100) { // Latin 1, maps 1-1 + return p_keysym; + } + + // look for special key + for (int idx = 0; _xkeysym_to_keycode[idx].keysym != 0; idx++) { + if (_xkeysym_to_keycode[idx].keysym == p_keysym) { + return _xkeysym_to_keycode[idx].keycode; + } + } + + return 0; +} + +KeySym KeyMappingX11::get_keysym(unsigned int p_code) { + // kinda bruteforce.. could optimize. + + if (p_code < 0x100) { // Latin 1, maps 1-1 + return p_code; + } + + // look for special key + for (int idx = 0; _xkeysym_to_keycode[idx].keysym != 0; idx++) { + if (_xkeysym_to_keycode[idx].keycode == p_code) { + return _xkeysym_to_keycode[idx].keysym; + } + } + + return 0; +} + +/***** UNICODE CONVERSION ******/ + +// Tables taken from FOX toolkit + +struct _XTranslateUnicodePair { + KeySym keysym; + unsigned int unicode; +}; + +enum { + _KEYSYM_MAX = 759 +}; + +static _XTranslateUnicodePair _xkeysym_to_unicode[_KEYSYM_MAX] = { + { 0x01A1, 0x0104 }, + { 0x01A2, 0x02D8 }, + { 0x01A3, 0x0141 }, + { 0x01A5, 0x013D }, + { 0x01A6, 0x015A }, + { 0x01A9, 0x0160 }, + { 0x01AA, 0x015E }, + { 0x01AB, 0x0164 }, + { 0x01AC, 0x0179 }, + { 0x01AE, 0x017D }, + { 0x01AF, 0x017B }, + { 0x01B1, 0x0105 }, + { 0x01B2, 0x02DB }, + { 0x01B3, 0x0142 }, + { 0x01B5, 0x013E }, + { 0x01B6, 0x015B }, + { 0x01B7, 0x02C7 }, + { 0x01B9, 0x0161 }, + { 0x01BA, 0x015F }, + { 0x01BB, 0x0165 }, + { 0x01BC, 0x017A }, + { 0x01BD, 0x02DD }, + { 0x01BE, 0x017E }, + { 0x01BF, 0x017C }, + { 0x01C0, 0x0154 }, + { 0x01C3, 0x0102 }, + { 0x01C5, 0x0139 }, + { 0x01C6, 0x0106 }, + { 0x01C8, 0x010C }, + { 0x01CA, 0x0118 }, + { 0x01CC, 0x011A }, + { 0x01CF, 0x010E }, + { 0x01D0, 0x0110 }, + { 0x01D1, 0x0143 }, + { 0x01D2, 0x0147 }, + { 0x01D5, 0x0150 }, + { 0x01D8, 0x0158 }, + { 0x01D9, 0x016E }, + { 0x01DB, 0x0170 }, + { 0x01DE, 0x0162 }, + { 0x01E0, 0x0155 }, + { 0x01E3, 0x0103 }, + { 0x01E5, 0x013A }, + { 0x01E6, 0x0107 }, + { 0x01E8, 0x010D }, + { 0x01EA, 0x0119 }, + { 0x01EC, 0x011B }, + { 0x01EF, 0x010F }, + { 0x01F0, 0x0111 }, + { 0x01F1, 0x0144 }, + { 0x01F2, 0x0148 }, + { 0x01F5, 0x0151 }, + { 0x01F8, 0x0159 }, + { 0x01F9, 0x016F }, + { 0x01FB, 0x0171 }, + { 0x01FE, 0x0163 }, + { 0x01FF, 0x02D9 }, + { 0x02A1, 0x0126 }, + { 0x02A6, 0x0124 }, + { 0x02A9, 0x0130 }, + { 0x02AB, 0x011E }, + { 0x02AC, 0x0134 }, + { 0x02B1, 0x0127 }, + { 0x02B6, 0x0125 }, + { 0x02B9, 0x0131 }, + { 0x02BB, 0x011F }, + { 0x02BC, 0x0135 }, + { 0x02C5, 0x010A }, + { 0x02C6, 0x0108 }, + { 0x02D5, 0x0120 }, + { 0x02D8, 0x011C }, + { 0x02DD, 0x016C }, + { 0x02DE, 0x015C }, + { 0x02E5, 0x010B }, + { 0x02E6, 0x0109 }, + { 0x02F5, 0x0121 }, + { 0x02F8, 0x011D }, + { 0x02FD, 0x016D }, + { 0x02FE, 0x015D }, + { 0x03A2, 0x0138 }, + { 0x03A3, 0x0156 }, + { 0x03A5, 0x0128 }, + { 0x03A6, 0x013B }, + { 0x03AA, 0x0112 }, + { 0x03AB, 0x0122 }, + { 0x03AC, 0x0166 }, + { 0x03B3, 0x0157 }, + { 0x03B5, 0x0129 }, + { 0x03B6, 0x013C }, + { 0x03BA, 0x0113 }, + { 0x03BB, 0x0123 }, + { 0x03BC, 0x0167 }, + { 0x03BD, 0x014A }, + { 0x03BF, 0x014B }, + { 0x03C0, 0x0100 }, + { 0x03C7, 0x012E }, + { 0x03CC, 0x0116 }, + { 0x03CF, 0x012A }, + { 0x03D1, 0x0145 }, + { 0x03D2, 0x014C }, + { 0x03D3, 0x0136 }, + { 0x03D9, 0x0172 }, + { 0x03DD, 0x0168 }, + { 0x03DE, 0x016A }, + { 0x03E0, 0x0101 }, + { 0x03E7, 0x012F }, + { 0x03EC, 0x0117 }, + { 0x03EF, 0x012B }, + { 0x03F1, 0x0146 }, + { 0x03F2, 0x014D }, + { 0x03F3, 0x0137 }, + { 0x03F9, 0x0173 }, + { 0x03FD, 0x0169 }, + { 0x03FE, 0x016B }, + { 0x047E, 0x203E }, + { 0x04A1, 0x3002 }, + { 0x04A2, 0x300C }, + { 0x04A3, 0x300D }, + { 0x04A4, 0x3001 }, + { 0x04A5, 0x30FB }, + { 0x04A6, 0x30F2 }, + { 0x04A7, 0x30A1 }, + { 0x04A8, 0x30A3 }, + { 0x04A9, 0x30A5 }, + { 0x04AA, 0x30A7 }, + { 0x04AB, 0x30A9 }, + { 0x04AC, 0x30E3 }, + { 0x04AD, 0x30E5 }, + { 0x04AE, 0x30E7 }, + { 0x04AF, 0x30C3 }, + { 0x04B0, 0x30FC }, + { 0x04B1, 0x30A2 }, + { 0x04B2, 0x30A4 }, + { 0x04B3, 0x30A6 }, + { 0x04B4, 0x30A8 }, + { 0x04B5, 0x30AA }, + { 0x04B6, 0x30AB }, + { 0x04B7, 0x30AD }, + { 0x04B8, 0x30AF }, + { 0x04B9, 0x30B1 }, + { 0x04BA, 0x30B3 }, + { 0x04BB, 0x30B5 }, + { 0x04BC, 0x30B7 }, + { 0x04BD, 0x30B9 }, + { 0x04BE, 0x30BB }, + { 0x04BF, 0x30BD }, + { 0x04C0, 0x30BF }, + { 0x04C1, 0x30C1 }, + { 0x04C2, 0x30C4 }, + { 0x04C3, 0x30C6 }, + { 0x04C4, 0x30C8 }, + { 0x04C5, 0x30CA }, + { 0x04C6, 0x30CB }, + { 0x04C7, 0x30CC }, + { 0x04C8, 0x30CD }, + { 0x04C9, 0x30CE }, + { 0x04CA, 0x30CF }, + { 0x04CB, 0x30D2 }, + { 0x04CC, 0x30D5 }, + { 0x04CD, 0x30D8 }, + { 0x04CE, 0x30DB }, + { 0x04CF, 0x30DE }, + { 0x04D0, 0x30DF }, + { 0x04D1, 0x30E0 }, + { 0x04D2, 0x30E1 }, + { 0x04D3, 0x30E2 }, + { 0x04D4, 0x30E4 }, + { 0x04D5, 0x30E6 }, + { 0x04D6, 0x30E8 }, + { 0x04D7, 0x30E9 }, + { 0x04D8, 0x30EA }, + { 0x04D9, 0x30EB }, + { 0x04DA, 0x30EC }, + { 0x04DB, 0x30ED }, + { 0x04DC, 0x30EF }, + { 0x04DD, 0x30F3 }, + { 0x04DE, 0x309B }, + { 0x04DF, 0x309C }, + { 0x05AC, 0x060C }, + { 0x05BB, 0x061B }, + { 0x05BF, 0x061F }, + { 0x05C1, 0x0621 }, + { 0x05C2, 0x0622 }, + { 0x05C3, 0x0623 }, + { 0x05C4, 0x0624 }, + { 0x05C5, 0x0625 }, + { 0x05C6, 0x0626 }, + { 0x05C7, 0x0627 }, + { 0x05C8, 0x0628 }, + { 0x05C9, 0x0629 }, + { 0x05CA, 0x062A }, + { 0x05CB, 0x062B }, + { 0x05CC, 0x062C }, + { 0x05CD, 0x062D }, + { 0x05CE, 0x062E }, + { 0x05CF, 0x062F }, + { 0x05D0, 0x0630 }, + { 0x05D1, 0x0631 }, + { 0x05D2, 0x0632 }, + { 0x05D3, 0x0633 }, + { 0x05D4, 0x0634 }, + { 0x05D5, 0x0635 }, + { 0x05D6, 0x0636 }, + { 0x05D7, 0x0637 }, + { 0x05D8, 0x0638 }, + { 0x05D9, 0x0639 }, + { 0x05DA, 0x063A }, + { 0x05E0, 0x0640 }, + { 0x05E1, 0x0641 }, + { 0x05E2, 0x0642 }, + { 0x05E3, 0x0643 }, + { 0x05E4, 0x0644 }, + { 0x05E5, 0x0645 }, + { 0x05E6, 0x0646 }, + { 0x05E7, 0x0647 }, + { 0x05E8, 0x0648 }, + { 0x05E9, 0x0649 }, + { 0x05EA, 0x064A }, + { 0x05EB, 0x064B }, + { 0x05EC, 0x064C }, + { 0x05ED, 0x064D }, + { 0x05EE, 0x064E }, + { 0x05EF, 0x064F }, + { 0x05F0, 0x0650 }, + { 0x05F1, 0x0651 }, + { 0x05F2, 0x0652 }, + { 0x06A1, 0x0452 }, + { 0x06A2, 0x0453 }, + { 0x06A3, 0x0451 }, + { 0x06A4, 0x0454 }, + { 0x06A5, 0x0455 }, + { 0x06A6, 0x0456 }, + { 0x06A7, 0x0457 }, + { 0x06A8, 0x0458 }, + { 0x06A9, 0x0459 }, + { 0x06AA, 0x045A }, + { 0x06AB, 0x045B }, + { 0x06AC, 0x045C }, + { 0x06AE, 0x045E }, + { 0x06AF, 0x045F }, + { 0x06B0, 0x2116 }, + { 0x06B1, 0x0402 }, + { 0x06B2, 0x0403 }, + { 0x06B3, 0x0401 }, + { 0x06B4, 0x0404 }, + { 0x06B5, 0x0405 }, + { 0x06B6, 0x0406 }, + { 0x06B7, 0x0407 }, + { 0x06B8, 0x0408 }, + { 0x06B9, 0x0409 }, + { 0x06BA, 0x040A }, + { 0x06BB, 0x040B }, + { 0x06BC, 0x040C }, + { 0x06BE, 0x040E }, + { 0x06BF, 0x040F }, + { 0x06C0, 0x044E }, + { 0x06C1, 0x0430 }, + { 0x06C2, 0x0431 }, + { 0x06C3, 0x0446 }, + { 0x06C4, 0x0434 }, + { 0x06C5, 0x0435 }, + { 0x06C6, 0x0444 }, + { 0x06C7, 0x0433 }, + { 0x06C8, 0x0445 }, + { 0x06C9, 0x0438 }, + { 0x06CA, 0x0439 }, + { 0x06CB, 0x043A }, + { 0x06CC, 0x043B }, + { 0x06CD, 0x043C }, + { 0x06CE, 0x043D }, + { 0x06CF, 0x043E }, + { 0x06D0, 0x043F }, + { 0x06D1, 0x044F }, + { 0x06D2, 0x0440 }, + { 0x06D3, 0x0441 }, + { 0x06D4, 0x0442 }, + { 0x06D5, 0x0443 }, + { 0x06D6, 0x0436 }, + { 0x06D7, 0x0432 }, + { 0x06D8, 0x044C }, + { 0x06D9, 0x044B }, + { 0x06DA, 0x0437 }, + { 0x06DB, 0x0448 }, + { 0x06DC, 0x044D }, + { 0x06DD, 0x0449 }, + { 0x06DE, 0x0447 }, + { 0x06DF, 0x044A }, + { 0x06E0, 0x042E }, + { 0x06E1, 0x0410 }, + { 0x06E2, 0x0411 }, + { 0x06E3, 0x0426 }, + { 0x06E4, 0x0414 }, + { 0x06E5, 0x0415 }, + { 0x06E6, 0x0424 }, + { 0x06E7, 0x0413 }, + { 0x06E8, 0x0425 }, + { 0x06E9, 0x0418 }, + { 0x06EA, 0x0419 }, + { 0x06EB, 0x041A }, + { 0x06EC, 0x041B }, + { 0x06ED, 0x041C }, + { 0x06EE, 0x041D }, + { 0x06EF, 0x041E }, + { 0x06F0, 0x041F }, + { 0x06F1, 0x042F }, + { 0x06F2, 0x0420 }, + { 0x06F3, 0x0421 }, + { 0x06F4, 0x0422 }, + { 0x06F5, 0x0423 }, + { 0x06F6, 0x0416 }, + { 0x06F7, 0x0412 }, + { 0x06F8, 0x042C }, + { 0x06F9, 0x042B }, + { 0x06FA, 0x0417 }, + { 0x06FB, 0x0428 }, + { 0x06FC, 0x042D }, + { 0x06FD, 0x0429 }, + { 0x06FE, 0x0427 }, + { 0x06FF, 0x042A }, + { 0x07A1, 0x0386 }, + { 0x07A2, 0x0388 }, + { 0x07A3, 0x0389 }, + { 0x07A4, 0x038A }, + { 0x07A5, 0x03AA }, + { 0x07A7, 0x038C }, + { 0x07A8, 0x038E }, + { 0x07A9, 0x03AB }, + { 0x07AB, 0x038F }, + { 0x07AE, 0x0385 }, + { 0x07AF, 0x2015 }, + { 0x07B1, 0x03AC }, + { 0x07B2, 0x03AD }, + { 0x07B3, 0x03AE }, + { 0x07B4, 0x03AF }, + { 0x07B5, 0x03CA }, + { 0x07B6, 0x0390 }, + { 0x07B7, 0x03CC }, + { 0x07B8, 0x03CD }, + { 0x07B9, 0x03CB }, + { 0x07BA, 0x03B0 }, + { 0x07BB, 0x03CE }, + { 0x07C1, 0x0391 }, + { 0x07C2, 0x0392 }, + { 0x07C3, 0x0393 }, + { 0x07C4, 0x0394 }, + { 0x07C5, 0x0395 }, + { 0x07C6, 0x0396 }, + { 0x07C7, 0x0397 }, + { 0x07C8, 0x0398 }, + { 0x07C9, 0x0399 }, + { 0x07CA, 0x039A }, + { 0x07CB, 0x039B }, + { 0x07CC, 0x039C }, + { 0x07CD, 0x039D }, + { 0x07CE, 0x039E }, + { 0x07CF, 0x039F }, + { 0x07D0, 0x03A0 }, + { 0x07D1, 0x03A1 }, + { 0x07D2, 0x03A3 }, + { 0x07D4, 0x03A4 }, + { 0x07D5, 0x03A5 }, + { 0x07D6, 0x03A6 }, + { 0x07D7, 0x03A7 }, + { 0x07D8, 0x03A8 }, + { 0x07D9, 0x03A9 }, + { 0x07E1, 0x03B1 }, + { 0x07E2, 0x03B2 }, + { 0x07E3, 0x03B3 }, + { 0x07E4, 0x03B4 }, + { 0x07E5, 0x03B5 }, + { 0x07E6, 0x03B6 }, + { 0x07E7, 0x03B7 }, + { 0x07E8, 0x03B8 }, + { 0x07E9, 0x03B9 }, + { 0x07EA, 0x03BA }, + { 0x07EB, 0x03BB }, + { 0x07EC, 0x03BC }, + { 0x07ED, 0x03BD }, + { 0x07EE, 0x03BE }, + { 0x07EF, 0x03BF }, + { 0x07F0, 0x03C0 }, + { 0x07F1, 0x03C1 }, + { 0x07F2, 0x03C3 }, + { 0x07F3, 0x03C2 }, + { 0x07F4, 0x03C4 }, + { 0x07F5, 0x03C5 }, + { 0x07F6, 0x03C6 }, + { 0x07F7, 0x03C7 }, + { 0x07F8, 0x03C8 }, + { 0x07F9, 0x03C9 }, + { 0x08A1, 0x23B7 }, + { 0x08A2, 0x250C }, + { 0x08A3, 0x2500 }, + { 0x08A4, 0x2320 }, + { 0x08A5, 0x2321 }, + { 0x08A6, 0x2502 }, + { 0x08A7, 0x23A1 }, + { 0x08A8, 0x23A3 }, + { 0x08A9, 0x23A4 }, + { 0x08AA, 0x23A6 }, + { 0x08AB, 0x239B }, + { 0x08AC, 0x239D }, + { 0x08AD, 0x239E }, + { 0x08AE, 0x23A0 }, + { 0x08AF, 0x23A8 }, + { 0x08B0, 0x23AC }, + { 0x08BC, 0x2264 }, + { 0x08BD, 0x2260 }, + { 0x08BE, 0x2265 }, + { 0x08BF, 0x222B }, + { 0x08C0, 0x2234 }, + { 0x08C1, 0x221D }, + { 0x08C2, 0x221E }, + { 0x08C5, 0x2207 }, + { 0x08C8, 0x223C }, + { 0x08C9, 0x2243 }, + { 0x08CD, 0x21D4 }, + { 0x08CE, 0x21D2 }, + { 0x08CF, 0x2261 }, + { 0x08D6, 0x221A }, + { 0x08DA, 0x2282 }, + { 0x08DB, 0x2283 }, + { 0x08DC, 0x2229 }, + { 0x08DD, 0x222A }, + { 0x08DE, 0x2227 }, + { 0x08DF, 0x2228 }, + { 0x08EF, 0x2202 }, + { 0x08F6, 0x0192 }, + { 0x08FB, 0x2190 }, + { 0x08FC, 0x2191 }, + { 0x08FD, 0x2192 }, + { 0x08FE, 0x2193 }, + { 0x09E0, 0x25C6 }, + { 0x09E1, 0x2592 }, + { 0x09E2, 0x2409 }, + { 0x09E3, 0x240C }, + { 0x09E4, 0x240D }, + { 0x09E5, 0x240A }, + { 0x09E8, 0x2424 }, + { 0x09E9, 0x240B }, + { 0x09EA, 0x2518 }, + { 0x09EB, 0x2510 }, + { 0x09EC, 0x250C }, + { 0x09ED, 0x2514 }, + { 0x09EE, 0x253C }, + { 0x09EF, 0x23BA }, + { 0x09F0, 0x23BB }, + { 0x09F1, 0x2500 }, + { 0x09F2, 0x23BC }, + { 0x09F3, 0x23BD }, + { 0x09F4, 0x251C }, + { 0x09F5, 0x2524 }, + { 0x09F6, 0x2534 }, + { 0x09F7, 0x252C }, + { 0x09F8, 0x2502 }, + { 0x0AA1, 0x2003 }, + { 0x0AA2, 0x2002 }, + { 0x0AA3, 0x2004 }, + { 0x0AA4, 0x2005 }, + { 0x0AA5, 0x2007 }, + { 0x0AA6, 0x2008 }, + { 0x0AA7, 0x2009 }, + { 0x0AA8, 0x200A }, + { 0x0AA9, 0x2014 }, + { 0x0AAA, 0x2013 }, + { 0x0AAE, 0x2026 }, + { 0x0AAF, 0x2025 }, + { 0x0AB0, 0x2153 }, + { 0x0AB1, 0x2154 }, + { 0x0AB2, 0x2155 }, + { 0x0AB3, 0x2156 }, + { 0x0AB4, 0x2157 }, + { 0x0AB5, 0x2158 }, + { 0x0AB6, 0x2159 }, + { 0x0AB7, 0x215A }, + { 0x0AB8, 0x2105 }, + { 0x0ABB, 0x2012 }, + { 0x0ABC, 0x2329 }, + { 0x0ABE, 0x232A }, + { 0x0AC3, 0x215B }, + { 0x0AC4, 0x215C }, + { 0x0AC5, 0x215D }, + { 0x0AC6, 0x215E }, + { 0x0AC9, 0x2122 }, + { 0x0ACA, 0x2613 }, + { 0x0ACC, 0x25C1 }, + { 0x0ACD, 0x25B7 }, + { 0x0ACE, 0x25CB }, + { 0x0ACF, 0x25AF }, + { 0x0AD0, 0x2018 }, + { 0x0AD1, 0x2019 }, + { 0x0AD2, 0x201C }, + { 0x0AD3, 0x201D }, + { 0x0AD4, 0x211E }, + { 0x0AD6, 0x2032 }, + { 0x0AD7, 0x2033 }, + { 0x0AD9, 0x271D }, + { 0x0ADB, 0x25AC }, + { 0x0ADC, 0x25C0 }, + { 0x0ADD, 0x25B6 }, + { 0x0ADE, 0x25CF }, + { 0x0ADF, 0x25AE }, + { 0x0AE0, 0x25E6 }, + { 0x0AE1, 0x25AB }, + { 0x0AE2, 0x25AD }, + { 0x0AE3, 0x25B3 }, + { 0x0AE4, 0x25BD }, + { 0x0AE5, 0x2606 }, + { 0x0AE6, 0x2022 }, + { 0x0AE7, 0x25AA }, + { 0x0AE8, 0x25B2 }, + { 0x0AE9, 0x25BC }, + { 0x0AEA, 0x261C }, + { 0x0AEB, 0x261E }, + { 0x0AEC, 0x2663 }, + { 0x0AED, 0x2666 }, + { 0x0AEE, 0x2665 }, + { 0x0AF0, 0x2720 }, + { 0x0AF1, 0x2020 }, + { 0x0AF2, 0x2021 }, + { 0x0AF3, 0x2713 }, + { 0x0AF4, 0x2717 }, + { 0x0AF5, 0x266F }, + { 0x0AF6, 0x266D }, + { 0x0AF7, 0x2642 }, + { 0x0AF8, 0x2640 }, + { 0x0AF9, 0x260E }, + { 0x0AFA, 0x2315 }, + { 0x0AFB, 0x2117 }, + { 0x0AFC, 0x2038 }, + { 0x0AFD, 0x201A }, + { 0x0AFE, 0x201E }, + { 0x0BA3, 0x003C }, + { 0x0BA6, 0x003E }, + { 0x0BA8, 0x2228 }, + { 0x0BA9, 0x2227 }, + { 0x0BC0, 0x00AF }, + { 0x0BC2, 0x22A5 }, + { 0x0BC3, 0x2229 }, + { 0x0BC4, 0x230A }, + { 0x0BC6, 0x005F }, + { 0x0BCA, 0x2218 }, + { 0x0BCC, 0x2395 }, + { 0x0BCE, 0x22A4 }, + { 0x0BCF, 0x25CB }, + { 0x0BD3, 0x2308 }, + { 0x0BD6, 0x222A }, + { 0x0BD8, 0x2283 }, + { 0x0BDA, 0x2282 }, + { 0x0BDC, 0x22A2 }, + { 0x0BFC, 0x22A3 }, + { 0x0CDF, 0x2017 }, + { 0x0CE0, 0x05D0 }, + { 0x0CE1, 0x05D1 }, + { 0x0CE2, 0x05D2 }, + { 0x0CE3, 0x05D3 }, + { 0x0CE4, 0x05D4 }, + { 0x0CE5, 0x05D5 }, + { 0x0CE6, 0x05D6 }, + { 0x0CE7, 0x05D7 }, + { 0x0CE8, 0x05D8 }, + { 0x0CE9, 0x05D9 }, + { 0x0CEA, 0x05DA }, + { 0x0CEB, 0x05DB }, + { 0x0CEC, 0x05DC }, + { 0x0CED, 0x05DD }, + { 0x0CEE, 0x05DE }, + { 0x0CEF, 0x05DF }, + { 0x0CF0, 0x05E0 }, + { 0x0CF1, 0x05E1 }, + { 0x0CF2, 0x05E2 }, + { 0x0CF3, 0x05E3 }, + { 0x0CF4, 0x05E4 }, + { 0x0CF5, 0x05E5 }, + { 0x0CF6, 0x05E6 }, + { 0x0CF7, 0x05E7 }, + { 0x0CF8, 0x05E8 }, + { 0x0CF9, 0x05E9 }, + { 0x0CFA, 0x05EA }, + { 0x0DA1, 0x0E01 }, + { 0x0DA2, 0x0E02 }, + { 0x0DA3, 0x0E03 }, + { 0x0DA4, 0x0E04 }, + { 0x0DA5, 0x0E05 }, + { 0x0DA6, 0x0E06 }, + { 0x0DA7, 0x0E07 }, + { 0x0DA8, 0x0E08 }, + { 0x0DA9, 0x0E09 }, + { 0x0DAA, 0x0E0A }, + { 0x0DAB, 0x0E0B }, + { 0x0DAC, 0x0E0C }, + { 0x0DAD, 0x0E0D }, + { 0x0DAE, 0x0E0E }, + { 0x0DAF, 0x0E0F }, + { 0x0DB0, 0x0E10 }, + { 0x0DB1, 0x0E11 }, + { 0x0DB2, 0x0E12 }, + { 0x0DB3, 0x0E13 }, + { 0x0DB4, 0x0E14 }, + { 0x0DB5, 0x0E15 }, + { 0x0DB6, 0x0E16 }, + { 0x0DB7, 0x0E17 }, + { 0x0DB8, 0x0E18 }, + { 0x0DB9, 0x0E19 }, + { 0x0DBA, 0x0E1A }, + { 0x0DBB, 0x0E1B }, + { 0x0DBC, 0x0E1C }, + { 0x0DBD, 0x0E1D }, + { 0x0DBE, 0x0E1E }, + { 0x0DBF, 0x0E1F }, + { 0x0DC0, 0x0E20 }, + { 0x0DC1, 0x0E21 }, + { 0x0DC2, 0x0E22 }, + { 0x0DC3, 0x0E23 }, + { 0x0DC4, 0x0E24 }, + { 0x0DC5, 0x0E25 }, + { 0x0DC6, 0x0E26 }, + { 0x0DC7, 0x0E27 }, + { 0x0DC8, 0x0E28 }, + { 0x0DC9, 0x0E29 }, + { 0x0DCA, 0x0E2A }, + { 0x0DCB, 0x0E2B }, + { 0x0DCC, 0x0E2C }, + { 0x0DCD, 0x0E2D }, + { 0x0DCE, 0x0E2E }, + { 0x0DCF, 0x0E2F }, + { 0x0DD0, 0x0E30 }, + { 0x0DD1, 0x0E31 }, + { 0x0DD2, 0x0E32 }, + { 0x0DD3, 0x0E33 }, + { 0x0DD4, 0x0E34 }, + { 0x0DD5, 0x0E35 }, + { 0x0DD6, 0x0E36 }, + { 0x0DD7, 0x0E37 }, + { 0x0DD8, 0x0E38 }, + { 0x0DD9, 0x0E39 }, + { 0x0DDA, 0x0E3A }, + { 0x0DDF, 0x0E3F }, + { 0x0DE0, 0x0E40 }, + { 0x0DE1, 0x0E41 }, + { 0x0DE2, 0x0E42 }, + { 0x0DE3, 0x0E43 }, + { 0x0DE4, 0x0E44 }, + { 0x0DE5, 0x0E45 }, + { 0x0DE6, 0x0E46 }, + { 0x0DE7, 0x0E47 }, + { 0x0DE8, 0x0E48 }, + { 0x0DE9, 0x0E49 }, + { 0x0DEA, 0x0E4A }, + { 0x0DEB, 0x0E4B }, + { 0x0DEC, 0x0E4C }, + { 0x0DED, 0x0E4D }, + { 0x0DF0, 0x0E50 }, + { 0x0DF1, 0x0E51 }, + { 0x0DF2, 0x0E52 }, + { 0x0DF3, 0x0E53 }, + { 0x0DF4, 0x0E54 }, + { 0x0DF5, 0x0E55 }, + { 0x0DF6, 0x0E56 }, + { 0x0DF7, 0x0E57 }, + { 0x0DF8, 0x0E58 }, + { 0x0DF9, 0x0E59 }, + { 0x0EA1, 0x3131 }, + { 0x0EA2, 0x3132 }, + { 0x0EA3, 0x3133 }, + { 0x0EA4, 0x3134 }, + { 0x0EA5, 0x3135 }, + { 0x0EA6, 0x3136 }, + { 0x0EA7, 0x3137 }, + { 0x0EA8, 0x3138 }, + { 0x0EA9, 0x3139 }, + { 0x0EAA, 0x313A }, + { 0x0EAB, 0x313B }, + { 0x0EAC, 0x313C }, + { 0x0EAD, 0x313D }, + { 0x0EAE, 0x313E }, + { 0x0EAF, 0x313F }, + { 0x0EB0, 0x3140 }, + { 0x0EB1, 0x3141 }, + { 0x0EB2, 0x3142 }, + { 0x0EB3, 0x3143 }, + { 0x0EB4, 0x3144 }, + { 0x0EB5, 0x3145 }, + { 0x0EB6, 0x3146 }, + { 0x0EB7, 0x3147 }, + { 0x0EB8, 0x3148 }, + { 0x0EB9, 0x3149 }, + { 0x0EBA, 0x314A }, + { 0x0EBB, 0x314B }, + { 0x0EBC, 0x314C }, + { 0x0EBD, 0x314D }, + { 0x0EBE, 0x314E }, + { 0x0EBF, 0x314F }, + { 0x0EC0, 0x3150 }, + { 0x0EC1, 0x3151 }, + { 0x0EC2, 0x3152 }, + { 0x0EC3, 0x3153 }, + { 0x0EC4, 0x3154 }, + { 0x0EC5, 0x3155 }, + { 0x0EC6, 0x3156 }, + { 0x0EC7, 0x3157 }, + { 0x0EC8, 0x3158 }, + { 0x0EC9, 0x3159 }, + { 0x0ECA, 0x315A }, + { 0x0ECB, 0x315B }, + { 0x0ECC, 0x315C }, + { 0x0ECD, 0x315D }, + { 0x0ECE, 0x315E }, + { 0x0ECF, 0x315F }, + { 0x0ED0, 0x3160 }, + { 0x0ED1, 0x3161 }, + { 0x0ED2, 0x3162 }, + { 0x0ED3, 0x3163 }, + { 0x0ED4, 0x11A8 }, + { 0x0ED5, 0x11A9 }, + { 0x0ED6, 0x11AA }, + { 0x0ED7, 0x11AB }, + { 0x0ED8, 0x11AC }, + { 0x0ED9, 0x11AD }, + { 0x0EDA, 0x11AE }, + { 0x0EDB, 0x11AF }, + { 0x0EDC, 0x11B0 }, + { 0x0EDD, 0x11B1 }, + { 0x0EDE, 0x11B2 }, + { 0x0EDF, 0x11B3 }, + { 0x0EE0, 0x11B4 }, + { 0x0EE1, 0x11B5 }, + { 0x0EE2, 0x11B6 }, + { 0x0EE3, 0x11B7 }, + { 0x0EE4, 0x11B8 }, + { 0x0EE5, 0x11B9 }, + { 0x0EE6, 0x11BA }, + { 0x0EE7, 0x11BB }, + { 0x0EE8, 0x11BC }, + { 0x0EE9, 0x11BD }, + { 0x0EEA, 0x11BE }, + { 0x0EEB, 0x11BF }, + { 0x0EEC, 0x11C0 }, + { 0x0EED, 0x11C1 }, + { 0x0EEE, 0x11C2 }, + { 0x0EEF, 0x316D }, + { 0x0EF0, 0x3171 }, + { 0x0EF1, 0x3178 }, + { 0x0EF2, 0x317F }, + { 0x0EF3, 0x3181 }, + { 0x0EF4, 0x3184 }, + { 0x0EF5, 0x3186 }, + { 0x0EF6, 0x318D }, + { 0x0EF7, 0x318E }, + { 0x0EF8, 0x11EB }, + { 0x0EF9, 0x11F0 }, + { 0x0EFA, 0x11F9 }, + { 0x0EFF, 0x20A9 }, + { 0x13A4, 0x20AC }, + { 0x13BC, 0x0152 }, + { 0x13BD, 0x0153 }, + { 0x13BE, 0x0178 }, + { 0x20AC, 0x20AC }, +}; + +unsigned int KeyMappingX11::get_unicode_from_keysym(KeySym p_keysym) { + /* Latin-1 */ + if (p_keysym >= 0x20 && p_keysym <= 0x7e) { + return p_keysym; + } + if (p_keysym >= 0xa0 && p_keysym <= 0xff) { + return p_keysym; + } + // keypad to latin1 is easy + if (p_keysym >= 0xffaa && p_keysym <= 0xffb9) { + return p_keysym - 0xff80; + } + + /* Unicode (may be present)*/ + + if ((p_keysym & 0xff000000) == 0x01000000) { + return p_keysym & 0x00ffffff; + } + + int middle, low = 0, high = _KEYSYM_MAX - 1; + do { + middle = (high + low) / 2; + if (_xkeysym_to_unicode[middle].keysym == p_keysym) { + return _xkeysym_to_unicode[middle].unicode; + } + if (_xkeysym_to_unicode[middle].keysym <= p_keysym) { + low = middle + 1; + } else { + high = middle - 1; + } + } while (high >= low); + + return 0; +} + +struct _XTranslateUnicodePairReverse { + unsigned int unicode; + KeySym keysym; +}; + +enum { + _UNICODE_MAX = 750 +}; + +static _XTranslateUnicodePairReverse _unicode_to_xkeysym[_UNICODE_MAX] = { + { 0x0ABD, 0x002E }, + { 0x0BA3, 0x003C }, + { 0x0BA6, 0x003E }, + { 0x0BC6, 0x005F }, + { 0x0BC0, 0x00AF }, + { 0x03C0, 0x0100 }, + { 0x03E0, 0x0101 }, + { 0x01C3, 0x0102 }, + { 0x01E3, 0x0103 }, + { 0x01A1, 0x0104 }, + { 0x01B1, 0x0105 }, + { 0x01C6, 0x0106 }, + { 0x01E6, 0x0107 }, + { 0x02C6, 0x0108 }, + { 0x02E6, 0x0109 }, + { 0x02C5, 0x010A }, + { 0x02E5, 0x010B }, + { 0x01C8, 0x010C }, + { 0x01E8, 0x010D }, + { 0x01CF, 0x010E }, + { 0x01EF, 0x010F }, + { 0x01D0, 0x0110 }, + { 0x01F0, 0x0111 }, + { 0x03AA, 0x0112 }, + { 0x03BA, 0x0113 }, + { 0x03CC, 0x0116 }, + { 0x03EC, 0x0117 }, + { 0x01CA, 0x0118 }, + { 0x01EA, 0x0119 }, + { 0x01CC, 0x011A }, + { 0x01EC, 0x011B }, + { 0x02D8, 0x011C }, + { 0x02F8, 0x011D }, + { 0x02AB, 0x011E }, + { 0x02BB, 0x011F }, + { 0x02D5, 0x0120 }, + { 0x02F5, 0x0121 }, + { 0x03AB, 0x0122 }, + { 0x03BB, 0x0123 }, + { 0x02A6, 0x0124 }, + { 0x02B6, 0x0125 }, + { 0x02A1, 0x0126 }, + { 0x02B1, 0x0127 }, + { 0x03A5, 0x0128 }, + { 0x03B5, 0x0129 }, + { 0x03CF, 0x012A }, + { 0x03EF, 0x012B }, + { 0x03C7, 0x012E }, + { 0x03E7, 0x012F }, + { 0x02A9, 0x0130 }, + { 0x02B9, 0x0131 }, + { 0x02AC, 0x0134 }, + { 0x02BC, 0x0135 }, + { 0x03D3, 0x0136 }, + { 0x03F3, 0x0137 }, + { 0x03A2, 0x0138 }, + { 0x01C5, 0x0139 }, + { 0x01E5, 0x013A }, + { 0x03A6, 0x013B }, + { 0x03B6, 0x013C }, + { 0x01A5, 0x013D }, + { 0x01B5, 0x013E }, + { 0x01A3, 0x0141 }, + { 0x01B3, 0x0142 }, + { 0x01D1, 0x0143 }, + { 0x01F1, 0x0144 }, + { 0x03D1, 0x0145 }, + { 0x03F1, 0x0146 }, + { 0x01D2, 0x0147 }, + { 0x01F2, 0x0148 }, + { 0x03BD, 0x014A }, + { 0x03BF, 0x014B }, + { 0x03D2, 0x014C }, + { 0x03F2, 0x014D }, + { 0x01D5, 0x0150 }, + { 0x01F5, 0x0151 }, + { 0x13BC, 0x0152 }, + { 0x13BD, 0x0153 }, + { 0x01C0, 0x0154 }, + { 0x01E0, 0x0155 }, + { 0x03A3, 0x0156 }, + { 0x03B3, 0x0157 }, + { 0x01D8, 0x0158 }, + { 0x01F8, 0x0159 }, + { 0x01A6, 0x015A }, + { 0x01B6, 0x015B }, + { 0x02DE, 0x015C }, + { 0x02FE, 0x015D }, + { 0x01AA, 0x015E }, + { 0x01BA, 0x015F }, + { 0x01A9, 0x0160 }, + { 0x01B9, 0x0161 }, + { 0x01DE, 0x0162 }, + { 0x01FE, 0x0163 }, + { 0x01AB, 0x0164 }, + { 0x01BB, 0x0165 }, + { 0x03AC, 0x0166 }, + { 0x03BC, 0x0167 }, + { 0x03DD, 0x0168 }, + { 0x03FD, 0x0169 }, + { 0x03DE, 0x016A }, + { 0x03FE, 0x016B }, + { 0x02DD, 0x016C }, + { 0x02FD, 0x016D }, + { 0x01D9, 0x016E }, + { 0x01F9, 0x016F }, + { 0x01DB, 0x0170 }, + { 0x01FB, 0x0171 }, + { 0x03D9, 0x0172 }, + { 0x03F9, 0x0173 }, + { 0x13BE, 0x0178 }, + { 0x01AC, 0x0179 }, + { 0x01BC, 0x017A }, + { 0x01AF, 0x017B }, + { 0x01BF, 0x017C }, + { 0x01AE, 0x017D }, + { 0x01BE, 0x017E }, + { 0x08F6, 0x0192 }, + { 0x01B7, 0x02C7 }, + { 0x01A2, 0x02D8 }, + { 0x01FF, 0x02D9 }, + { 0x01B2, 0x02DB }, + { 0x01BD, 0x02DD }, + { 0x07AE, 0x0385 }, + { 0x07A1, 0x0386 }, + { 0x07A2, 0x0388 }, + { 0x07A3, 0x0389 }, + { 0x07A4, 0x038A }, + { 0x07A7, 0x038C }, + { 0x07A8, 0x038E }, + { 0x07AB, 0x038F }, + { 0x07B6, 0x0390 }, + { 0x07C1, 0x0391 }, + { 0x07C2, 0x0392 }, + { 0x07C3, 0x0393 }, + { 0x07C4, 0x0394 }, + { 0x07C5, 0x0395 }, + { 0x07C6, 0x0396 }, + { 0x07C7, 0x0397 }, + { 0x07C8, 0x0398 }, + { 0x07C9, 0x0399 }, + { 0x07CA, 0x039A }, + { 0x07CB, 0x039B }, + { 0x07CC, 0x039C }, + { 0x07CD, 0x039D }, + { 0x07CE, 0x039E }, + { 0x07CF, 0x039F }, + { 0x07D0, 0x03A0 }, + { 0x07D1, 0x03A1 }, + { 0x07D2, 0x03A3 }, + { 0x07D4, 0x03A4 }, + { 0x07D5, 0x03A5 }, + { 0x07D6, 0x03A6 }, + { 0x07D7, 0x03A7 }, + { 0x07D8, 0x03A8 }, + { 0x07D9, 0x03A9 }, + { 0x07A5, 0x03AA }, + { 0x07A9, 0x03AB }, + { 0x07B1, 0x03AC }, + { 0x07B2, 0x03AD }, + { 0x07B3, 0x03AE }, + { 0x07B4, 0x03AF }, + { 0x07BA, 0x03B0 }, + { 0x07E1, 0x03B1 }, + { 0x07E2, 0x03B2 }, + { 0x07E3, 0x03B3 }, + { 0x07E4, 0x03B4 }, + { 0x07E5, 0x03B5 }, + { 0x07E6, 0x03B6 }, + { 0x07E7, 0x03B7 }, + { 0x07E8, 0x03B8 }, + { 0x07E9, 0x03B9 }, + { 0x07EA, 0x03BA }, + { 0x07EB, 0x03BB }, + { 0x07EC, 0x03BC }, + { 0x07ED, 0x03BD }, + { 0x07EE, 0x03BE }, + { 0x07EF, 0x03BF }, + { 0x07F0, 0x03C0 }, + { 0x07F1, 0x03C1 }, + { 0x07F3, 0x03C2 }, + { 0x07F2, 0x03C3 }, + { 0x07F4, 0x03C4 }, + { 0x07F5, 0x03C5 }, + { 0x07F6, 0x03C6 }, + { 0x07F7, 0x03C7 }, + { 0x07F8, 0x03C8 }, + { 0x07F9, 0x03C9 }, + { 0x07B5, 0x03CA }, + { 0x07B9, 0x03CB }, + { 0x07B7, 0x03CC }, + { 0x07B8, 0x03CD }, + { 0x07BB, 0x03CE }, + { 0x06B3, 0x0401 }, + { 0x06B1, 0x0402 }, + { 0x06B2, 0x0403 }, + { 0x06B4, 0x0404 }, + { 0x06B5, 0x0405 }, + { 0x06B6, 0x0406 }, + { 0x06B7, 0x0407 }, + { 0x06B8, 0x0408 }, + { 0x06B9, 0x0409 }, + { 0x06BA, 0x040A }, + { 0x06BB, 0x040B }, + { 0x06BC, 0x040C }, + { 0x06BE, 0x040E }, + { 0x06BF, 0x040F }, + { 0x06E1, 0x0410 }, + { 0x06E2, 0x0411 }, + { 0x06F7, 0x0412 }, + { 0x06E7, 0x0413 }, + { 0x06E4, 0x0414 }, + { 0x06E5, 0x0415 }, + { 0x06F6, 0x0416 }, + { 0x06FA, 0x0417 }, + { 0x06E9, 0x0418 }, + { 0x06EA, 0x0419 }, + { 0x06EB, 0x041A }, + { 0x06EC, 0x041B }, + { 0x06ED, 0x041C }, + { 0x06EE, 0x041D }, + { 0x06EF, 0x041E }, + { 0x06F0, 0x041F }, + { 0x06F2, 0x0420 }, + { 0x06F3, 0x0421 }, + { 0x06F4, 0x0422 }, + { 0x06F5, 0x0423 }, + { 0x06E6, 0x0424 }, + { 0x06E8, 0x0425 }, + { 0x06E3, 0x0426 }, + { 0x06FE, 0x0427 }, + { 0x06FB, 0x0428 }, + { 0x06FD, 0x0429 }, + { 0x06FF, 0x042A }, + { 0x06F9, 0x042B }, + { 0x06F8, 0x042C }, + { 0x06FC, 0x042D }, + { 0x06E0, 0x042E }, + { 0x06F1, 0x042F }, + { 0x06C1, 0x0430 }, + { 0x06C2, 0x0431 }, + { 0x06D7, 0x0432 }, + { 0x06C7, 0x0433 }, + { 0x06C4, 0x0434 }, + { 0x06C5, 0x0435 }, + { 0x06D6, 0x0436 }, + { 0x06DA, 0x0437 }, + { 0x06C9, 0x0438 }, + { 0x06CA, 0x0439 }, + { 0x06CB, 0x043A }, + { 0x06CC, 0x043B }, + { 0x06CD, 0x043C }, + { 0x06CE, 0x043D }, + { 0x06CF, 0x043E }, + { 0x06D0, 0x043F }, + { 0x06D2, 0x0440 }, + { 0x06D3, 0x0441 }, + { 0x06D4, 0x0442 }, + { 0x06D5, 0x0443 }, + { 0x06C6, 0x0444 }, + { 0x06C8, 0x0445 }, + { 0x06C3, 0x0446 }, + { 0x06DE, 0x0447 }, + { 0x06DB, 0x0448 }, + { 0x06DD, 0x0449 }, + { 0x06DF, 0x044A }, + { 0x06D9, 0x044B }, + { 0x06D8, 0x044C }, + { 0x06DC, 0x044D }, + { 0x06C0, 0x044E }, + { 0x06D1, 0x044F }, + { 0x06A3, 0x0451 }, + { 0x06A1, 0x0452 }, + { 0x06A2, 0x0453 }, + { 0x06A4, 0x0454 }, + { 0x06A5, 0x0455 }, + { 0x06A6, 0x0456 }, + { 0x06A7, 0x0457 }, + { 0x06A8, 0x0458 }, + { 0x06A9, 0x0459 }, + { 0x06AA, 0x045A }, + { 0x06AB, 0x045B }, + { 0x06AC, 0x045C }, + { 0x06AE, 0x045E }, + { 0x06AF, 0x045F }, + { 0x0CE0, 0x05D0 }, + { 0x0CE1, 0x05D1 }, + { 0x0CE2, 0x05D2 }, + { 0x0CE3, 0x05D3 }, + { 0x0CE4, 0x05D4 }, + { 0x0CE5, 0x05D5 }, + { 0x0CE6, 0x05D6 }, + { 0x0CE7, 0x05D7 }, + { 0x0CE8, 0x05D8 }, + { 0x0CE9, 0x05D9 }, + { 0x0CEA, 0x05DA }, + { 0x0CEB, 0x05DB }, + { 0x0CEC, 0x05DC }, + { 0x0CED, 0x05DD }, + { 0x0CEE, 0x05DE }, + { 0x0CEF, 0x05DF }, + { 0x0CF0, 0x05E0 }, + { 0x0CF1, 0x05E1 }, + { 0x0CF2, 0x05E2 }, + { 0x0CF3, 0x05E3 }, + { 0x0CF4, 0x05E4 }, + { 0x0CF5, 0x05E5 }, + { 0x0CF6, 0x05E6 }, + { 0x0CF7, 0x05E7 }, + { 0x0CF8, 0x05E8 }, + { 0x0CF9, 0x05E9 }, + { 0x0CFA, 0x05EA }, + { 0x05AC, 0x060C }, + { 0x05BB, 0x061B }, + { 0x05BF, 0x061F }, + { 0x05C1, 0x0621 }, + { 0x05C2, 0x0622 }, + { 0x05C3, 0x0623 }, + { 0x05C4, 0x0624 }, + { 0x05C5, 0x0625 }, + { 0x05C6, 0x0626 }, + { 0x05C7, 0x0627 }, + { 0x05C8, 0x0628 }, + { 0x05C9, 0x0629 }, + { 0x05CA, 0x062A }, + { 0x05CB, 0x062B }, + { 0x05CC, 0x062C }, + { 0x05CD, 0x062D }, + { 0x05CE, 0x062E }, + { 0x05CF, 0x062F }, + { 0x05D0, 0x0630 }, + { 0x05D1, 0x0631 }, + { 0x05D2, 0x0632 }, + { 0x05D3, 0x0633 }, + { 0x05D4, 0x0634 }, + { 0x05D5, 0x0635 }, + { 0x05D6, 0x0636 }, + { 0x05D7, 0x0637 }, + { 0x05D8, 0x0638 }, + { 0x05D9, 0x0639 }, + { 0x05DA, 0x063A }, + { 0x05E0, 0x0640 }, + { 0x05E1, 0x0641 }, + { 0x05E2, 0x0642 }, + { 0x05E3, 0x0643 }, + { 0x05E4, 0x0644 }, + { 0x05E5, 0x0645 }, + { 0x05E6, 0x0646 }, + { 0x05E7, 0x0647 }, + { 0x05E8, 0x0648 }, + { 0x05E9, 0x0649 }, + { 0x05EA, 0x064A }, + { 0x05EB, 0x064B }, + { 0x05EC, 0x064C }, + { 0x05ED, 0x064D }, + { 0x05EE, 0x064E }, + { 0x05EF, 0x064F }, + { 0x05F0, 0x0650 }, + { 0x05F1, 0x0651 }, + { 0x05F2, 0x0652 }, + { 0x0DA1, 0x0E01 }, + { 0x0DA2, 0x0E02 }, + { 0x0DA3, 0x0E03 }, + { 0x0DA4, 0x0E04 }, + { 0x0DA5, 0x0E05 }, + { 0x0DA6, 0x0E06 }, + { 0x0DA7, 0x0E07 }, + { 0x0DA8, 0x0E08 }, + { 0x0DA9, 0x0E09 }, + { 0x0DAA, 0x0E0A }, + { 0x0DAB, 0x0E0B }, + { 0x0DAC, 0x0E0C }, + { 0x0DAD, 0x0E0D }, + { 0x0DAE, 0x0E0E }, + { 0x0DAF, 0x0E0F }, + { 0x0DB0, 0x0E10 }, + { 0x0DB1, 0x0E11 }, + { 0x0DB2, 0x0E12 }, + { 0x0DB3, 0x0E13 }, + { 0x0DB4, 0x0E14 }, + { 0x0DB5, 0x0E15 }, + { 0x0DB6, 0x0E16 }, + { 0x0DB7, 0x0E17 }, + { 0x0DB8, 0x0E18 }, + { 0x0DB9, 0x0E19 }, + { 0x0DBA, 0x0E1A }, + { 0x0DBB, 0x0E1B }, + { 0x0DBC, 0x0E1C }, + { 0x0DBD, 0x0E1D }, + { 0x0DBE, 0x0E1E }, + { 0x0DBF, 0x0E1F }, + { 0x0DC0, 0x0E20 }, + { 0x0DC1, 0x0E21 }, + { 0x0DC2, 0x0E22 }, + { 0x0DC3, 0x0E23 }, + { 0x0DC4, 0x0E24 }, + { 0x0DC5, 0x0E25 }, + { 0x0DC6, 0x0E26 }, + { 0x0DC7, 0x0E27 }, + { 0x0DC8, 0x0E28 }, + { 0x0DC9, 0x0E29 }, + { 0x0DCA, 0x0E2A }, + { 0x0DCB, 0x0E2B }, + { 0x0DCC, 0x0E2C }, + { 0x0DCD, 0x0E2D }, + { 0x0DCE, 0x0E2E }, + { 0x0DCF, 0x0E2F }, + { 0x0DD0, 0x0E30 }, + { 0x0DD1, 0x0E31 }, + { 0x0DD2, 0x0E32 }, + { 0x0DD3, 0x0E33 }, + { 0x0DD4, 0x0E34 }, + { 0x0DD5, 0x0E35 }, + { 0x0DD6, 0x0E36 }, + { 0x0DD7, 0x0E37 }, + { 0x0DD8, 0x0E38 }, + { 0x0DD9, 0x0E39 }, + { 0x0DDA, 0x0E3A }, + { 0x0DDF, 0x0E3F }, + { 0x0DE0, 0x0E40 }, + { 0x0DE1, 0x0E41 }, + { 0x0DE2, 0x0E42 }, + { 0x0DE3, 0x0E43 }, + { 0x0DE4, 0x0E44 }, + { 0x0DE5, 0x0E45 }, + { 0x0DE6, 0x0E46 }, + { 0x0DE7, 0x0E47 }, + { 0x0DE8, 0x0E48 }, + { 0x0DE9, 0x0E49 }, + { 0x0DEA, 0x0E4A }, + { 0x0DEB, 0x0E4B }, + { 0x0DEC, 0x0E4C }, + { 0x0DED, 0x0E4D }, + { 0x0DF0, 0x0E50 }, + { 0x0DF1, 0x0E51 }, + { 0x0DF2, 0x0E52 }, + { 0x0DF3, 0x0E53 }, + { 0x0DF4, 0x0E54 }, + { 0x0DF5, 0x0E55 }, + { 0x0DF6, 0x0E56 }, + { 0x0DF7, 0x0E57 }, + { 0x0DF8, 0x0E58 }, + { 0x0DF9, 0x0E59 }, + { 0x0ED4, 0x11A8 }, + { 0x0ED5, 0x11A9 }, + { 0x0ED6, 0x11AA }, + { 0x0ED7, 0x11AB }, + { 0x0ED8, 0x11AC }, + { 0x0ED9, 0x11AD }, + { 0x0EDA, 0x11AE }, + { 0x0EDB, 0x11AF }, + { 0x0EDC, 0x11B0 }, + { 0x0EDD, 0x11B1 }, + { 0x0EDE, 0x11B2 }, + { 0x0EDF, 0x11B3 }, + { 0x0EE0, 0x11B4 }, + { 0x0EE1, 0x11B5 }, + { 0x0EE2, 0x11B6 }, + { 0x0EE3, 0x11B7 }, + { 0x0EE4, 0x11B8 }, + { 0x0EE5, 0x11B9 }, + { 0x0EE6, 0x11BA }, + { 0x0EE7, 0x11BB }, + { 0x0EE8, 0x11BC }, + { 0x0EE9, 0x11BD }, + { 0x0EEA, 0x11BE }, + { 0x0EEB, 0x11BF }, + { 0x0EEC, 0x11C0 }, + { 0x0EED, 0x11C1 }, + { 0x0EEE, 0x11C2 }, + { 0x0EF8, 0x11EB }, + { 0x0EFA, 0x11F9 }, + { 0x0AA2, 0x2002 }, + { 0x0AA1, 0x2003 }, + { 0x0AA3, 0x2004 }, + { 0x0AA4, 0x2005 }, + { 0x0AA5, 0x2007 }, + { 0x0AA6, 0x2008 }, + { 0x0AA7, 0x2009 }, + { 0x0AA8, 0x200A }, + { 0x0ABB, 0x2012 }, + { 0x0AAA, 0x2013 }, + { 0x0AA9, 0x2014 }, + { 0x07AF, 0x2015 }, + { 0x0CDF, 0x2017 }, + { 0x0AD0, 0x2018 }, + { 0x0AD1, 0x2019 }, + { 0x0AFD, 0x201A }, + { 0x0AD2, 0x201C }, + { 0x0AD3, 0x201D }, + { 0x0AFE, 0x201E }, + { 0x0AF1, 0x2020 }, + { 0x0AF2, 0x2021 }, + { 0x0AE6, 0x2022 }, + { 0x0AAE, 0x2026 }, + { 0x0AD6, 0x2032 }, + { 0x0AD7, 0x2033 }, + { 0x0AFC, 0x2038 }, + { 0x047E, 0x203E }, + { 0x20A0, 0x20A0 }, + { 0x20A1, 0x20A1 }, + { 0x20A2, 0x20A2 }, + { 0x20A3, 0x20A3 }, + { 0x20A4, 0x20A4 }, + { 0x20A5, 0x20A5 }, + { 0x20A6, 0x20A6 }, + { 0x20A7, 0x20A7 }, + { 0x20A8, 0x20A8 }, + { 0x0EFF, 0x20A9 }, + { 0x20A9, 0x20A9 }, + { 0x20AA, 0x20AA }, + { 0x20AB, 0x20AB }, + { 0x20AC, 0x20AC }, + { 0x0AB8, 0x2105 }, + { 0x06B0, 0x2116 }, + { 0x0AFB, 0x2117 }, + { 0x0AD4, 0x211E }, + { 0x0AC9, 0x2122 }, + { 0x0AB0, 0x2153 }, + { 0x0AB1, 0x2154 }, + { 0x0AB2, 0x2155 }, + { 0x0AB3, 0x2156 }, + { 0x0AB4, 0x2157 }, + { 0x0AB5, 0x2158 }, + { 0x0AB6, 0x2159 }, + { 0x0AB7, 0x215A }, + { 0x0AC3, 0x215B }, + { 0x0AC4, 0x215C }, + { 0x0AC5, 0x215D }, + { 0x0AC6, 0x215E }, + { 0x08FB, 0x2190 }, + { 0x08FC, 0x2191 }, + { 0x08FD, 0x2192 }, + { 0x08FE, 0x2193 }, + { 0x08CE, 0x21D2 }, + { 0x08CD, 0x21D4 }, + { 0x08EF, 0x2202 }, + { 0x08C5, 0x2207 }, + { 0x0BCA, 0x2218 }, + { 0x08D6, 0x221A }, + { 0x08C1, 0x221D }, + { 0x08C2, 0x221E }, + { 0x08DE, 0x2227 }, + { 0x0BA9, 0x2227 }, + { 0x08DF, 0x2228 }, + { 0x0BA8, 0x2228 }, + { 0x08DC, 0x2229 }, + { 0x0BC3, 0x2229 }, + { 0x08DD, 0x222A }, + { 0x0BD6, 0x222A }, + { 0x08BF, 0x222B }, + { 0x08C0, 0x2234 }, + { 0x08C8, 0x2245 }, + { 0x08BD, 0x2260 }, + { 0x08CF, 0x2261 }, + { 0x08BC, 0x2264 }, + { 0x08BE, 0x2265 }, + { 0x08DA, 0x2282 }, + { 0x0BDA, 0x2282 }, + { 0x08DB, 0x2283 }, + { 0x0BD8, 0x2283 }, + { 0x0BFC, 0x22A2 }, + { 0x0BDC, 0x22A3 }, + { 0x0BC2, 0x22A4 }, + { 0x0BCE, 0x22A5 }, + { 0x0BD3, 0x2308 }, + { 0x0BC4, 0x230A }, + { 0x0AFA, 0x2315 }, + { 0x08A4, 0x2320 }, + { 0x08A5, 0x2321 }, + { 0x0ABC, 0x2329 }, + { 0x0ABE, 0x232A }, + { 0x0BCC, 0x2395 }, + { 0x09E2, 0x2409 }, + { 0x09E5, 0x240A }, + { 0x09E9, 0x240B }, + { 0x09E3, 0x240C }, + { 0x09E4, 0x240D }, + { 0x09DF, 0x2422 }, + { 0x09E8, 0x2424 }, + { 0x09F1, 0x2500 }, + { 0x08A6, 0x2502 }, + { 0x09F8, 0x2502 }, + { 0x09EC, 0x250C }, + { 0x09EB, 0x2510 }, + { 0x09ED, 0x2514 }, + { 0x09EA, 0x2518 }, + { 0x09F4, 0x251C }, + { 0x09F5, 0x2524 }, + { 0x09F7, 0x252C }, + { 0x09F6, 0x2534 }, + { 0x09EE, 0x253C }, + { 0x09E1, 0x2592 }, + { 0x0ADF, 0x25A0 }, + { 0x0ACF, 0x25A1 }, + { 0x0AE7, 0x25AA }, + { 0x0AE1, 0x25AB }, + { 0x0ADB, 0x25AC }, + { 0x0AE2, 0x25AD }, + { 0x0AE8, 0x25B2 }, + { 0x0AE3, 0x25B3 }, + { 0x0ADD, 0x25B6 }, + { 0x0ACD, 0x25B7 }, + { 0x0AE9, 0x25BC }, + { 0x0AE4, 0x25BD }, + { 0x0ADC, 0x25C0 }, + { 0x0ACC, 0x25C1 }, + { 0x09E0, 0x25C6 }, + { 0x0ACE, 0x25CB }, + { 0x0BCF, 0x25CB }, + { 0x0ADE, 0x25CF }, + { 0x0AE0, 0x25E6 }, + { 0x0AE5, 0x2606 }, + { 0x0AF9, 0x260E }, + { 0x0ACA, 0x2613 }, + { 0x0AEA, 0x261C }, + { 0x0AEB, 0x261E }, + { 0x0AF8, 0x2640 }, + { 0x0AF7, 0x2642 }, + { 0x0AEC, 0x2663 }, + { 0x0AEE, 0x2665 }, + { 0x0AED, 0x2666 }, + { 0x0AF6, 0x266D }, + { 0x0AF5, 0x266F }, + { 0x0AF3, 0x2713 }, + { 0x0AF4, 0x2717 }, + { 0x0AD9, 0x271D }, + { 0x0AF0, 0x2720 }, + { 0x04A4, 0x3001 }, + { 0x04A1, 0x3002 }, + { 0x04A2, 0x300C }, + { 0x04A3, 0x300D }, + { 0x04DE, 0x309B }, + { 0x04DF, 0x309C }, + { 0x04A7, 0x30A1 }, + { 0x04B1, 0x30A2 }, + { 0x04A8, 0x30A3 }, + { 0x04B2, 0x30A4 }, + { 0x04A9, 0x30A5 }, + { 0x04B3, 0x30A6 }, + { 0x04AA, 0x30A7 }, + { 0x04B4, 0x30A8 }, + { 0x04AB, 0x30A9 }, + { 0x04B5, 0x30AA }, + { 0x04B6, 0x30AB }, + { 0x04B7, 0x30AD }, + { 0x04B8, 0x30AF }, + { 0x04B9, 0x30B1 }, + { 0x04BA, 0x30B3 }, + { 0x04BB, 0x30B5 }, + { 0x04BC, 0x30B7 }, + { 0x04BD, 0x30B9 }, + { 0x04BE, 0x30BB }, + { 0x04BF, 0x30BD }, + { 0x04C0, 0x30BF }, + { 0x04C1, 0x30C1 }, + { 0x04AF, 0x30C3 }, + { 0x04C2, 0x30C4 }, + { 0x04C3, 0x30C6 }, + { 0x04C4, 0x30C8 }, + { 0x04C5, 0x30CA }, + { 0x04C6, 0x30CB }, + { 0x04C7, 0x30CC }, + { 0x04C8, 0x30CD }, + { 0x04C9, 0x30CE }, + { 0x04CA, 0x30CF }, + { 0x04CB, 0x30D2 }, + { 0x04CC, 0x30D5 }, + { 0x04CD, 0x30D8 }, + { 0x04CE, 0x30DB }, + { 0x04CF, 0x30DE }, + { 0x04D0, 0x30DF }, + { 0x04D1, 0x30E0 }, + { 0x04D2, 0x30E1 }, + { 0x04D3, 0x30E2 }, + { 0x04AC, 0x30E3 }, + { 0x04D4, 0x30E4 }, + { 0x04AD, 0x30E5 }, + { 0x04D5, 0x30E6 }, + { 0x04AE, 0x30E7 }, + { 0x04D6, 0x30E8 }, + { 0x04D7, 0x30E9 }, + { 0x04D8, 0x30EA }, + { 0x04D9, 0x30EB }, + { 0x04DA, 0x30EC }, + { 0x04DB, 0x30ED }, + { 0x04DC, 0x30EF }, + { 0x04A6, 0x30F2 }, + { 0x04DD, 0x30F3 }, + { 0x04A5, 0x30FB }, + { 0x04B0, 0x30FC }, + { 0x0EA1, 0x3131 }, + { 0x0EA2, 0x3132 }, + { 0x0EA3, 0x3133 }, + { 0x0EA4, 0x3134 }, + { 0x0EA5, 0x3135 }, + { 0x0EA6, 0x3136 }, + { 0x0EA7, 0x3137 }, + { 0x0EA8, 0x3138 }, + { 0x0EA9, 0x3139 }, + { 0x0EAA, 0x313A }, + { 0x0EAB, 0x313B }, + { 0x0EAC, 0x313C }, + { 0x0EAD, 0x313D }, + { 0x0EAE, 0x313E }, + { 0x0EAF, 0x313F }, + { 0x0EB0, 0x3140 }, + { 0x0EB1, 0x3141 }, + { 0x0EB2, 0x3142 }, + { 0x0EB3, 0x3143 }, + { 0x0EB4, 0x3144 }, + { 0x0EB5, 0x3145 }, + { 0x0EB6, 0x3146 }, + { 0x0EB7, 0x3147 }, + { 0x0EB8, 0x3148 }, + { 0x0EB9, 0x3149 }, + { 0x0EBA, 0x314A }, + { 0x0EBB, 0x314B }, + { 0x0EBC, 0x314C }, + { 0x0EBD, 0x314D }, + { 0x0EBE, 0x314E }, + { 0x0EBF, 0x314F }, + { 0x0EC0, 0x3150 }, + { 0x0EC1, 0x3151 }, + { 0x0EC2, 0x3152 }, + { 0x0EC3, 0x3153 }, + { 0x0EC4, 0x3154 }, + { 0x0EC5, 0x3155 }, + { 0x0EC6, 0x3156 }, + { 0x0EC7, 0x3157 }, + { 0x0EC8, 0x3158 }, + { 0x0EC9, 0x3159 }, + { 0x0ECA, 0x315A }, + { 0x0ECB, 0x315B }, + { 0x0ECC, 0x315C }, + { 0x0ECD, 0x315D }, + { 0x0ECE, 0x315E }, + { 0x0ECF, 0x315F }, + { 0x0ED0, 0x3160 }, + { 0x0ED1, 0x3161 }, + { 0x0ED2, 0x3162 }, + { 0x0ED3, 0x3163 }, + { 0x0EEF, 0x316D }, + { 0x0EF0, 0x3171 }, + { 0x0EF1, 0x3178 }, + { 0x0EF2, 0x317F }, + { 0x0EF4, 0x3184 }, + { 0x0EF5, 0x3186 }, + { 0x0EF6, 0x318D }, + { 0x0EF7, 0x318E } +}; + +KeySym KeyMappingX11::get_keysym_from_unicode(unsigned int p_unicode) { + /* Latin 1 */ + + if (p_unicode >= 0x20 && p_unicode <= 0x7e) { + return p_unicode; + } + + if (p_unicode >= 0xa0 && p_unicode <= 0xff) { + return p_unicode; + } + + int middle, low = 0, high = _UNICODE_MAX - 1; + do { + middle = (high + low) / 2; + if (_unicode_to_xkeysym[middle].keysym == p_unicode) { + return _unicode_to_xkeysym[middle].keysym; + } + if (_unicode_to_xkeysym[middle].keysym <= p_unicode) { + low = middle + 1; + } else { + high = middle - 1; + } + } while (high >= low); + + // if not found, let's hope X understands it as unicode + return p_unicode | 0x01000000; +} diff --git a/platform/linuxbsd/key_mapping_x11.h b/platform/linuxbsd/key_mapping_x11.h new file mode 100644 index 0000000000..163a8e21db --- /dev/null +++ b/platform/linuxbsd/key_mapping_x11.h @@ -0,0 +1,54 @@ +/*************************************************************************/ +/* key_mapping_x11.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifndef KEY_MAPPING_X11_H +#define KEY_MAPPING_X11_H + +#include <X11/XF86keysym.h> +#include <X11/Xlib.h> +#define XK_MISCELLANY +#define XK_LATIN1 +#define XK_XKB_KEYS +#include <X11/keysymdef.h> + +#include "core/os/keyboard.h" + +class KeyMappingX11 { + KeyMappingX11() {} + +public: + static unsigned int get_keycode(KeySym p_keysym); + static unsigned int get_scancode(unsigned int p_code); + static KeySym get_keysym(unsigned int p_code); + static unsigned int get_unicode_from_keysym(KeySym p_keysym); + static KeySym get_keysym_from_unicode(unsigned int p_unicode); +}; + +#endif diff --git a/platform/linuxbsd/libudev-so_wrap.c b/platform/linuxbsd/libudev-so_wrap.c new file mode 100644 index 0000000000..a9fa4a494a --- /dev/null +++ b/platform/linuxbsd/libudev-so_wrap.c @@ -0,0 +1,1013 @@ +// This file is generated. Do not edit! +// see https://github.com/hpvb/dynload-wrapper for details +// generated by /home/hp/Projects/godot/pulse/generate-wrapper.py 0.3 on 2021-02-20 00:08:59 +// flags: /home/hp/Projects/godot/pulse/generate-wrapper.py --include /usr/include/libudev.h --sys-include <libudev.h> --soname libudev.so.1 --init-name libudev --omit-prefix gnu_ --output-header libudev-so_wrap.h --output-implementation libudev-so_wrap.c +// +#include <stdint.h> + +#define udev_ref udev_ref_dylibloader_orig_libudev +#define udev_unref udev_unref_dylibloader_orig_libudev +#define udev_new udev_new_dylibloader_orig_libudev +#define udev_set_log_fn udev_set_log_fn_dylibloader_orig_libudev +#define udev_get_log_priority udev_get_log_priority_dylibloader_orig_libudev +#define udev_set_log_priority udev_set_log_priority_dylibloader_orig_libudev +#define udev_get_userdata udev_get_userdata_dylibloader_orig_libudev +#define udev_set_userdata udev_set_userdata_dylibloader_orig_libudev +#define udev_list_entry_get_next udev_list_entry_get_next_dylibloader_orig_libudev +#define udev_list_entry_get_by_name udev_list_entry_get_by_name_dylibloader_orig_libudev +#define udev_list_entry_get_name udev_list_entry_get_name_dylibloader_orig_libudev +#define udev_list_entry_get_value udev_list_entry_get_value_dylibloader_orig_libudev +#define udev_device_ref udev_device_ref_dylibloader_orig_libudev +#define udev_device_unref udev_device_unref_dylibloader_orig_libudev +#define udev_device_get_udev udev_device_get_udev_dylibloader_orig_libudev +#define udev_device_new_from_syspath udev_device_new_from_syspath_dylibloader_orig_libudev +#define udev_device_new_from_devnum udev_device_new_from_devnum_dylibloader_orig_libudev +#define udev_device_new_from_subsystem_sysname udev_device_new_from_subsystem_sysname_dylibloader_orig_libudev +#define udev_device_new_from_device_id udev_device_new_from_device_id_dylibloader_orig_libudev +#define udev_device_new_from_environment udev_device_new_from_environment_dylibloader_orig_libudev +#define udev_device_get_parent udev_device_get_parent_dylibloader_orig_libudev +#define udev_device_get_parent_with_subsystem_devtype udev_device_get_parent_with_subsystem_devtype_dylibloader_orig_libudev +#define udev_device_get_devpath udev_device_get_devpath_dylibloader_orig_libudev +#define udev_device_get_subsystem udev_device_get_subsystem_dylibloader_orig_libudev +#define udev_device_get_devtype udev_device_get_devtype_dylibloader_orig_libudev +#define udev_device_get_syspath udev_device_get_syspath_dylibloader_orig_libudev +#define udev_device_get_sysname udev_device_get_sysname_dylibloader_orig_libudev +#define udev_device_get_sysnum udev_device_get_sysnum_dylibloader_orig_libudev +#define udev_device_get_devnode udev_device_get_devnode_dylibloader_orig_libudev +#define udev_device_get_is_initialized udev_device_get_is_initialized_dylibloader_orig_libudev +#define udev_device_get_devlinks_list_entry udev_device_get_devlinks_list_entry_dylibloader_orig_libudev +#define udev_device_get_properties_list_entry udev_device_get_properties_list_entry_dylibloader_orig_libudev +#define udev_device_get_tags_list_entry udev_device_get_tags_list_entry_dylibloader_orig_libudev +#define udev_device_get_sysattr_list_entry udev_device_get_sysattr_list_entry_dylibloader_orig_libudev +#define udev_device_get_property_value udev_device_get_property_value_dylibloader_orig_libudev +#define udev_device_get_driver udev_device_get_driver_dylibloader_orig_libudev +#define udev_device_get_devnum udev_device_get_devnum_dylibloader_orig_libudev +#define udev_device_get_action udev_device_get_action_dylibloader_orig_libudev +#define udev_device_get_seqnum udev_device_get_seqnum_dylibloader_orig_libudev +#define udev_device_get_usec_since_initialized udev_device_get_usec_since_initialized_dylibloader_orig_libudev +#define udev_device_get_sysattr_value udev_device_get_sysattr_value_dylibloader_orig_libudev +#define udev_device_set_sysattr_value udev_device_set_sysattr_value_dylibloader_orig_libudev +#define udev_device_has_tag udev_device_has_tag_dylibloader_orig_libudev +#define udev_monitor_ref udev_monitor_ref_dylibloader_orig_libudev +#define udev_monitor_unref udev_monitor_unref_dylibloader_orig_libudev +#define udev_monitor_get_udev udev_monitor_get_udev_dylibloader_orig_libudev +#define udev_monitor_new_from_netlink udev_monitor_new_from_netlink_dylibloader_orig_libudev +#define udev_monitor_enable_receiving udev_monitor_enable_receiving_dylibloader_orig_libudev +#define udev_monitor_set_receive_buffer_size udev_monitor_set_receive_buffer_size_dylibloader_orig_libudev +#define udev_monitor_get_fd udev_monitor_get_fd_dylibloader_orig_libudev +#define udev_monitor_receive_device udev_monitor_receive_device_dylibloader_orig_libudev +#define udev_monitor_filter_add_match_subsystem_devtype udev_monitor_filter_add_match_subsystem_devtype_dylibloader_orig_libudev +#define udev_monitor_filter_add_match_tag udev_monitor_filter_add_match_tag_dylibloader_orig_libudev +#define udev_monitor_filter_update udev_monitor_filter_update_dylibloader_orig_libudev +#define udev_monitor_filter_remove udev_monitor_filter_remove_dylibloader_orig_libudev +#define udev_enumerate_ref udev_enumerate_ref_dylibloader_orig_libudev +#define udev_enumerate_unref udev_enumerate_unref_dylibloader_orig_libudev +#define udev_enumerate_get_udev udev_enumerate_get_udev_dylibloader_orig_libudev +#define udev_enumerate_new udev_enumerate_new_dylibloader_orig_libudev +#define udev_enumerate_add_match_subsystem udev_enumerate_add_match_subsystem_dylibloader_orig_libudev +#define udev_enumerate_add_nomatch_subsystem udev_enumerate_add_nomatch_subsystem_dylibloader_orig_libudev +#define udev_enumerate_add_match_sysattr udev_enumerate_add_match_sysattr_dylibloader_orig_libudev +#define udev_enumerate_add_nomatch_sysattr udev_enumerate_add_nomatch_sysattr_dylibloader_orig_libudev +#define udev_enumerate_add_match_property udev_enumerate_add_match_property_dylibloader_orig_libudev +#define udev_enumerate_add_match_sysname udev_enumerate_add_match_sysname_dylibloader_orig_libudev +#define udev_enumerate_add_match_tag udev_enumerate_add_match_tag_dylibloader_orig_libudev +#define udev_enumerate_add_match_parent udev_enumerate_add_match_parent_dylibloader_orig_libudev +#define udev_enumerate_add_match_is_initialized udev_enumerate_add_match_is_initialized_dylibloader_orig_libudev +#define udev_enumerate_add_syspath udev_enumerate_add_syspath_dylibloader_orig_libudev +#define udev_enumerate_scan_devices udev_enumerate_scan_devices_dylibloader_orig_libudev +#define udev_enumerate_scan_subsystems udev_enumerate_scan_subsystems_dylibloader_orig_libudev +#define udev_enumerate_get_list_entry udev_enumerate_get_list_entry_dylibloader_orig_libudev +#define udev_queue_ref udev_queue_ref_dylibloader_orig_libudev +#define udev_queue_unref udev_queue_unref_dylibloader_orig_libudev +#define udev_queue_get_udev udev_queue_get_udev_dylibloader_orig_libudev +#define udev_queue_new udev_queue_new_dylibloader_orig_libudev +#define udev_queue_get_kernel_seqnum udev_queue_get_kernel_seqnum_dylibloader_orig_libudev +#define udev_queue_get_udev_seqnum udev_queue_get_udev_seqnum_dylibloader_orig_libudev +#define udev_queue_get_udev_is_active udev_queue_get_udev_is_active_dylibloader_orig_libudev +#define udev_queue_get_queue_is_empty udev_queue_get_queue_is_empty_dylibloader_orig_libudev +#define udev_queue_get_seqnum_is_finished udev_queue_get_seqnum_is_finished_dylibloader_orig_libudev +#define udev_queue_get_seqnum_sequence_is_finished udev_queue_get_seqnum_sequence_is_finished_dylibloader_orig_libudev +#define udev_queue_get_fd udev_queue_get_fd_dylibloader_orig_libudev +#define udev_queue_flush udev_queue_flush_dylibloader_orig_libudev +#define udev_queue_get_queued_list_entry udev_queue_get_queued_list_entry_dylibloader_orig_libudev +#define udev_hwdb_new udev_hwdb_new_dylibloader_orig_libudev +#define udev_hwdb_ref udev_hwdb_ref_dylibloader_orig_libudev +#define udev_hwdb_unref udev_hwdb_unref_dylibloader_orig_libudev +#define udev_hwdb_get_properties_list_entry udev_hwdb_get_properties_list_entry_dylibloader_orig_libudev +#define udev_util_encode_string udev_util_encode_string_dylibloader_orig_libudev +#include <libudev.h> +#undef udev_ref +#undef udev_unref +#undef udev_new +#undef udev_set_log_fn +#undef udev_get_log_priority +#undef udev_set_log_priority +#undef udev_get_userdata +#undef udev_set_userdata +#undef udev_list_entry_get_next +#undef udev_list_entry_get_by_name +#undef udev_list_entry_get_name +#undef udev_list_entry_get_value +#undef udev_device_ref +#undef udev_device_unref +#undef udev_device_get_udev +#undef udev_device_new_from_syspath +#undef udev_device_new_from_devnum +#undef udev_device_new_from_subsystem_sysname +#undef udev_device_new_from_device_id +#undef udev_device_new_from_environment +#undef udev_device_get_parent +#undef udev_device_get_parent_with_subsystem_devtype +#undef udev_device_get_devpath +#undef udev_device_get_subsystem +#undef udev_device_get_devtype +#undef udev_device_get_syspath +#undef udev_device_get_sysname +#undef udev_device_get_sysnum +#undef udev_device_get_devnode +#undef udev_device_get_is_initialized +#undef udev_device_get_devlinks_list_entry +#undef udev_device_get_properties_list_entry +#undef udev_device_get_tags_list_entry +#undef udev_device_get_sysattr_list_entry +#undef udev_device_get_property_value +#undef udev_device_get_driver +#undef udev_device_get_devnum +#undef udev_device_get_action +#undef udev_device_get_seqnum +#undef udev_device_get_usec_since_initialized +#undef udev_device_get_sysattr_value +#undef udev_device_set_sysattr_value +#undef udev_device_has_tag +#undef udev_monitor_ref +#undef udev_monitor_unref +#undef udev_monitor_get_udev +#undef udev_monitor_new_from_netlink +#undef udev_monitor_enable_receiving +#undef udev_monitor_set_receive_buffer_size +#undef udev_monitor_get_fd +#undef udev_monitor_receive_device +#undef udev_monitor_filter_add_match_subsystem_devtype +#undef udev_monitor_filter_add_match_tag +#undef udev_monitor_filter_update +#undef udev_monitor_filter_remove +#undef udev_enumerate_ref +#undef udev_enumerate_unref +#undef udev_enumerate_get_udev +#undef udev_enumerate_new +#undef udev_enumerate_add_match_subsystem +#undef udev_enumerate_add_nomatch_subsystem +#undef udev_enumerate_add_match_sysattr +#undef udev_enumerate_add_nomatch_sysattr +#undef udev_enumerate_add_match_property +#undef udev_enumerate_add_match_sysname +#undef udev_enumerate_add_match_tag +#undef udev_enumerate_add_match_parent +#undef udev_enumerate_add_match_is_initialized +#undef udev_enumerate_add_syspath +#undef udev_enumerate_scan_devices +#undef udev_enumerate_scan_subsystems +#undef udev_enumerate_get_list_entry +#undef udev_queue_ref +#undef udev_queue_unref +#undef udev_queue_get_udev +#undef udev_queue_new +#undef udev_queue_get_kernel_seqnum +#undef udev_queue_get_udev_seqnum +#undef udev_queue_get_udev_is_active +#undef udev_queue_get_queue_is_empty +#undef udev_queue_get_seqnum_is_finished +#undef udev_queue_get_seqnum_sequence_is_finished +#undef udev_queue_get_fd +#undef udev_queue_flush +#undef udev_queue_get_queued_list_entry +#undef udev_hwdb_new +#undef udev_hwdb_ref +#undef udev_hwdb_unref +#undef udev_hwdb_get_properties_list_entry +#undef udev_util_encode_string +#include <dlfcn.h> +#include <stdio.h> +struct udev* (*udev_ref_dylibloader_wrapper_libudev)(struct udev*); +struct udev* (*udev_unref_dylibloader_wrapper_libudev)(struct udev*); +struct udev* (*udev_new_dylibloader_wrapper_libudev)( void); +void (*udev_set_log_fn_dylibloader_wrapper_libudev)(struct udev*, void*); +int (*udev_get_log_priority_dylibloader_wrapper_libudev)(struct udev*); +void (*udev_set_log_priority_dylibloader_wrapper_libudev)(struct udev*, int); +void* (*udev_get_userdata_dylibloader_wrapper_libudev)(struct udev*); +void (*udev_set_userdata_dylibloader_wrapper_libudev)(struct udev*, void*); +struct udev_list_entry* (*udev_list_entry_get_next_dylibloader_wrapper_libudev)(struct udev_list_entry*); +struct udev_list_entry* (*udev_list_entry_get_by_name_dylibloader_wrapper_libudev)(struct udev_list_entry*,const char*); +const char* (*udev_list_entry_get_name_dylibloader_wrapper_libudev)(struct udev_list_entry*); +const char* (*udev_list_entry_get_value_dylibloader_wrapper_libudev)(struct udev_list_entry*); +struct udev_device* (*udev_device_ref_dylibloader_wrapper_libudev)(struct udev_device*); +struct udev_device* (*udev_device_unref_dylibloader_wrapper_libudev)(struct udev_device*); +struct udev* (*udev_device_get_udev_dylibloader_wrapper_libudev)(struct udev_device*); +struct udev_device* (*udev_device_new_from_syspath_dylibloader_wrapper_libudev)(struct udev*,const char*); +struct udev_device* (*udev_device_new_from_devnum_dylibloader_wrapper_libudev)(struct udev*, char, dev_t); +struct udev_device* (*udev_device_new_from_subsystem_sysname_dylibloader_wrapper_libudev)(struct udev*,const char*,const char*); +struct udev_device* (*udev_device_new_from_device_id_dylibloader_wrapper_libudev)(struct udev*,const char*); +struct udev_device* (*udev_device_new_from_environment_dylibloader_wrapper_libudev)(struct udev*); +struct udev_device* (*udev_device_get_parent_dylibloader_wrapper_libudev)(struct udev_device*); +struct udev_device* (*udev_device_get_parent_with_subsystem_devtype_dylibloader_wrapper_libudev)(struct udev_device*,const char*,const char*); +const char* (*udev_device_get_devpath_dylibloader_wrapper_libudev)(struct udev_device*); +const char* (*udev_device_get_subsystem_dylibloader_wrapper_libudev)(struct udev_device*); +const char* (*udev_device_get_devtype_dylibloader_wrapper_libudev)(struct udev_device*); +const char* (*udev_device_get_syspath_dylibloader_wrapper_libudev)(struct udev_device*); +const char* (*udev_device_get_sysname_dylibloader_wrapper_libudev)(struct udev_device*); +const char* (*udev_device_get_sysnum_dylibloader_wrapper_libudev)(struct udev_device*); +const char* (*udev_device_get_devnode_dylibloader_wrapper_libudev)(struct udev_device*); +int (*udev_device_get_is_initialized_dylibloader_wrapper_libudev)(struct udev_device*); +struct udev_list_entry* (*udev_device_get_devlinks_list_entry_dylibloader_wrapper_libudev)(struct udev_device*); +struct udev_list_entry* (*udev_device_get_properties_list_entry_dylibloader_wrapper_libudev)(struct udev_device*); +struct udev_list_entry* (*udev_device_get_tags_list_entry_dylibloader_wrapper_libudev)(struct udev_device*); +struct udev_list_entry* (*udev_device_get_sysattr_list_entry_dylibloader_wrapper_libudev)(struct udev_device*); +const char* (*udev_device_get_property_value_dylibloader_wrapper_libudev)(struct udev_device*,const char*); +const char* (*udev_device_get_driver_dylibloader_wrapper_libudev)(struct udev_device*); +dev_t (*udev_device_get_devnum_dylibloader_wrapper_libudev)(struct udev_device*); +const char* (*udev_device_get_action_dylibloader_wrapper_libudev)(struct udev_device*); +unsigned long long int (*udev_device_get_seqnum_dylibloader_wrapper_libudev)(struct udev_device*); +unsigned long long int (*udev_device_get_usec_since_initialized_dylibloader_wrapper_libudev)(struct udev_device*); +const char* (*udev_device_get_sysattr_value_dylibloader_wrapper_libudev)(struct udev_device*,const char*); +int (*udev_device_set_sysattr_value_dylibloader_wrapper_libudev)(struct udev_device*,const char*,const char*); +int (*udev_device_has_tag_dylibloader_wrapper_libudev)(struct udev_device*,const char*); +struct udev_monitor* (*udev_monitor_ref_dylibloader_wrapper_libudev)(struct udev_monitor*); +struct udev_monitor* (*udev_monitor_unref_dylibloader_wrapper_libudev)(struct udev_monitor*); +struct udev* (*udev_monitor_get_udev_dylibloader_wrapper_libudev)(struct udev_monitor*); +struct udev_monitor* (*udev_monitor_new_from_netlink_dylibloader_wrapper_libudev)(struct udev*,const char*); +int (*udev_monitor_enable_receiving_dylibloader_wrapper_libudev)(struct udev_monitor*); +int (*udev_monitor_set_receive_buffer_size_dylibloader_wrapper_libudev)(struct udev_monitor*, int); +int (*udev_monitor_get_fd_dylibloader_wrapper_libudev)(struct udev_monitor*); +struct udev_device* (*udev_monitor_receive_device_dylibloader_wrapper_libudev)(struct udev_monitor*); +int (*udev_monitor_filter_add_match_subsystem_devtype_dylibloader_wrapper_libudev)(struct udev_monitor*,const char*,const char*); +int (*udev_monitor_filter_add_match_tag_dylibloader_wrapper_libudev)(struct udev_monitor*,const char*); +int (*udev_monitor_filter_update_dylibloader_wrapper_libudev)(struct udev_monitor*); +int (*udev_monitor_filter_remove_dylibloader_wrapper_libudev)(struct udev_monitor*); +struct udev_enumerate* (*udev_enumerate_ref_dylibloader_wrapper_libudev)(struct udev_enumerate*); +struct udev_enumerate* (*udev_enumerate_unref_dylibloader_wrapper_libudev)(struct udev_enumerate*); +struct udev* (*udev_enumerate_get_udev_dylibloader_wrapper_libudev)(struct udev_enumerate*); +struct udev_enumerate* (*udev_enumerate_new_dylibloader_wrapper_libudev)(struct udev*); +int (*udev_enumerate_add_match_subsystem_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +int (*udev_enumerate_add_nomatch_subsystem_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +int (*udev_enumerate_add_match_sysattr_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*,const char*); +int (*udev_enumerate_add_nomatch_sysattr_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*,const char*); +int (*udev_enumerate_add_match_property_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*,const char*); +int (*udev_enumerate_add_match_sysname_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +int (*udev_enumerate_add_match_tag_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +int (*udev_enumerate_add_match_parent_dylibloader_wrapper_libudev)(struct udev_enumerate*,struct udev_device*); +int (*udev_enumerate_add_match_is_initialized_dylibloader_wrapper_libudev)(struct udev_enumerate*); +int (*udev_enumerate_add_syspath_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +int (*udev_enumerate_scan_devices_dylibloader_wrapper_libudev)(struct udev_enumerate*); +int (*udev_enumerate_scan_subsystems_dylibloader_wrapper_libudev)(struct udev_enumerate*); +struct udev_list_entry* (*udev_enumerate_get_list_entry_dylibloader_wrapper_libudev)(struct udev_enumerate*); +struct udev_queue* (*udev_queue_ref_dylibloader_wrapper_libudev)(struct udev_queue*); +struct udev_queue* (*udev_queue_unref_dylibloader_wrapper_libudev)(struct udev_queue*); +struct udev* (*udev_queue_get_udev_dylibloader_wrapper_libudev)(struct udev_queue*); +struct udev_queue* (*udev_queue_new_dylibloader_wrapper_libudev)(struct udev*); +unsigned long long int (*udev_queue_get_kernel_seqnum_dylibloader_wrapper_libudev)(struct udev_queue*); +unsigned long long int (*udev_queue_get_udev_seqnum_dylibloader_wrapper_libudev)(struct udev_queue*); +int (*udev_queue_get_udev_is_active_dylibloader_wrapper_libudev)(struct udev_queue*); +int (*udev_queue_get_queue_is_empty_dylibloader_wrapper_libudev)(struct udev_queue*); +int (*udev_queue_get_seqnum_is_finished_dylibloader_wrapper_libudev)(struct udev_queue*, unsigned long long int); +int (*udev_queue_get_seqnum_sequence_is_finished_dylibloader_wrapper_libudev)(struct udev_queue*, unsigned long long int, unsigned long long int); +int (*udev_queue_get_fd_dylibloader_wrapper_libudev)(struct udev_queue*); +int (*udev_queue_flush_dylibloader_wrapper_libudev)(struct udev_queue*); +struct udev_list_entry* (*udev_queue_get_queued_list_entry_dylibloader_wrapper_libudev)(struct udev_queue*); +struct udev_hwdb* (*udev_hwdb_new_dylibloader_wrapper_libudev)(struct udev*); +struct udev_hwdb* (*udev_hwdb_ref_dylibloader_wrapper_libudev)(struct udev_hwdb*); +struct udev_hwdb* (*udev_hwdb_unref_dylibloader_wrapper_libudev)(struct udev_hwdb*); +struct udev_list_entry* (*udev_hwdb_get_properties_list_entry_dylibloader_wrapper_libudev)(struct udev_hwdb*,const char*, unsigned); +int (*udev_util_encode_string_dylibloader_wrapper_libudev)(const char*, char*, size_t); +int initialize_libudev(int verbose) { + void *handle; + char *error; + handle = dlopen("libudev.so.1", RTLD_LAZY); + if (!handle) { + if (verbose) { + fprintf(stderr, "%s\n", dlerror()); + } + return(1); + } + dlerror(); +// udev_ref + *(void **) (&udev_ref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_ref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_unref + *(void **) (&udev_unref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_unref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_new + *(void **) (&udev_new_dylibloader_wrapper_libudev) = dlsym(handle, "udev_new"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_set_log_fn + *(void **) (&udev_set_log_fn_dylibloader_wrapper_libudev) = dlsym(handle, "udev_set_log_fn"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_get_log_priority + *(void **) (&udev_get_log_priority_dylibloader_wrapper_libudev) = dlsym(handle, "udev_get_log_priority"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_set_log_priority + *(void **) (&udev_set_log_priority_dylibloader_wrapper_libudev) = dlsym(handle, "udev_set_log_priority"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_get_userdata + *(void **) (&udev_get_userdata_dylibloader_wrapper_libudev) = dlsym(handle, "udev_get_userdata"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_set_userdata + *(void **) (&udev_set_userdata_dylibloader_wrapper_libudev) = dlsym(handle, "udev_set_userdata"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_list_entry_get_next + *(void **) (&udev_list_entry_get_next_dylibloader_wrapper_libudev) = dlsym(handle, "udev_list_entry_get_next"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_list_entry_get_by_name + *(void **) (&udev_list_entry_get_by_name_dylibloader_wrapper_libudev) = dlsym(handle, "udev_list_entry_get_by_name"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_list_entry_get_name + *(void **) (&udev_list_entry_get_name_dylibloader_wrapper_libudev) = dlsym(handle, "udev_list_entry_get_name"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_list_entry_get_value + *(void **) (&udev_list_entry_get_value_dylibloader_wrapper_libudev) = dlsym(handle, "udev_list_entry_get_value"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_ref + *(void **) (&udev_device_ref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_ref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_unref + *(void **) (&udev_device_unref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_unref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_udev + *(void **) (&udev_device_get_udev_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_udev"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_new_from_syspath + *(void **) (&udev_device_new_from_syspath_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_new_from_syspath"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_new_from_devnum + *(void **) (&udev_device_new_from_devnum_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_new_from_devnum"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_new_from_subsystem_sysname + *(void **) (&udev_device_new_from_subsystem_sysname_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_new_from_subsystem_sysname"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_new_from_device_id + *(void **) (&udev_device_new_from_device_id_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_new_from_device_id"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_new_from_environment + *(void **) (&udev_device_new_from_environment_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_new_from_environment"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_parent + *(void **) (&udev_device_get_parent_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_parent"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_parent_with_subsystem_devtype + *(void **) (&udev_device_get_parent_with_subsystem_devtype_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_parent_with_subsystem_devtype"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_devpath + *(void **) (&udev_device_get_devpath_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_devpath"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_subsystem + *(void **) (&udev_device_get_subsystem_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_subsystem"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_devtype + *(void **) (&udev_device_get_devtype_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_devtype"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_syspath + *(void **) (&udev_device_get_syspath_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_syspath"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_sysname + *(void **) (&udev_device_get_sysname_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_sysname"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_sysnum + *(void **) (&udev_device_get_sysnum_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_sysnum"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_devnode + *(void **) (&udev_device_get_devnode_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_devnode"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_is_initialized + *(void **) (&udev_device_get_is_initialized_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_is_initialized"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_devlinks_list_entry + *(void **) (&udev_device_get_devlinks_list_entry_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_devlinks_list_entry"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_properties_list_entry + *(void **) (&udev_device_get_properties_list_entry_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_properties_list_entry"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_tags_list_entry + *(void **) (&udev_device_get_tags_list_entry_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_tags_list_entry"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_sysattr_list_entry + *(void **) (&udev_device_get_sysattr_list_entry_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_sysattr_list_entry"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_property_value + *(void **) (&udev_device_get_property_value_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_property_value"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_driver + *(void **) (&udev_device_get_driver_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_driver"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_devnum + *(void **) (&udev_device_get_devnum_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_devnum"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_action + *(void **) (&udev_device_get_action_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_action"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_seqnum + *(void **) (&udev_device_get_seqnum_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_seqnum"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_usec_since_initialized + *(void **) (&udev_device_get_usec_since_initialized_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_usec_since_initialized"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_get_sysattr_value + *(void **) (&udev_device_get_sysattr_value_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_get_sysattr_value"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_set_sysattr_value + *(void **) (&udev_device_set_sysattr_value_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_set_sysattr_value"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_device_has_tag + *(void **) (&udev_device_has_tag_dylibloader_wrapper_libudev) = dlsym(handle, "udev_device_has_tag"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_ref + *(void **) (&udev_monitor_ref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_ref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_unref + *(void **) (&udev_monitor_unref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_unref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_get_udev + *(void **) (&udev_monitor_get_udev_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_get_udev"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_new_from_netlink + *(void **) (&udev_monitor_new_from_netlink_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_new_from_netlink"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_enable_receiving + *(void **) (&udev_monitor_enable_receiving_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_enable_receiving"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_set_receive_buffer_size + *(void **) (&udev_monitor_set_receive_buffer_size_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_set_receive_buffer_size"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_get_fd + *(void **) (&udev_monitor_get_fd_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_get_fd"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_receive_device + *(void **) (&udev_monitor_receive_device_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_receive_device"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_filter_add_match_subsystem_devtype + *(void **) (&udev_monitor_filter_add_match_subsystem_devtype_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_filter_add_match_subsystem_devtype"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_filter_add_match_tag + *(void **) (&udev_monitor_filter_add_match_tag_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_filter_add_match_tag"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_filter_update + *(void **) (&udev_monitor_filter_update_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_filter_update"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_monitor_filter_remove + *(void **) (&udev_monitor_filter_remove_dylibloader_wrapper_libudev) = dlsym(handle, "udev_monitor_filter_remove"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_ref + *(void **) (&udev_enumerate_ref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_ref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_unref + *(void **) (&udev_enumerate_unref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_unref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_get_udev + *(void **) (&udev_enumerate_get_udev_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_get_udev"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_new + *(void **) (&udev_enumerate_new_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_new"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_match_subsystem + *(void **) (&udev_enumerate_add_match_subsystem_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_match_subsystem"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_nomatch_subsystem + *(void **) (&udev_enumerate_add_nomatch_subsystem_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_nomatch_subsystem"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_match_sysattr + *(void **) (&udev_enumerate_add_match_sysattr_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_match_sysattr"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_nomatch_sysattr + *(void **) (&udev_enumerate_add_nomatch_sysattr_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_nomatch_sysattr"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_match_property + *(void **) (&udev_enumerate_add_match_property_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_match_property"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_match_sysname + *(void **) (&udev_enumerate_add_match_sysname_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_match_sysname"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_match_tag + *(void **) (&udev_enumerate_add_match_tag_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_match_tag"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_match_parent + *(void **) (&udev_enumerate_add_match_parent_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_match_parent"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_match_is_initialized + *(void **) (&udev_enumerate_add_match_is_initialized_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_match_is_initialized"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_add_syspath + *(void **) (&udev_enumerate_add_syspath_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_add_syspath"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_scan_devices + *(void **) (&udev_enumerate_scan_devices_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_scan_devices"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_scan_subsystems + *(void **) (&udev_enumerate_scan_subsystems_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_scan_subsystems"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_enumerate_get_list_entry + *(void **) (&udev_enumerate_get_list_entry_dylibloader_wrapper_libudev) = dlsym(handle, "udev_enumerate_get_list_entry"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_ref + *(void **) (&udev_queue_ref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_ref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_unref + *(void **) (&udev_queue_unref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_unref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_get_udev + *(void **) (&udev_queue_get_udev_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_get_udev"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_new + *(void **) (&udev_queue_new_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_new"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_get_kernel_seqnum + *(void **) (&udev_queue_get_kernel_seqnum_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_get_kernel_seqnum"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_get_udev_seqnum + *(void **) (&udev_queue_get_udev_seqnum_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_get_udev_seqnum"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_get_udev_is_active + *(void **) (&udev_queue_get_udev_is_active_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_get_udev_is_active"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_get_queue_is_empty + *(void **) (&udev_queue_get_queue_is_empty_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_get_queue_is_empty"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_get_seqnum_is_finished + *(void **) (&udev_queue_get_seqnum_is_finished_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_get_seqnum_is_finished"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_get_seqnum_sequence_is_finished + *(void **) (&udev_queue_get_seqnum_sequence_is_finished_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_get_seqnum_sequence_is_finished"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_get_fd + *(void **) (&udev_queue_get_fd_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_get_fd"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_flush + *(void **) (&udev_queue_flush_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_flush"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_queue_get_queued_list_entry + *(void **) (&udev_queue_get_queued_list_entry_dylibloader_wrapper_libudev) = dlsym(handle, "udev_queue_get_queued_list_entry"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_hwdb_new + *(void **) (&udev_hwdb_new_dylibloader_wrapper_libudev) = dlsym(handle, "udev_hwdb_new"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_hwdb_ref + *(void **) (&udev_hwdb_ref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_hwdb_ref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_hwdb_unref + *(void **) (&udev_hwdb_unref_dylibloader_wrapper_libudev) = dlsym(handle, "udev_hwdb_unref"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_hwdb_get_properties_list_entry + *(void **) (&udev_hwdb_get_properties_list_entry_dylibloader_wrapper_libudev) = dlsym(handle, "udev_hwdb_get_properties_list_entry"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +// udev_util_encode_string + *(void **) (&udev_util_encode_string_dylibloader_wrapper_libudev) = dlsym(handle, "udev_util_encode_string"); + if (verbose) { + error = dlerror(); + if (error != NULL) { + fprintf(stderr, "%s\n", error); + } + } +return 0; +} diff --git a/platform/linuxbsd/libudev-so_wrap.h b/platform/linuxbsd/libudev-so_wrap.h new file mode 100644 index 0000000000..dd43fd1191 --- /dev/null +++ b/platform/linuxbsd/libudev-so_wrap.h @@ -0,0 +1,378 @@ +#ifndef DYLIBLOAD_WRAPPER_LIBUDEV +#define DYLIBLOAD_WRAPPER_LIBUDEV +// This file is generated. Do not edit! +// see https://github.com/hpvb/dynload-wrapper for details +// generated by /home/hp/Projects/godot/pulse/generate-wrapper.py 0.3 on 2021-02-20 00:08:59 +// flags: /home/hp/Projects/godot/pulse/generate-wrapper.py --include /usr/include/libudev.h --sys-include <libudev.h> --soname libudev.so.1 --init-name libudev --omit-prefix gnu_ --output-header libudev-so_wrap.h --output-implementation libudev-so_wrap.c +// +#include <stdint.h> + +#define udev_ref udev_ref_dylibloader_orig_libudev +#define udev_unref udev_unref_dylibloader_orig_libudev +#define udev_new udev_new_dylibloader_orig_libudev +#define udev_set_log_fn udev_set_log_fn_dylibloader_orig_libudev +#define udev_get_log_priority udev_get_log_priority_dylibloader_orig_libudev +#define udev_set_log_priority udev_set_log_priority_dylibloader_orig_libudev +#define udev_get_userdata udev_get_userdata_dylibloader_orig_libudev +#define udev_set_userdata udev_set_userdata_dylibloader_orig_libudev +#define udev_list_entry_get_next udev_list_entry_get_next_dylibloader_orig_libudev +#define udev_list_entry_get_by_name udev_list_entry_get_by_name_dylibloader_orig_libudev +#define udev_list_entry_get_name udev_list_entry_get_name_dylibloader_orig_libudev +#define udev_list_entry_get_value udev_list_entry_get_value_dylibloader_orig_libudev +#define udev_device_ref udev_device_ref_dylibloader_orig_libudev +#define udev_device_unref udev_device_unref_dylibloader_orig_libudev +#define udev_device_get_udev udev_device_get_udev_dylibloader_orig_libudev +#define udev_device_new_from_syspath udev_device_new_from_syspath_dylibloader_orig_libudev +#define udev_device_new_from_devnum udev_device_new_from_devnum_dylibloader_orig_libudev +#define udev_device_new_from_subsystem_sysname udev_device_new_from_subsystem_sysname_dylibloader_orig_libudev +#define udev_device_new_from_device_id udev_device_new_from_device_id_dylibloader_orig_libudev +#define udev_device_new_from_environment udev_device_new_from_environment_dylibloader_orig_libudev +#define udev_device_get_parent udev_device_get_parent_dylibloader_orig_libudev +#define udev_device_get_parent_with_subsystem_devtype udev_device_get_parent_with_subsystem_devtype_dylibloader_orig_libudev +#define udev_device_get_devpath udev_device_get_devpath_dylibloader_orig_libudev +#define udev_device_get_subsystem udev_device_get_subsystem_dylibloader_orig_libudev +#define udev_device_get_devtype udev_device_get_devtype_dylibloader_orig_libudev +#define udev_device_get_syspath udev_device_get_syspath_dylibloader_orig_libudev +#define udev_device_get_sysname udev_device_get_sysname_dylibloader_orig_libudev +#define udev_device_get_sysnum udev_device_get_sysnum_dylibloader_orig_libudev +#define udev_device_get_devnode udev_device_get_devnode_dylibloader_orig_libudev +#define udev_device_get_is_initialized udev_device_get_is_initialized_dylibloader_orig_libudev +#define udev_device_get_devlinks_list_entry udev_device_get_devlinks_list_entry_dylibloader_orig_libudev +#define udev_device_get_properties_list_entry udev_device_get_properties_list_entry_dylibloader_orig_libudev +#define udev_device_get_tags_list_entry udev_device_get_tags_list_entry_dylibloader_orig_libudev +#define udev_device_get_sysattr_list_entry udev_device_get_sysattr_list_entry_dylibloader_orig_libudev +#define udev_device_get_property_value udev_device_get_property_value_dylibloader_orig_libudev +#define udev_device_get_driver udev_device_get_driver_dylibloader_orig_libudev +#define udev_device_get_devnum udev_device_get_devnum_dylibloader_orig_libudev +#define udev_device_get_action udev_device_get_action_dylibloader_orig_libudev +#define udev_device_get_seqnum udev_device_get_seqnum_dylibloader_orig_libudev +#define udev_device_get_usec_since_initialized udev_device_get_usec_since_initialized_dylibloader_orig_libudev +#define udev_device_get_sysattr_value udev_device_get_sysattr_value_dylibloader_orig_libudev +#define udev_device_set_sysattr_value udev_device_set_sysattr_value_dylibloader_orig_libudev +#define udev_device_has_tag udev_device_has_tag_dylibloader_orig_libudev +#define udev_monitor_ref udev_monitor_ref_dylibloader_orig_libudev +#define udev_monitor_unref udev_monitor_unref_dylibloader_orig_libudev +#define udev_monitor_get_udev udev_monitor_get_udev_dylibloader_orig_libudev +#define udev_monitor_new_from_netlink udev_monitor_new_from_netlink_dylibloader_orig_libudev +#define udev_monitor_enable_receiving udev_monitor_enable_receiving_dylibloader_orig_libudev +#define udev_monitor_set_receive_buffer_size udev_monitor_set_receive_buffer_size_dylibloader_orig_libudev +#define udev_monitor_get_fd udev_monitor_get_fd_dylibloader_orig_libudev +#define udev_monitor_receive_device udev_monitor_receive_device_dylibloader_orig_libudev +#define udev_monitor_filter_add_match_subsystem_devtype udev_monitor_filter_add_match_subsystem_devtype_dylibloader_orig_libudev +#define udev_monitor_filter_add_match_tag udev_monitor_filter_add_match_tag_dylibloader_orig_libudev +#define udev_monitor_filter_update udev_monitor_filter_update_dylibloader_orig_libudev +#define udev_monitor_filter_remove udev_monitor_filter_remove_dylibloader_orig_libudev +#define udev_enumerate_ref udev_enumerate_ref_dylibloader_orig_libudev +#define udev_enumerate_unref udev_enumerate_unref_dylibloader_orig_libudev +#define udev_enumerate_get_udev udev_enumerate_get_udev_dylibloader_orig_libudev +#define udev_enumerate_new udev_enumerate_new_dylibloader_orig_libudev +#define udev_enumerate_add_match_subsystem udev_enumerate_add_match_subsystem_dylibloader_orig_libudev +#define udev_enumerate_add_nomatch_subsystem udev_enumerate_add_nomatch_subsystem_dylibloader_orig_libudev +#define udev_enumerate_add_match_sysattr udev_enumerate_add_match_sysattr_dylibloader_orig_libudev +#define udev_enumerate_add_nomatch_sysattr udev_enumerate_add_nomatch_sysattr_dylibloader_orig_libudev +#define udev_enumerate_add_match_property udev_enumerate_add_match_property_dylibloader_orig_libudev +#define udev_enumerate_add_match_sysname udev_enumerate_add_match_sysname_dylibloader_orig_libudev +#define udev_enumerate_add_match_tag udev_enumerate_add_match_tag_dylibloader_orig_libudev +#define udev_enumerate_add_match_parent udev_enumerate_add_match_parent_dylibloader_orig_libudev +#define udev_enumerate_add_match_is_initialized udev_enumerate_add_match_is_initialized_dylibloader_orig_libudev +#define udev_enumerate_add_syspath udev_enumerate_add_syspath_dylibloader_orig_libudev +#define udev_enumerate_scan_devices udev_enumerate_scan_devices_dylibloader_orig_libudev +#define udev_enumerate_scan_subsystems udev_enumerate_scan_subsystems_dylibloader_orig_libudev +#define udev_enumerate_get_list_entry udev_enumerate_get_list_entry_dylibloader_orig_libudev +#define udev_queue_ref udev_queue_ref_dylibloader_orig_libudev +#define udev_queue_unref udev_queue_unref_dylibloader_orig_libudev +#define udev_queue_get_udev udev_queue_get_udev_dylibloader_orig_libudev +#define udev_queue_new udev_queue_new_dylibloader_orig_libudev +#define udev_queue_get_kernel_seqnum udev_queue_get_kernel_seqnum_dylibloader_orig_libudev +#define udev_queue_get_udev_seqnum udev_queue_get_udev_seqnum_dylibloader_orig_libudev +#define udev_queue_get_udev_is_active udev_queue_get_udev_is_active_dylibloader_orig_libudev +#define udev_queue_get_queue_is_empty udev_queue_get_queue_is_empty_dylibloader_orig_libudev +#define udev_queue_get_seqnum_is_finished udev_queue_get_seqnum_is_finished_dylibloader_orig_libudev +#define udev_queue_get_seqnum_sequence_is_finished udev_queue_get_seqnum_sequence_is_finished_dylibloader_orig_libudev +#define udev_queue_get_fd udev_queue_get_fd_dylibloader_orig_libudev +#define udev_queue_flush udev_queue_flush_dylibloader_orig_libudev +#define udev_queue_get_queued_list_entry udev_queue_get_queued_list_entry_dylibloader_orig_libudev +#define udev_hwdb_new udev_hwdb_new_dylibloader_orig_libudev +#define udev_hwdb_ref udev_hwdb_ref_dylibloader_orig_libudev +#define udev_hwdb_unref udev_hwdb_unref_dylibloader_orig_libudev +#define udev_hwdb_get_properties_list_entry udev_hwdb_get_properties_list_entry_dylibloader_orig_libudev +#define udev_util_encode_string udev_util_encode_string_dylibloader_orig_libudev +#include <libudev.h> +#undef udev_ref +#undef udev_unref +#undef udev_new +#undef udev_set_log_fn +#undef udev_get_log_priority +#undef udev_set_log_priority +#undef udev_get_userdata +#undef udev_set_userdata +#undef udev_list_entry_get_next +#undef udev_list_entry_get_by_name +#undef udev_list_entry_get_name +#undef udev_list_entry_get_value +#undef udev_device_ref +#undef udev_device_unref +#undef udev_device_get_udev +#undef udev_device_new_from_syspath +#undef udev_device_new_from_devnum +#undef udev_device_new_from_subsystem_sysname +#undef udev_device_new_from_device_id +#undef udev_device_new_from_environment +#undef udev_device_get_parent +#undef udev_device_get_parent_with_subsystem_devtype +#undef udev_device_get_devpath +#undef udev_device_get_subsystem +#undef udev_device_get_devtype +#undef udev_device_get_syspath +#undef udev_device_get_sysname +#undef udev_device_get_sysnum +#undef udev_device_get_devnode +#undef udev_device_get_is_initialized +#undef udev_device_get_devlinks_list_entry +#undef udev_device_get_properties_list_entry +#undef udev_device_get_tags_list_entry +#undef udev_device_get_sysattr_list_entry +#undef udev_device_get_property_value +#undef udev_device_get_driver +#undef udev_device_get_devnum +#undef udev_device_get_action +#undef udev_device_get_seqnum +#undef udev_device_get_usec_since_initialized +#undef udev_device_get_sysattr_value +#undef udev_device_set_sysattr_value +#undef udev_device_has_tag +#undef udev_monitor_ref +#undef udev_monitor_unref +#undef udev_monitor_get_udev +#undef udev_monitor_new_from_netlink +#undef udev_monitor_enable_receiving +#undef udev_monitor_set_receive_buffer_size +#undef udev_monitor_get_fd +#undef udev_monitor_receive_device +#undef udev_monitor_filter_add_match_subsystem_devtype +#undef udev_monitor_filter_add_match_tag +#undef udev_monitor_filter_update +#undef udev_monitor_filter_remove +#undef udev_enumerate_ref +#undef udev_enumerate_unref +#undef udev_enumerate_get_udev +#undef udev_enumerate_new +#undef udev_enumerate_add_match_subsystem +#undef udev_enumerate_add_nomatch_subsystem +#undef udev_enumerate_add_match_sysattr +#undef udev_enumerate_add_nomatch_sysattr +#undef udev_enumerate_add_match_property +#undef udev_enumerate_add_match_sysname +#undef udev_enumerate_add_match_tag +#undef udev_enumerate_add_match_parent +#undef udev_enumerate_add_match_is_initialized +#undef udev_enumerate_add_syspath +#undef udev_enumerate_scan_devices +#undef udev_enumerate_scan_subsystems +#undef udev_enumerate_get_list_entry +#undef udev_queue_ref +#undef udev_queue_unref +#undef udev_queue_get_udev +#undef udev_queue_new +#undef udev_queue_get_kernel_seqnum +#undef udev_queue_get_udev_seqnum +#undef udev_queue_get_udev_is_active +#undef udev_queue_get_queue_is_empty +#undef udev_queue_get_seqnum_is_finished +#undef udev_queue_get_seqnum_sequence_is_finished +#undef udev_queue_get_fd +#undef udev_queue_flush +#undef udev_queue_get_queued_list_entry +#undef udev_hwdb_new +#undef udev_hwdb_ref +#undef udev_hwdb_unref +#undef udev_hwdb_get_properties_list_entry +#undef udev_util_encode_string +#ifdef __cplusplus +extern "C" { +#endif +#define udev_ref udev_ref_dylibloader_wrapper_libudev +#define udev_unref udev_unref_dylibloader_wrapper_libudev +#define udev_new udev_new_dylibloader_wrapper_libudev +#define udev_set_log_fn udev_set_log_fn_dylibloader_wrapper_libudev +#define udev_get_log_priority udev_get_log_priority_dylibloader_wrapper_libudev +#define udev_set_log_priority udev_set_log_priority_dylibloader_wrapper_libudev +#define udev_get_userdata udev_get_userdata_dylibloader_wrapper_libudev +#define udev_set_userdata udev_set_userdata_dylibloader_wrapper_libudev +#define udev_list_entry_get_next udev_list_entry_get_next_dylibloader_wrapper_libudev +#define udev_list_entry_get_by_name udev_list_entry_get_by_name_dylibloader_wrapper_libudev +#define udev_list_entry_get_name udev_list_entry_get_name_dylibloader_wrapper_libudev +#define udev_list_entry_get_value udev_list_entry_get_value_dylibloader_wrapper_libudev +#define udev_device_ref udev_device_ref_dylibloader_wrapper_libudev +#define udev_device_unref udev_device_unref_dylibloader_wrapper_libudev +#define udev_device_get_udev udev_device_get_udev_dylibloader_wrapper_libudev +#define udev_device_new_from_syspath udev_device_new_from_syspath_dylibloader_wrapper_libudev +#define udev_device_new_from_devnum udev_device_new_from_devnum_dylibloader_wrapper_libudev +#define udev_device_new_from_subsystem_sysname udev_device_new_from_subsystem_sysname_dylibloader_wrapper_libudev +#define udev_device_new_from_device_id udev_device_new_from_device_id_dylibloader_wrapper_libudev +#define udev_device_new_from_environment udev_device_new_from_environment_dylibloader_wrapper_libudev +#define udev_device_get_parent udev_device_get_parent_dylibloader_wrapper_libudev +#define udev_device_get_parent_with_subsystem_devtype udev_device_get_parent_with_subsystem_devtype_dylibloader_wrapper_libudev +#define udev_device_get_devpath udev_device_get_devpath_dylibloader_wrapper_libudev +#define udev_device_get_subsystem udev_device_get_subsystem_dylibloader_wrapper_libudev +#define udev_device_get_devtype udev_device_get_devtype_dylibloader_wrapper_libudev +#define udev_device_get_syspath udev_device_get_syspath_dylibloader_wrapper_libudev +#define udev_device_get_sysname udev_device_get_sysname_dylibloader_wrapper_libudev +#define udev_device_get_sysnum udev_device_get_sysnum_dylibloader_wrapper_libudev +#define udev_device_get_devnode udev_device_get_devnode_dylibloader_wrapper_libudev +#define udev_device_get_is_initialized udev_device_get_is_initialized_dylibloader_wrapper_libudev +#define udev_device_get_devlinks_list_entry udev_device_get_devlinks_list_entry_dylibloader_wrapper_libudev +#define udev_device_get_properties_list_entry udev_device_get_properties_list_entry_dylibloader_wrapper_libudev +#define udev_device_get_tags_list_entry udev_device_get_tags_list_entry_dylibloader_wrapper_libudev +#define udev_device_get_sysattr_list_entry udev_device_get_sysattr_list_entry_dylibloader_wrapper_libudev +#define udev_device_get_property_value udev_device_get_property_value_dylibloader_wrapper_libudev +#define udev_device_get_driver udev_device_get_driver_dylibloader_wrapper_libudev +#define udev_device_get_devnum udev_device_get_devnum_dylibloader_wrapper_libudev +#define udev_device_get_action udev_device_get_action_dylibloader_wrapper_libudev +#define udev_device_get_seqnum udev_device_get_seqnum_dylibloader_wrapper_libudev +#define udev_device_get_usec_since_initialized udev_device_get_usec_since_initialized_dylibloader_wrapper_libudev +#define udev_device_get_sysattr_value udev_device_get_sysattr_value_dylibloader_wrapper_libudev +#define udev_device_set_sysattr_value udev_device_set_sysattr_value_dylibloader_wrapper_libudev +#define udev_device_has_tag udev_device_has_tag_dylibloader_wrapper_libudev +#define udev_monitor_ref udev_monitor_ref_dylibloader_wrapper_libudev +#define udev_monitor_unref udev_monitor_unref_dylibloader_wrapper_libudev +#define udev_monitor_get_udev udev_monitor_get_udev_dylibloader_wrapper_libudev +#define udev_monitor_new_from_netlink udev_monitor_new_from_netlink_dylibloader_wrapper_libudev +#define udev_monitor_enable_receiving udev_monitor_enable_receiving_dylibloader_wrapper_libudev +#define udev_monitor_set_receive_buffer_size udev_monitor_set_receive_buffer_size_dylibloader_wrapper_libudev +#define udev_monitor_get_fd udev_monitor_get_fd_dylibloader_wrapper_libudev +#define udev_monitor_receive_device udev_monitor_receive_device_dylibloader_wrapper_libudev +#define udev_monitor_filter_add_match_subsystem_devtype udev_monitor_filter_add_match_subsystem_devtype_dylibloader_wrapper_libudev +#define udev_monitor_filter_add_match_tag udev_monitor_filter_add_match_tag_dylibloader_wrapper_libudev +#define udev_monitor_filter_update udev_monitor_filter_update_dylibloader_wrapper_libudev +#define udev_monitor_filter_remove udev_monitor_filter_remove_dylibloader_wrapper_libudev +#define udev_enumerate_ref udev_enumerate_ref_dylibloader_wrapper_libudev +#define udev_enumerate_unref udev_enumerate_unref_dylibloader_wrapper_libudev +#define udev_enumerate_get_udev udev_enumerate_get_udev_dylibloader_wrapper_libudev +#define udev_enumerate_new udev_enumerate_new_dylibloader_wrapper_libudev +#define udev_enumerate_add_match_subsystem udev_enumerate_add_match_subsystem_dylibloader_wrapper_libudev +#define udev_enumerate_add_nomatch_subsystem udev_enumerate_add_nomatch_subsystem_dylibloader_wrapper_libudev +#define udev_enumerate_add_match_sysattr udev_enumerate_add_match_sysattr_dylibloader_wrapper_libudev +#define udev_enumerate_add_nomatch_sysattr udev_enumerate_add_nomatch_sysattr_dylibloader_wrapper_libudev +#define udev_enumerate_add_match_property udev_enumerate_add_match_property_dylibloader_wrapper_libudev +#define udev_enumerate_add_match_sysname udev_enumerate_add_match_sysname_dylibloader_wrapper_libudev +#define udev_enumerate_add_match_tag udev_enumerate_add_match_tag_dylibloader_wrapper_libudev +#define udev_enumerate_add_match_parent udev_enumerate_add_match_parent_dylibloader_wrapper_libudev +#define udev_enumerate_add_match_is_initialized udev_enumerate_add_match_is_initialized_dylibloader_wrapper_libudev +#define udev_enumerate_add_syspath udev_enumerate_add_syspath_dylibloader_wrapper_libudev +#define udev_enumerate_scan_devices udev_enumerate_scan_devices_dylibloader_wrapper_libudev +#define udev_enumerate_scan_subsystems udev_enumerate_scan_subsystems_dylibloader_wrapper_libudev +#define udev_enumerate_get_list_entry udev_enumerate_get_list_entry_dylibloader_wrapper_libudev +#define udev_queue_ref udev_queue_ref_dylibloader_wrapper_libudev +#define udev_queue_unref udev_queue_unref_dylibloader_wrapper_libudev +#define udev_queue_get_udev udev_queue_get_udev_dylibloader_wrapper_libudev +#define udev_queue_new udev_queue_new_dylibloader_wrapper_libudev +#define udev_queue_get_kernel_seqnum udev_queue_get_kernel_seqnum_dylibloader_wrapper_libudev +#define udev_queue_get_udev_seqnum udev_queue_get_udev_seqnum_dylibloader_wrapper_libudev +#define udev_queue_get_udev_is_active udev_queue_get_udev_is_active_dylibloader_wrapper_libudev +#define udev_queue_get_queue_is_empty udev_queue_get_queue_is_empty_dylibloader_wrapper_libudev +#define udev_queue_get_seqnum_is_finished udev_queue_get_seqnum_is_finished_dylibloader_wrapper_libudev +#define udev_queue_get_seqnum_sequence_is_finished udev_queue_get_seqnum_sequence_is_finished_dylibloader_wrapper_libudev +#define udev_queue_get_fd udev_queue_get_fd_dylibloader_wrapper_libudev +#define udev_queue_flush udev_queue_flush_dylibloader_wrapper_libudev +#define udev_queue_get_queued_list_entry udev_queue_get_queued_list_entry_dylibloader_wrapper_libudev +#define udev_hwdb_new udev_hwdb_new_dylibloader_wrapper_libudev +#define udev_hwdb_ref udev_hwdb_ref_dylibloader_wrapper_libudev +#define udev_hwdb_unref udev_hwdb_unref_dylibloader_wrapper_libudev +#define udev_hwdb_get_properties_list_entry udev_hwdb_get_properties_list_entry_dylibloader_wrapper_libudev +#define udev_util_encode_string udev_util_encode_string_dylibloader_wrapper_libudev +extern struct udev* (*udev_ref_dylibloader_wrapper_libudev)(struct udev*); +extern struct udev* (*udev_unref_dylibloader_wrapper_libudev)(struct udev*); +extern struct udev* (*udev_new_dylibloader_wrapper_libudev)( void); +extern void (*udev_set_log_fn_dylibloader_wrapper_libudev)(struct udev*, void*); +extern int (*udev_get_log_priority_dylibloader_wrapper_libudev)(struct udev*); +extern void (*udev_set_log_priority_dylibloader_wrapper_libudev)(struct udev*, int); +extern void* (*udev_get_userdata_dylibloader_wrapper_libudev)(struct udev*); +extern void (*udev_set_userdata_dylibloader_wrapper_libudev)(struct udev*, void*); +extern struct udev_list_entry* (*udev_list_entry_get_next_dylibloader_wrapper_libudev)(struct udev_list_entry*); +extern struct udev_list_entry* (*udev_list_entry_get_by_name_dylibloader_wrapper_libudev)(struct udev_list_entry*,const char*); +extern const char* (*udev_list_entry_get_name_dylibloader_wrapper_libudev)(struct udev_list_entry*); +extern const char* (*udev_list_entry_get_value_dylibloader_wrapper_libudev)(struct udev_list_entry*); +extern struct udev_device* (*udev_device_ref_dylibloader_wrapper_libudev)(struct udev_device*); +extern struct udev_device* (*udev_device_unref_dylibloader_wrapper_libudev)(struct udev_device*); +extern struct udev* (*udev_device_get_udev_dylibloader_wrapper_libudev)(struct udev_device*); +extern struct udev_device* (*udev_device_new_from_syspath_dylibloader_wrapper_libudev)(struct udev*,const char*); +extern struct udev_device* (*udev_device_new_from_devnum_dylibloader_wrapper_libudev)(struct udev*, char, dev_t); +extern struct udev_device* (*udev_device_new_from_subsystem_sysname_dylibloader_wrapper_libudev)(struct udev*,const char*,const char*); +extern struct udev_device* (*udev_device_new_from_device_id_dylibloader_wrapper_libudev)(struct udev*,const char*); +extern struct udev_device* (*udev_device_new_from_environment_dylibloader_wrapper_libudev)(struct udev*); +extern struct udev_device* (*udev_device_get_parent_dylibloader_wrapper_libudev)(struct udev_device*); +extern struct udev_device* (*udev_device_get_parent_with_subsystem_devtype_dylibloader_wrapper_libudev)(struct udev_device*,const char*,const char*); +extern const char* (*udev_device_get_devpath_dylibloader_wrapper_libudev)(struct udev_device*); +extern const char* (*udev_device_get_subsystem_dylibloader_wrapper_libudev)(struct udev_device*); +extern const char* (*udev_device_get_devtype_dylibloader_wrapper_libudev)(struct udev_device*); +extern const char* (*udev_device_get_syspath_dylibloader_wrapper_libudev)(struct udev_device*); +extern const char* (*udev_device_get_sysname_dylibloader_wrapper_libudev)(struct udev_device*); +extern const char* (*udev_device_get_sysnum_dylibloader_wrapper_libudev)(struct udev_device*); +extern const char* (*udev_device_get_devnode_dylibloader_wrapper_libudev)(struct udev_device*); +extern int (*udev_device_get_is_initialized_dylibloader_wrapper_libudev)(struct udev_device*); +extern struct udev_list_entry* (*udev_device_get_devlinks_list_entry_dylibloader_wrapper_libudev)(struct udev_device*); +extern struct udev_list_entry* (*udev_device_get_properties_list_entry_dylibloader_wrapper_libudev)(struct udev_device*); +extern struct udev_list_entry* (*udev_device_get_tags_list_entry_dylibloader_wrapper_libudev)(struct udev_device*); +extern struct udev_list_entry* (*udev_device_get_sysattr_list_entry_dylibloader_wrapper_libudev)(struct udev_device*); +extern const char* (*udev_device_get_property_value_dylibloader_wrapper_libudev)(struct udev_device*,const char*); +extern const char* (*udev_device_get_driver_dylibloader_wrapper_libudev)(struct udev_device*); +extern dev_t (*udev_device_get_devnum_dylibloader_wrapper_libudev)(struct udev_device*); +extern const char* (*udev_device_get_action_dylibloader_wrapper_libudev)(struct udev_device*); +extern unsigned long long int (*udev_device_get_seqnum_dylibloader_wrapper_libudev)(struct udev_device*); +extern unsigned long long int (*udev_device_get_usec_since_initialized_dylibloader_wrapper_libudev)(struct udev_device*); +extern const char* (*udev_device_get_sysattr_value_dylibloader_wrapper_libudev)(struct udev_device*,const char*); +extern int (*udev_device_set_sysattr_value_dylibloader_wrapper_libudev)(struct udev_device*,const char*,const char*); +extern int (*udev_device_has_tag_dylibloader_wrapper_libudev)(struct udev_device*,const char*); +extern struct udev_monitor* (*udev_monitor_ref_dylibloader_wrapper_libudev)(struct udev_monitor*); +extern struct udev_monitor* (*udev_monitor_unref_dylibloader_wrapper_libudev)(struct udev_monitor*); +extern struct udev* (*udev_monitor_get_udev_dylibloader_wrapper_libudev)(struct udev_monitor*); +extern struct udev_monitor* (*udev_monitor_new_from_netlink_dylibloader_wrapper_libudev)(struct udev*,const char*); +extern int (*udev_monitor_enable_receiving_dylibloader_wrapper_libudev)(struct udev_monitor*); +extern int (*udev_monitor_set_receive_buffer_size_dylibloader_wrapper_libudev)(struct udev_monitor*, int); +extern int (*udev_monitor_get_fd_dylibloader_wrapper_libudev)(struct udev_monitor*); +extern struct udev_device* (*udev_monitor_receive_device_dylibloader_wrapper_libudev)(struct udev_monitor*); +extern int (*udev_monitor_filter_add_match_subsystem_devtype_dylibloader_wrapper_libudev)(struct udev_monitor*,const char*,const char*); +extern int (*udev_monitor_filter_add_match_tag_dylibloader_wrapper_libudev)(struct udev_monitor*,const char*); +extern int (*udev_monitor_filter_update_dylibloader_wrapper_libudev)(struct udev_monitor*); +extern int (*udev_monitor_filter_remove_dylibloader_wrapper_libudev)(struct udev_monitor*); +extern struct udev_enumerate* (*udev_enumerate_ref_dylibloader_wrapper_libudev)(struct udev_enumerate*); +extern struct udev_enumerate* (*udev_enumerate_unref_dylibloader_wrapper_libudev)(struct udev_enumerate*); +extern struct udev* (*udev_enumerate_get_udev_dylibloader_wrapper_libudev)(struct udev_enumerate*); +extern struct udev_enumerate* (*udev_enumerate_new_dylibloader_wrapper_libudev)(struct udev*); +extern int (*udev_enumerate_add_match_subsystem_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +extern int (*udev_enumerate_add_nomatch_subsystem_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +extern int (*udev_enumerate_add_match_sysattr_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*,const char*); +extern int (*udev_enumerate_add_nomatch_sysattr_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*,const char*); +extern int (*udev_enumerate_add_match_property_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*,const char*); +extern int (*udev_enumerate_add_match_sysname_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +extern int (*udev_enumerate_add_match_tag_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +extern int (*udev_enumerate_add_match_parent_dylibloader_wrapper_libudev)(struct udev_enumerate*,struct udev_device*); +extern int (*udev_enumerate_add_match_is_initialized_dylibloader_wrapper_libudev)(struct udev_enumerate*); +extern int (*udev_enumerate_add_syspath_dylibloader_wrapper_libudev)(struct udev_enumerate*,const char*); +extern int (*udev_enumerate_scan_devices_dylibloader_wrapper_libudev)(struct udev_enumerate*); +extern int (*udev_enumerate_scan_subsystems_dylibloader_wrapper_libudev)(struct udev_enumerate*); +extern struct udev_list_entry* (*udev_enumerate_get_list_entry_dylibloader_wrapper_libudev)(struct udev_enumerate*); +extern struct udev_queue* (*udev_queue_ref_dylibloader_wrapper_libudev)(struct udev_queue*); +extern struct udev_queue* (*udev_queue_unref_dylibloader_wrapper_libudev)(struct udev_queue*); +extern struct udev* (*udev_queue_get_udev_dylibloader_wrapper_libudev)(struct udev_queue*); +extern struct udev_queue* (*udev_queue_new_dylibloader_wrapper_libudev)(struct udev*); +extern unsigned long long int (*udev_queue_get_kernel_seqnum_dylibloader_wrapper_libudev)(struct udev_queue*); +extern unsigned long long int (*udev_queue_get_udev_seqnum_dylibloader_wrapper_libudev)(struct udev_queue*); +extern int (*udev_queue_get_udev_is_active_dylibloader_wrapper_libudev)(struct udev_queue*); +extern int (*udev_queue_get_queue_is_empty_dylibloader_wrapper_libudev)(struct udev_queue*); +extern int (*udev_queue_get_seqnum_is_finished_dylibloader_wrapper_libudev)(struct udev_queue*, unsigned long long int); +extern int (*udev_queue_get_seqnum_sequence_is_finished_dylibloader_wrapper_libudev)(struct udev_queue*, unsigned long long int, unsigned long long int); +extern int (*udev_queue_get_fd_dylibloader_wrapper_libudev)(struct udev_queue*); +extern int (*udev_queue_flush_dylibloader_wrapper_libudev)(struct udev_queue*); +extern struct udev_list_entry* (*udev_queue_get_queued_list_entry_dylibloader_wrapper_libudev)(struct udev_queue*); +extern struct udev_hwdb* (*udev_hwdb_new_dylibloader_wrapper_libudev)(struct udev*); +extern struct udev_hwdb* (*udev_hwdb_ref_dylibloader_wrapper_libudev)(struct udev_hwdb*); +extern struct udev_hwdb* (*udev_hwdb_unref_dylibloader_wrapper_libudev)(struct udev_hwdb*); +extern struct udev_list_entry* (*udev_hwdb_get_properties_list_entry_dylibloader_wrapper_libudev)(struct udev_hwdb*,const char*, unsigned); +extern int (*udev_util_encode_string_dylibloader_wrapper_libudev)(const char*, char*, size_t); +int initialize_libudev(int verbose); +#ifdef __cplusplus +} +#endif +#endif diff --git a/platform/linuxbsd/logo.png b/platform/linuxbsd/logo.png Binary files differnew file mode 100644 index 0000000000..078654b757 --- /dev/null +++ b/platform/linuxbsd/logo.png diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp new file mode 100644 index 0000000000..c6a2fa5be7 --- /dev/null +++ b/platform/linuxbsd/os_linuxbsd.cpp @@ -0,0 +1,482 @@ +/*************************************************************************/ +/* os_linuxbsd.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#include "os_linuxbsd.h" + +#include "core/io/dir_access.h" +#include "main/main.h" + +#ifdef X11_ENABLED +#include "display_server_x11.h" +#endif + +#ifdef HAVE_MNTENT +#include <mntent.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include <dlfcn.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> + +void OS_LinuxBSD::initialize() { + crash_handler.initialize(); + + OS_Unix::initialize_core(); +} + +void OS_LinuxBSD::initialize_joypads() { +#ifdef JOYDEV_ENABLED + joypad = memnew(JoypadLinux(Input::get_singleton())); +#endif +} + +String OS_LinuxBSD::get_unique_id() const { + static String machine_id; + if (machine_id.is_empty()) { + if (FileAccess *f = FileAccess::open("/etc/machine-id", FileAccess::READ)) { + while (machine_id.is_empty() && !f->eof_reached()) { + machine_id = f->get_line().strip_edges(); + } + f->close(); + memdelete(f); + } + } + return machine_id; +} + +void OS_LinuxBSD::finalize() { + if (main_loop) { + memdelete(main_loop); + } + main_loop = nullptr; + +#ifdef ALSAMIDI_ENABLED + driver_alsamidi.close(); +#endif + +#ifdef JOYDEV_ENABLED + if (joypad) { + memdelete(joypad); + } +#endif +} + +MainLoop *OS_LinuxBSD::get_main_loop() const { + return main_loop; +} + +void OS_LinuxBSD::delete_main_loop() { + if (main_loop) { + memdelete(main_loop); + } + main_loop = nullptr; +} + +void OS_LinuxBSD::set_main_loop(MainLoop *p_main_loop) { + main_loop = p_main_loop; +} + +String OS_LinuxBSD::get_name() const { +#ifdef __linux__ + return "Linux"; +#elif defined(__FreeBSD__) + return "FreeBSD"; +#elif defined(__NetBSD__) + return "NetBSD"; +#elif defined(__OpenBSD__) + return "OpenBSD"; +#else + return "BSD"; +#endif +} + +Error OS_LinuxBSD::shell_open(String p_uri) { + Error ok; + int err_code; + List<String> args; + args.push_back(p_uri); + + // Agnostic + ok = execute("xdg-open", args, nullptr, &err_code); + if (ok == OK && !err_code) { + return OK; + } else if (err_code == 2) { + return ERR_FILE_NOT_FOUND; + } + // GNOME + args.push_front("open"); // The command is `gio open`, so we need to add it to args + ok = execute("gio", args, nullptr, &err_code); + if (ok == OK && !err_code) { + return OK; + } else if (err_code == 2) { + return ERR_FILE_NOT_FOUND; + } + args.pop_front(); + ok = execute("gvfs-open", args, nullptr, &err_code); + if (ok == OK && !err_code) { + return OK; + } else if (err_code == 2) { + return ERR_FILE_NOT_FOUND; + } + // KDE + ok = execute("kde-open5", args, nullptr, &err_code); + if (ok == OK && !err_code) { + return OK; + } + ok = execute("kde-open", args, nullptr, &err_code); + return !err_code ? ok : FAILED; +} + +bool OS_LinuxBSD::_check_internal_feature_support(const String &p_feature) { + return p_feature == "pc"; +} + +String OS_LinuxBSD::get_config_path() const { + if (has_environment("XDG_CONFIG_HOME")) { + if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) { + return get_environment("XDG_CONFIG_HOME"); + } else { + WARN_PRINT_ONCE("`XDG_CONFIG_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.config` or `.` per the XDG Base Directory specification."); + return has_environment("HOME") ? get_environment("HOME").plus_file(".config") : "."; + } + } else if (has_environment("HOME")) { + return get_environment("HOME").plus_file(".config"); + } else { + return "."; + } +} + +String OS_LinuxBSD::get_data_path() const { + if (has_environment("XDG_DATA_HOME")) { + if (get_environment("XDG_DATA_HOME").is_absolute_path()) { + return get_environment("XDG_DATA_HOME"); + } else { + WARN_PRINT_ONCE("`XDG_DATA_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.local/share` or `get_config_path()` per the XDG Base Directory specification."); + return has_environment("HOME") ? get_environment("HOME").plus_file(".local/share") : get_config_path(); + } + } else if (has_environment("HOME")) { + return get_environment("HOME").plus_file(".local/share"); + } else { + return get_config_path(); + } +} + +String OS_LinuxBSD::get_cache_path() const { + if (has_environment("XDG_CACHE_HOME")) { + if (get_environment("XDG_CACHE_HOME").is_absolute_path()) { + return get_environment("XDG_CACHE_HOME"); + } else { + WARN_PRINT_ONCE("`XDG_CACHE_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.cache` or `get_config_path()` per the XDG Base Directory specification."); + return has_environment("HOME") ? get_environment("HOME").plus_file(".cache") : get_config_path(); + } + } else if (has_environment("HOME")) { + return get_environment("HOME").plus_file(".cache"); + } else { + return get_config_path(); + } +} + +String OS_LinuxBSD::get_system_dir(SystemDir p_dir) const { + String xdgparam; + + switch (p_dir) { + case SYSTEM_DIR_DESKTOP: { + xdgparam = "DESKTOP"; + } break; + case SYSTEM_DIR_DCIM: { + xdgparam = "PICTURES"; + + } break; + case SYSTEM_DIR_DOCUMENTS: { + xdgparam = "DOCUMENTS"; + + } break; + case SYSTEM_DIR_DOWNLOADS: { + xdgparam = "DOWNLOAD"; + + } break; + case SYSTEM_DIR_MOVIES: { + xdgparam = "VIDEOS"; + + } break; + case SYSTEM_DIR_MUSIC: { + xdgparam = "MUSIC"; + + } break; + case SYSTEM_DIR_PICTURES: { + xdgparam = "PICTURES"; + + } break; + case SYSTEM_DIR_RINGTONES: { + xdgparam = "MUSIC"; + + } break; + } + + String pipe; + List<String> arg; + arg.push_back(xdgparam); + Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, &pipe); + if (err != OK) { + return "."; + } + return pipe.strip_edges(); +} + +void OS_LinuxBSD::run() { + force_quit = false; + + if (!main_loop) { + return; + } + + main_loop->initialize(); + + //uint64_t last_ticks=get_ticks_usec(); + + //int frames=0; + //uint64_t frame=0; + + while (!force_quit) { + DisplayServer::get_singleton()->process_events(); // get rid of pending events +#ifdef JOYDEV_ENABLED + joypad->process_joypads(); +#endif + if (Main::iteration()) { + break; + } + }; + + main_loop->finalize(); +} + +void OS_LinuxBSD::disable_crash_handler() { + crash_handler.disable(); +} + +bool OS_LinuxBSD::is_disable_crash_handler() const { + return crash_handler.is_disabled(); +} + +static String get_mountpoint(const String &p_path) { + struct stat s; + if (stat(p_path.utf8().get_data(), &s)) { + return ""; + } + +#ifdef HAVE_MNTENT + dev_t dev = s.st_dev; + FILE *fd = setmntent("/proc/mounts", "r"); + if (!fd) { + return ""; + } + + struct mntent mnt; + char buf[1024]; + size_t buflen = 1024; + while (getmntent_r(fd, &mnt, buf, buflen)) { + if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) { + endmntent(fd); + return String(mnt.mnt_dir); + } + } + + endmntent(fd); +#endif + return ""; +} + +Error OS_LinuxBSD::move_to_trash(const String &p_path) { + int err_code; + List<String> args; + args.push_back(p_path); + args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args. + Error result = execute("gio", args, nullptr, &err_code); // For GNOME based machines. + if (result == OK && !err_code) { + return OK; + } else if (err_code == 2) { + return ERR_FILE_NOT_FOUND; + } + + args.pop_front(); + args.push_front("move"); + args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`. + result = execute("kioclient5", args, nullptr, &err_code); // For KDE based machines. + if (result == OK && !err_code) { + return OK; + } else if (err_code == 2) { + return ERR_FILE_NOT_FOUND; + } + + args.pop_front(); + args.pop_back(); + result = execute("gvfs-trash", args, nullptr, &err_code); // For older Linux machines. + if (result == OK && !err_code) { + return OK; + } else if (err_code == 2) { + return ERR_FILE_NOT_FOUND; + } + + // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually. + String trash_path = ""; + String mnt = get_mountpoint(p_path); + + // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can. + if (mnt != "") { + String path(mnt + "/.Trash-" + itos(getuid())); + struct stat s; + if (!stat(path.utf8().get_data(), &s)) { + trash_path = path; + } + } + + // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can. + if (trash_path == "") { + char *dhome = getenv("XDG_DATA_HOME"); + if (dhome) { + trash_path = String(dhome) + "/Trash"; + } + } + + // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can. + if (trash_path == "") { + char *home = getenv("HOME"); + if (home) { + trash_path = String(home) + "/.local/share/Trash"; + } + } + + // Issue an error if none of the previous locations is appropriate for the trash can. + ERR_FAIL_COND_V_MSG(trash_path == "", FAILED, "Could not determine the trash can location"); + + // Create needed directories for decided trash can location. + { + DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Error err = dir_access->make_dir_recursive(trash_path); + + // Issue an error if trash can is not created proprely. + ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\""); + err = dir_access->make_dir_recursive(trash_path + "/files"); + ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"/files"); + err = dir_access->make_dir_recursive(trash_path + "/info"); + ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"/info"); + memdelete(dir_access); + } + + // The trash can is successfully created, now we check that we don't exceed our file name length limit. + // If the file name is too long trim it so we can add the identifying number and ".trashinfo". + // Assumes that the file name length limit is 255 characters. + String file_name = basename(p_path.utf8().get_data()); + if (file_name.length() > 240) { + file_name = file_name.substr(0, file_name.length() - 15); + } + + String dest_path = trash_path + "/files/" + file_name; + struct stat buff; + int id_number = 0; + String fn = file_name; + + // Checks if a resource with the same name already exist in the trash can, + // if there is, add an identifying number to our resource's name. + while (stat(dest_path.utf8().get_data(), &buff) == 0) { + id_number++; + + // Added a limit to check for identically named files already on the trash can + // if there are too many it could make the editor unresponsive. + ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can."); + fn = file_name + "." + itos(id_number); + dest_path = trash_path + "/files/" + fn; + } + file_name = fn; + + // Generates the .trashinfo file + OS::Date date = OS::get_singleton()->get_date(false); + OS::Time time = OS::get_singleton()->get_time(false); + String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", date.year, date.month, date.day, time.hour, time.minute); + timestamp = vformat("%s%02d", timestamp, time.second); // vformat only supports up to 6 arguments. + String trash_info = "[Trash Info]\nPath=" + p_path.uri_encode() + "\nDeletionDate=" + timestamp + "\n"; + { + Error err; + FileAccess *file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err); + ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file:" + trash_path + "/info/" + file_name + ".trashinfo"); + file->store_string(trash_info); + file->close(); + + // Rename our resource before moving it to the trash can. + DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + err = dir_access->rename(p_path, p_path.get_base_dir() + "/" + file_name); + ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + p_path + "\""); + memdelete(dir_access); + } + + // Move the given resource to the trash can. + // Do not use DirAccess:rename() because it can't move files across multiple mountpoints. + List<String> mv_args; + mv_args.push_back(p_path.get_base_dir() + "/" + file_name); + mv_args.push_back(trash_path + "/files"); + { + int retval; + Error err = execute("mv", mv_args, nullptr, &retval); + + // Issue an error if "mv" failed to move the given resource to the trash can. + if (err != OK || retval != 0) { + ERR_PRINT("move_to_trash: Could not move the resource \"" + p_path + "\" to the trash can \"" + trash_path + "/files\""); + DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + err = dir_access->rename(p_path.get_base_dir() + "/" + file_name, p_path); + memdelete(dir_access); + ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename " + p_path.get_base_dir() + "/" + file_name + " back to its original name:" + p_path); + return FAILED; + } + } + return OK; +} + +OS_LinuxBSD::OS_LinuxBSD() { + main_loop = nullptr; + force_quit = false; + +#ifdef PULSEAUDIO_ENABLED + AudioDriverManager::add_driver(&driver_pulseaudio); +#endif + +#ifdef ALSA_ENABLED + AudioDriverManager::add_driver(&driver_alsa); +#endif + +#ifdef X11_ENABLED + DisplayServerX11::register_x11_driver(); +#endif +} diff --git a/platform/linuxbsd/os_linuxbsd.h b/platform/linuxbsd/os_linuxbsd.h new file mode 100644 index 0000000000..b6cf93c551 --- /dev/null +++ b/platform/linuxbsd/os_linuxbsd.h @@ -0,0 +1,105 @@ +/*************************************************************************/ +/* os_linuxbsd.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifndef OS_LINUXBSD_H +#define OS_LINUXBSD_H + +#include "core/input/input.h" +#include "crash_handler_linuxbsd.h" +#include "drivers/alsa/audio_driver_alsa.h" +#include "drivers/alsamidi/midi_driver_alsamidi.h" +#include "drivers/pulseaudio/audio_driver_pulseaudio.h" +#include "drivers/unix/os_unix.h" +#include "joypad_linux.h" +#include "servers/audio_server.h" +#include "servers/rendering/renderer_compositor.h" +#include "servers/rendering_server.h" + +class OS_LinuxBSD : public OS_Unix { + virtual void delete_main_loop() override; + + bool force_quit; + +#ifdef JOYDEV_ENABLED + JoypadLinux *joypad = nullptr; +#endif + +#ifdef ALSA_ENABLED + AudioDriverALSA driver_alsa; +#endif + +#ifdef ALSAMIDI_ENABLED + MIDIDriverALSAMidi driver_alsamidi; +#endif + +#ifdef PULSEAUDIO_ENABLED + AudioDriverPulseAudio driver_pulseaudio; +#endif + + CrashHandler crash_handler; + + MainLoop *main_loop; + +protected: + virtual void initialize() override; + virtual void finalize() override; + + virtual void initialize_joypads() override; + + virtual void set_main_loop(MainLoop *p_main_loop) override; + +public: + virtual String get_name() const override; + + virtual MainLoop *get_main_loop() const override; + + virtual String get_config_path() const override; + virtual String get_data_path() const override; + virtual String get_cache_path() const override; + + virtual String get_system_dir(SystemDir p_dir) const override; + + virtual Error shell_open(String p_uri) override; + + virtual String get_unique_id() const override; + + virtual bool _check_internal_feature_support(const String &p_feature) override; + + void run(); + + virtual void disable_crash_handler() override; + virtual bool is_disable_crash_handler() const override; + + virtual Error move_to_trash(const String &p_path) override; + + OS_LinuxBSD(); +}; + +#endif diff --git a/platform/linuxbsd/pck_embed.ld b/platform/linuxbsd/pck_embed.ld new file mode 100644 index 0000000000..57a1994043 --- /dev/null +++ b/platform/linuxbsd/pck_embed.ld @@ -0,0 +1,10 @@ +SECTIONS +{ + /* Add a zero-sized section; the exporter will patch it to enclose the data appended to the executable (embedded PCK) */ + pck 0 (INFO) : + { + /* binutils >= 2.30 allow it being zero-sized, but needs something between the braces to keep the section */ + . = ALIGN(8); + } +} +INSERT AFTER .rodata; diff --git a/platform/linuxbsd/pck_embed.legacy.ld b/platform/linuxbsd/pck_embed.legacy.ld new file mode 100644 index 0000000000..a23013ba7a --- /dev/null +++ b/platform/linuxbsd/pck_embed.legacy.ld @@ -0,0 +1,10 @@ +SECTIONS +{ + /* The exporter will patch this section to enclose the data appended to the executable (embedded PCK) */ + pck 0 (INFO) : AT ( ADDR (.rodata) + SIZEOF (.rodata) ) + { + /* binutils < 2.30 need some actual content for the linker not to discard the section */ + BYTE(0); + } +} +INSERT AFTER .rodata; diff --git a/platform/linuxbsd/platform_config.h b/platform/linuxbsd/platform_config.h new file mode 100644 index 0000000000..3195d08935 --- /dev/null +++ b/platform/linuxbsd/platform_config.h @@ -0,0 +1,45 @@ +/*************************************************************************/ +/* platform_config.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifdef __linux__ +#include <alloca.h> +#endif + +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) +#include <stdlib.h> // alloca +// FreeBSD and OpenBSD use pthread_set_name_np, while other platforms, +// include NetBSD, use pthread_setname_np. NetBSD's version however requires +// a different format, we handle this directly in thread_posix. +#ifdef __NetBSD__ +#define PTHREAD_NETBSD_SET_NAME +#else +#define PTHREAD_BSD_SET_NAME +#endif +#endif diff --git a/platform/linuxbsd/platform_linuxbsd_builders.py b/platform/linuxbsd/platform_linuxbsd_builders.py new file mode 100644 index 0000000000..58234f3748 --- /dev/null +++ b/platform/linuxbsd/platform_linuxbsd_builders.py @@ -0,0 +1,17 @@ +"""Functions used to generate source files during build time + +All such functions are invoked in a subprocess on Windows to prevent build flakiness. + +""" +import os +from platform_methods import subprocess_main + + +def make_debug_linuxbsd(target, source, env): + os.system("objcopy --only-keep-debug {0} {0}.debugsymbols".format(target[0])) + os.system("strip --strip-debug --strip-unneeded {0}".format(target[0])) + os.system("objcopy --add-gnu-debuglink={0}.debugsymbols {0}".format(target[0])) + + +if __name__ == "__main__": + subprocess_main(globals()) diff --git a/platform/linuxbsd/vulkan_context_x11.cpp b/platform/linuxbsd/vulkan_context_x11.cpp new file mode 100644 index 0000000000..021db630e0 --- /dev/null +++ b/platform/linuxbsd/vulkan_context_x11.cpp @@ -0,0 +1,56 @@ +/*************************************************************************/ +/* vulkan_context_x11.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#include "vulkan_context_x11.h" +#include <vulkan/vulkan_xlib.h> + +const char *VulkanContextX11::_get_platform_surface_extension() const { + return VK_KHR_XLIB_SURFACE_EXTENSION_NAME; +} + +Error VulkanContextX11::window_create(DisplayServer::WindowID p_window_id, ::Window p_window, Display *p_display, int p_width, int p_height) { + VkXlibSurfaceCreateInfoKHR createInfo; + createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; + createInfo.pNext = nullptr; + createInfo.flags = 0; + createInfo.dpy = p_display; + createInfo.window = p_window; + + VkSurfaceKHR surface; + VkResult err = vkCreateXlibSurfaceKHR(_get_instance(), &createInfo, nullptr, &surface); + ERR_FAIL_COND_V(err, ERR_CANT_CREATE); + return _window_create(p_window_id, surface, p_width, p_height); +} + +VulkanContextX11::VulkanContextX11() { +} + +VulkanContextX11::~VulkanContextX11() { +} diff --git a/platform/linuxbsd/vulkan_context_x11.h b/platform/linuxbsd/vulkan_context_x11.h new file mode 100644 index 0000000000..26472444ad --- /dev/null +++ b/platform/linuxbsd/vulkan_context_x11.h @@ -0,0 +1,47 @@ +/*************************************************************************/ +/* vulkan_context_x11.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 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. */ +/*************************************************************************/ + +#ifndef VULKAN_DEVICE_X11_H +#define VULKAN_DEVICE_X11_H + +#include "drivers/vulkan/vulkan_context.h" +#include <X11/Xlib.h> + +class VulkanContextX11 : public VulkanContext { + virtual const char *_get_platform_surface_extension() const; + +public: + Error window_create(DisplayServer::WindowID p_window_id, ::Window p_window, Display *p_display, int p_width, int p_height); + + VulkanContextX11(); + ~VulkanContextX11(); +}; + +#endif // VULKAN_DEVICE_X11_H |