RmlUi_Backend_X11_GL2.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "RmlUi_Backend.h"
  29. #include "RmlUi_Include_Xlib.h"
  30. #include "RmlUi_Platform_X11.h"
  31. #include "RmlUi_Renderer_GL2.h"
  32. #include <RmlUi/Core/Context.h>
  33. #include <RmlUi/Core/Debug.h>
  34. #include <RmlUi/Core/Log.h>
  35. #include <GL/gl.h>
  36. #include <GL/glext.h>
  37. #include <GL/glx.h>
  38. #include <X11/Xlib.h>
  39. #include <X11/cursorfont.h>
  40. #include <X11/extensions/xf86vmode.h>
  41. #include <cmath>
  42. #include <limits.h>
  43. #include <stdarg.h>
  44. #include <stdio.h>
  45. #include <string.h>
  46. #include <sys/stat.h>
  47. #include <sys/time.h>
  48. #include <sys/types.h>
  49. #include <time.h>
  50. #include <unistd.h>
  51. // Attach the OpenGL context to the window.
  52. static bool AttachToNative(GLXContext& out_gl_context, Display* display, Window window, XVisualInfo* visual_info)
  53. {
  54. GLXContext gl_context = glXCreateContext(display, visual_info, nullptr, GL_TRUE);
  55. if (!gl_context)
  56. return false;
  57. if (!glXMakeCurrent(display, window, gl_context))
  58. return false;
  59. if (!glXIsDirect(display, gl_context))
  60. Rml::Log::Message(Rml::Log::LT_INFO, "OpenGL context does not support direct rendering; performance is likely to be poor.");
  61. out_gl_context = gl_context;
  62. Window root_window;
  63. int x, y;
  64. unsigned int width, height;
  65. unsigned int border_width, depth;
  66. XGetGeometry(display, window, &root_window, &x, &y, &width, &height, &border_width, &depth);
  67. return true;
  68. }
  69. // Shutdown the OpenGL context.
  70. static void DetachFromNative(GLXContext gl_context, Display* display)
  71. {
  72. glXMakeCurrent(display, 0L, nullptr);
  73. glXDestroyContext(display, gl_context);
  74. }
  75. /**
  76. Global data used by this backend.
  77. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  78. */
  79. struct BackendData {
  80. BackendData(Display* display) : system_interface(display) {}
  81. SystemInterface_X11 system_interface;
  82. RenderInterface_GL2 render_interface;
  83. Display* display = nullptr;
  84. Window window = 0;
  85. GLXContext gl_context = nullptr;
  86. bool running = true;
  87. };
  88. static Rml::UniquePtr<BackendData> data;
  89. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  90. {
  91. RMLUI_ASSERT(!data);
  92. Display* display = XOpenDisplay(0);
  93. if (!display)
  94. return false;
  95. int screen = XDefaultScreen(display);
  96. // Fetch an appropriate 32-bit visual interface.
  97. int attribute_list[] = {GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8,
  98. 0L};
  99. XVisualInfo* visual_info = glXChooseVisual(display, screen, attribute_list);
  100. if (!visual_info)
  101. return false;
  102. // Build up our window attributes.
  103. XSetWindowAttributes window_attributes;
  104. window_attributes.colormap = XCreateColormap(display, RootWindow(display, visual_info->screen), visual_info->visual, AllocNone);
  105. window_attributes.border_pixel = 0;
  106. window_attributes.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask;
  107. // Create the window.
  108. Window window = XCreateWindow(display, RootWindow(display, visual_info->screen), 0, 0, width, height, 0, visual_info->depth, InputOutput,
  109. visual_info->visual, CWBorderPixel | CWColormap | CWEventMask, &window_attributes);
  110. // Handle delete events in windowed mode.
  111. Atom delete_atom = XInternAtom(display, "WM_DELETE_WINDOW", True);
  112. XSetWMProtocols(display, window, &delete_atom, 1);
  113. // Capture the events we're interested in.
  114. XSelectInput(display, window,
  115. KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | LeaveWindowMask | PointerMotionMask | StructureNotifyMask);
  116. if (!allow_resize)
  117. {
  118. // Force the window to remain at the fixed size by asking the window manager nicely, it may choose to ignore us
  119. XSizeHints* win_size_hints = XAllocSizeHints(); // Allocate a size hint structure
  120. if (!win_size_hints)
  121. {
  122. Rml::Log::Message(Rml::Log::LT_ERROR, "XAllocSizeHints - out of memory");
  123. }
  124. else
  125. {
  126. // Initialize the structure and specify which hints will be providing
  127. win_size_hints->flags = PSize | PMinSize | PMaxSize;
  128. // Set the sizes we want the window manager to use
  129. win_size_hints->base_width = width;
  130. win_size_hints->base_height = height;
  131. win_size_hints->min_width = width;
  132. win_size_hints->min_height = height;
  133. win_size_hints->max_width = width;
  134. win_size_hints->max_height = height;
  135. // Pass the size hints to the window manager.
  136. XSetWMNormalHints(display, window, win_size_hints);
  137. // Free the size buffer
  138. XFree(win_size_hints);
  139. }
  140. }
  141. // Set the window title and show the window.
  142. XSetStandardProperties(display, window, window_name, "", 0L, nullptr, 0, nullptr);
  143. XMapRaised(display, window);
  144. GLXContext gl_context = {};
  145. if (!AttachToNative(gl_context, display, window, visual_info))
  146. return false;
  147. data = Rml::MakeUnique<BackendData>(display);
  148. data->display = display;
  149. data->window = window;
  150. data->gl_context = gl_context;
  151. data->system_interface.SetWindow(window);
  152. data->render_interface.SetViewport(width, height);
  153. return true;
  154. }
  155. void Backend::Shutdown()
  156. {
  157. RMLUI_ASSERT(data);
  158. DetachFromNative(data->gl_context, data->display);
  159. XCloseDisplay(data->display);
  160. data.reset();
  161. }
  162. Rml::SystemInterface* Backend::GetSystemInterface()
  163. {
  164. RMLUI_ASSERT(data);
  165. return &data->system_interface;
  166. }
  167. Rml::RenderInterface* Backend::GetRenderInterface()
  168. {
  169. RMLUI_ASSERT(data);
  170. return &data->render_interface;
  171. }
  172. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  173. {
  174. RMLUI_ASSERT(data && context);
  175. Display* display = data->display;
  176. bool result = data->running;
  177. data->running = true;
  178. if (power_save && XPending(display) == 0)
  179. {
  180. int display_fd = ConnectionNumber(display);
  181. fd_set fds{};
  182. FD_ZERO(&fds);
  183. FD_SET(display_fd, &fds);
  184. double timeout = Rml::Math::Min(context->GetNextUpdateDelay(), 10.0);
  185. struct timeval tv {};
  186. double seconds;
  187. tv.tv_usec = std::modf(timeout, &seconds) * 1000000.0;
  188. tv.tv_sec = seconds;
  189. int ready_fd_count;
  190. do
  191. {
  192. ready_fd_count = select(display_fd + 1, &fds, NULL, NULL, &tv);
  193. // We don't care about the return value as long as select didn't error out
  194. RMLUI_ASSERT(ready_fd_count >= 0);
  195. } while (XPending(display) == 0 && ready_fd_count != 0);
  196. }
  197. while (XPending(display) > 0)
  198. {
  199. XEvent ev;
  200. XNextEvent(display, &ev);
  201. switch (ev.type)
  202. {
  203. case ClientMessage:
  204. {
  205. // The only message we register for is WM_DELETE_WINDOW, so if we receive a client message then the window has been closed.
  206. char* event_type = XGetAtomName(display, ev.xclient.message_type);
  207. if (strcmp(event_type, "WM_PROTOCOLS") == 0)
  208. data->running = false;
  209. XFree(event_type);
  210. event_type = nullptr;
  211. }
  212. break;
  213. case ConfigureNotify:
  214. {
  215. int x = ev.xconfigure.width;
  216. int y = ev.xconfigure.height;
  217. context->SetDimensions({x, y});
  218. data->render_interface.SetViewport(x, y);
  219. }
  220. break;
  221. case KeyPress:
  222. {
  223. Rml::Input::KeyIdentifier key = RmlX11::ConvertKey(display, ev.xkey.keycode);
  224. const int key_modifier = RmlX11::GetKeyModifierState(ev.xkey.state);
  225. const float native_dp_ratio = 1.f;
  226. // See if we have any global shortcuts that take priority over the context.
  227. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  228. break;
  229. // Otherwise, hand the event over to the context by calling the input handler as normal.
  230. if (!RmlX11::HandleInputEvent(context, display, ev))
  231. break;
  232. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  233. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  234. break;
  235. }
  236. break;
  237. case SelectionRequest:
  238. {
  239. data->system_interface.HandleSelectionRequest(ev);
  240. }
  241. break;
  242. default:
  243. {
  244. // Pass unhandled events to the platform layer's input handler.
  245. RmlX11::HandleInputEvent(context, display, ev);
  246. }
  247. break;
  248. }
  249. }
  250. return result;
  251. }
  252. void Backend::RequestExit()
  253. {
  254. RMLUI_ASSERT(data);
  255. data->running = false;
  256. }
  257. void Backend::BeginFrame()
  258. {
  259. RMLUI_ASSERT(data);
  260. data->render_interface.BeginFrame();
  261. data->render_interface.Clear();
  262. }
  263. void Backend::PresentFrame()
  264. {
  265. RMLUI_ASSERT(data);
  266. data->render_interface.EndFrame();
  267. // Flips the OpenGL buffers.
  268. glXSwapBuffers(data->display, data->window);
  269. }