X11Window.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. 
  2. // Avoid cluttering the global namespace by hiding these from the header
  3. #include <X11/Xlib.h>
  4. #include <X11/Xutil.h>
  5. #include <X11/Xos.h>
  6. #include <X11/Xatom.h>
  7. #include "../DFPSR/api/imageAPI.h"
  8. #include "../DFPSR/gui/BackendWindow.h"
  9. // According to this documentation, XInitThreads doesn't have to be used if a mutex is wrapped around all the calls to XLib.
  10. // https://tronche.com/gui/x/xlib/display/XInitThreads.html
  11. #include <mutex>
  12. #include <future>
  13. static std::mutex windowLock;
  14. // Enable this macro to disable multi-threading
  15. //#define DISABLE_MULTI_THREADING
  16. static const int bufferCount = 2;
  17. class X11Window : public dsr::BackendWindow {
  18. private:
  19. // The display is the connection to the X server
  20. // Each window has it's own connection, because you're only supposed to have one window
  21. // Let sub-windows be visual components for simpler input and deterministic custom decorations
  22. Display *display = nullptr;
  23. // The handle to the X11 window
  24. Window window;
  25. // Holds settings for drawing to the window
  26. GC graphicsContext;
  27. // Double buffering to allow drawing to a canvas while displaying the previous one
  28. // The image which can be drawn to, sharing memory with the X11 image
  29. dsr::AlignedImageRgbaU8 canvas[bufferCount];
  30. // An X11 image wrapped around the canvas pixel data
  31. XImage *canvasX[bufferCount] = {};
  32. int drawIndex = 0 % bufferCount;
  33. int showIndex = 1 % bufferCount;
  34. #ifndef DISABLE_MULTI_THREADING
  35. // The background worker for displaying the result using a separate thread protected by a mutex
  36. std::future<void> displayFuture;
  37. #endif
  38. // Remembers the dimensions of the window from creation and resize events
  39. // This allow requesting the size of the window at any time
  40. int windowWidth = 0, windowHeight = 0;
  41. // Called before the application fetches events from the input queue
  42. // Closing the window, moving the mouse, pressing a key, et cetera
  43. void prefetchEvents() override;
  44. // Color format
  45. dsr::PackOrderIndex packOrderIndex = dsr::PackOrderIndex::RGBA;
  46. dsr::PackOrderIndex getColorFormat_locked();
  47. private:
  48. // Helper methods specific to calling XLib
  49. void updateTitle_locked();
  50. private:
  51. // Canvas methods
  52. dsr::AlignedImageRgbaU8 getCanvas() override { return this->canvas[this->drawIndex]; }
  53. void resizeCanvas(int width, int height) override;
  54. // Window methods
  55. void setTitle(const dsr::String &newTitle) override {
  56. this->title = newTitle;
  57. this->updateTitle_locked();
  58. }
  59. void removeOldWindow_locked();
  60. void createGCWindow_locked(const dsr::String& title, int width, int height);
  61. void createWindowed_locked(const dsr::String& title, int width, int height);
  62. void createFullscreen_locked();
  63. void prepareWindow_locked();
  64. int windowState = 0; // 0=none, 1=windowed, 2=fullscreen
  65. public:
  66. // Constructors
  67. X11Window(const X11Window&) = delete; // Non-copyable because of pointer aliasing.
  68. X11Window(const dsr::String& title, int width, int height);
  69. int getWidth() const override { return this->windowWidth; };
  70. int getHeight() const override { return this->windowHeight; };
  71. // Destructor
  72. ~X11Window();
  73. // Interface
  74. void setFullScreen(bool enabled) override;
  75. bool isFullScreen() override { return this->windowState == 2; }
  76. void showCanvas() override;
  77. };
  78. void X11Window::updateTitle_locked() {
  79. windowLock.lock();
  80. XSetStandardProperties(this->display, this->window, this->title.toStdString().c_str(), "Icon", None, NULL, 0, NULL);
  81. windowLock.unlock();
  82. }
  83. dsr::PackOrderIndex X11Window::getColorFormat_locked() {
  84. windowLock.lock();
  85. XVisualInfo visualRequest;
  86. visualRequest.screen = 0;
  87. visualRequest.depth = 32;
  88. visualRequest.c_class = TrueColor;
  89. int visualCount;
  90. XVisualInfo *formatList = XGetVisualInfo(this->display, VisualScreenMask | VisualDepthMask | VisualClassMask, &visualRequest, &visualCount);
  91. dsr::PackOrderIndex result = dsr::PackOrderIndex::RGBA;
  92. if (formatList == nullptr) {
  93. dsr::throwError(U"Error! The display does not support truecolor formats.\n");
  94. } else {
  95. for (int i = 0; i < visualCount; i++) {
  96. if (formatList[i].bits_per_rgb == 8) {
  97. const uint32_t red = formatList[i].red_mask;
  98. const uint32_t green = formatList[i].green_mask;
  99. const uint32_t blue = formatList[i].blue_mask;
  100. const uint32_t first = 255u;
  101. const uint32_t second = 255u << 8u;
  102. const uint32_t third = 255u << 16u;
  103. const uint32_t fourth = 255u << 24u;
  104. if (red == first && green == second && blue == third) {
  105. result = dsr::PackOrderIndex::RGBA;
  106. } else if (red == second && green == third && blue == fourth) {
  107. result = dsr::PackOrderIndex::ARGB;
  108. } else if (blue == first && green == second && red == third) {
  109. result = dsr::PackOrderIndex::BGRA;
  110. } else if (blue == second && green == third && red == fourth) {
  111. result = dsr::PackOrderIndex::ABGR;
  112. } else {
  113. dsr::throwError(U"Error! Unhandled color format. Only RGBA, ARGB, BGRA and ABGR are currently supported.\n");
  114. }
  115. break;
  116. }
  117. }
  118. XFree(formatList);
  119. }
  120. windowLock.unlock();
  121. return result;
  122. }
  123. struct Hints {
  124. unsigned long flags;
  125. unsigned long functions;
  126. unsigned long decorations;
  127. long inputMode;
  128. unsigned long status;
  129. };
  130. void X11Window::setFullScreen(bool enabled) {
  131. if (this->windowState == 1 && enabled) {
  132. // Clean up any previous X11 window
  133. removeOldWindow_locked();
  134. // Create the new window and graphics context
  135. this->createFullscreen_locked();
  136. } else if (this->windowState == 2 && !enabled) {
  137. // Clean up any previous X11 window
  138. removeOldWindow_locked();
  139. // Create the new window and graphics context
  140. this->createWindowed_locked(this->title, 800, 600); // TODO: Remember the dimensions from last windowed mode
  141. }
  142. }
  143. void X11Window::removeOldWindow_locked() {
  144. windowLock.lock();
  145. if (this->windowState != 0) {
  146. XFreeGC(this->display, this->graphicsContext);
  147. XDestroyWindow(this->display, this->window);
  148. XUngrabPointer(this->display, CurrentTime);
  149. }
  150. this->windowState = 0;
  151. windowLock.unlock();
  152. }
  153. void X11Window::prepareWindow_locked() {
  154. windowLock.lock();
  155. // Set input masks
  156. XSelectInput(this->display, this->window,
  157. ExposureMask | StructureNotifyMask |
  158. PointerMotionMask |
  159. ButtonPressMask | ButtonReleaseMask |
  160. KeyPressMask | KeyReleaseMask
  161. );
  162. // Listen to the window close event.
  163. Atom WM_DELETE_WINDOW = XInternAtom(this->display, "WM_DELETE_WINDOW", False);
  164. XSetWMProtocols(this->display, this->window, &WM_DELETE_WINDOW, 1);
  165. windowLock.unlock();
  166. // Reallocate the canvas
  167. this->resizeCanvas(this->windowWidth, this->windowHeight);
  168. }
  169. void X11Window::createGCWindow_locked(const dsr::String& title, int width, int height) {
  170. windowLock.lock();
  171. // Request to resize the canvas and interface according to the new window
  172. this->windowWidth = width;
  173. this->windowHeight = height;
  174. this->receivedWindowResize(width, height);
  175. // Screen handle
  176. int defaultScreenIndex = DefaultScreen(this->display);
  177. unsigned long black = BlackPixel(this->display, defaultScreenIndex);
  178. unsigned long white = WhitePixel(this->display, defaultScreenIndex);
  179. // Create a new window
  180. this->window = XCreateSimpleWindow(this->display, DefaultRootWindow(this->display), 0, 0, width, height, 0, white, black);
  181. windowLock.unlock();
  182. this->updateTitle_locked();
  183. windowLock.lock();
  184. // Create a new graphics context
  185. this->graphicsContext = XCreateGC(this->display, this->window, 0, 0);
  186. XSetBackground(this->display, this->graphicsContext, black);
  187. XSetForeground(this->display, this->graphicsContext, white);
  188. XClearWindow(this->display, this->window);
  189. windowLock.unlock();
  190. }
  191. void X11Window::createWindowed_locked(const dsr::String& title, int width, int height) {
  192. // Create the window
  193. this->createGCWindow_locked(title, width, height);
  194. windowLock.lock();
  195. // Display the window when done placing it
  196. XMapRaised(this->display, this->window);
  197. this->windowState = 1;
  198. windowLock.unlock();
  199. this->prepareWindow_locked();
  200. }
  201. void X11Window::createFullscreen_locked() {
  202. windowLock.lock();
  203. // Get the screen resolution
  204. Screen* screenInfo = DefaultScreenOfDisplay(this->display);
  205. windowLock.unlock();
  206. // Create the window
  207. this->createGCWindow_locked(U"", screenInfo->width, screenInfo->height);
  208. windowLock.lock();
  209. // Override redirect
  210. unsigned long valuemask = CWOverrideRedirect;
  211. XSetWindowAttributes setwinattr;
  212. setwinattr.override_redirect = 1;
  213. XChangeWindowAttributes(this->display, this->window, valuemask, &setwinattr);
  214. // Remove decorations
  215. Hints hints;
  216. memset(&hints, 0, sizeof(hints));
  217. hints.flags = 2;
  218. hints.decorations = 0;
  219. Atom property;
  220. property = XInternAtom(this->display, "_MOTIF_WM_HINTS", True); // TODO: Check if this optional XLib feature is supported
  221. XChangeProperty(this->display, this->window, property, property, 32, PropModeReplace, (unsigned char*)&hints, 5);
  222. // Move to absolute origin
  223. XMoveResizeWindow(this->display, this->window, 0, 0, screenInfo->width, screenInfo->height);
  224. // Prevent accessing anything outside of the window until it closes (for multiple displays)
  225. XGrabPointer(this->display, this->window, 1, 0, GrabModeAsync, GrabModeAsync, this->window, 0L, CurrentTime);
  226. XGrabKeyboard(this->display, this->window, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
  227. // Display the window when done placing it
  228. XMapRaised(this->display, this->window);
  229. // Now that the window is visible, it can be focused for keyboard input
  230. XSetInputFocus(this->display, this->window, RevertToNone, CurrentTime);
  231. this->windowState = 2;
  232. windowLock.unlock();
  233. this->prepareWindow_locked();
  234. }
  235. X11Window::X11Window(const dsr::String& title, int width, int height) {
  236. bool fullScreen = false;
  237. if (width < 1 || height < 1) {
  238. fullScreen = true;
  239. width = 400;
  240. height = 300;
  241. }
  242. windowLock.lock();
  243. this->display = XOpenDisplay(nullptr);
  244. windowLock.unlock();
  245. if (this->display == nullptr) {
  246. dsr::throwError(U"Error! Failed to open XLib display!\n");
  247. return;
  248. }
  249. // Get the color format
  250. this->packOrderIndex = this->getColorFormat_locked();
  251. // Remember the title
  252. this->title = title;
  253. // Create a window
  254. if (fullScreen) {
  255. this->createFullscreen_locked();
  256. } else {
  257. this->createWindowed_locked(title, width, height);
  258. }
  259. }
  260. // Convert keycodes from XLib to DSR
  261. static dsr::MouseKeyEnum getMouseKey(int keyCode) {
  262. dsr::MouseKeyEnum result = dsr::MouseKeyEnum::NoKey;
  263. if (keyCode == Button1) {
  264. result = dsr::MouseKeyEnum::Left;
  265. } else if (keyCode == Button2) {
  266. result = dsr::MouseKeyEnum::Middle;
  267. } else if (keyCode == Button3) {
  268. result = dsr::MouseKeyEnum::Right;
  269. } else if (keyCode == Button4) {
  270. result = dsr::MouseKeyEnum::ScrollUp;
  271. } else if (keyCode == Button5) {
  272. result = dsr::MouseKeyEnum::ScrollDown;
  273. }
  274. return result;
  275. }
  276. static bool isVerticalScrollKey(dsr::MouseKeyEnum key) {
  277. return key == dsr::MouseKeyEnum::ScrollDown || key == dsr::MouseKeyEnum::ScrollUp;
  278. }
  279. static dsr::DsrKey getDsrKey(KeySym keyCode) {
  280. dsr::DsrKey result = dsr::DsrKey_Unhandled;
  281. if (keyCode == XK_Escape) {
  282. result = dsr::DsrKey_Escape;
  283. } else if (keyCode == XK_F1) {
  284. result = dsr::DsrKey_F1;
  285. } else if (keyCode == XK_F2) {
  286. result = dsr::DsrKey_F2;
  287. } else if (keyCode == XK_F3) {
  288. result = dsr::DsrKey_F3;
  289. } else if (keyCode == XK_F4) {
  290. result = dsr::DsrKey_F4;
  291. } else if (keyCode == XK_F5) {
  292. result = dsr::DsrKey_F5;
  293. } else if (keyCode == XK_F6) {
  294. result = dsr::DsrKey_F6;
  295. } else if (keyCode == XK_F7) {
  296. result = dsr::DsrKey_F7;
  297. } else if (keyCode == XK_F8) {
  298. result = dsr::DsrKey_F8;
  299. } else if (keyCode == XK_F9) {
  300. result = dsr::DsrKey_F9;
  301. } else if (keyCode == XK_F10) {
  302. result = dsr::DsrKey_F10;
  303. } else if (keyCode == XK_F11) {
  304. result = dsr::DsrKey_F11;
  305. } else if (keyCode == XK_F12) {
  306. result = dsr::DsrKey_F12;
  307. } else if (keyCode == XK_Pause) {
  308. result = dsr::DsrKey_Pause;
  309. } else if (keyCode == XK_space) {
  310. result = dsr::DsrKey_Space;
  311. } else if (keyCode == XK_Tab) {
  312. result = dsr::DsrKey_Tab;
  313. } else if (keyCode == XK_Return) {
  314. result = dsr::DsrKey_Return;
  315. } else if (keyCode == XK_BackSpace) {
  316. result = dsr::DsrKey_BackSpace;
  317. } else if (keyCode == XK_Shift_L) {
  318. result = dsr::DsrKey_LeftShift;
  319. } else if (keyCode == XK_Shift_R) {
  320. result = dsr::DsrKey_RightShift;
  321. } else if (keyCode == XK_Control_L) {
  322. result = dsr::DsrKey_LeftControl;
  323. } else if (keyCode == XK_Control_R) {
  324. result = dsr::DsrKey_RightControl;
  325. } else if (keyCode == XK_Alt_L) {
  326. result = dsr::DsrKey_LeftAlt;
  327. } else if (keyCode == XK_Alt_R) {
  328. result = dsr::DsrKey_RightAlt;
  329. } else if (keyCode == XK_Delete) {
  330. result = dsr::DsrKey_Delete;
  331. } else if (keyCode == XK_Left) {
  332. result = dsr::DsrKey_LeftArrow;
  333. } else if (keyCode == XK_Right) {
  334. result = dsr::DsrKey_RightArrow;
  335. } else if (keyCode == XK_Up) {
  336. result = dsr::DsrKey_UpArrow;
  337. } else if (keyCode == XK_Down) {
  338. result = dsr::DsrKey_DownArrow;
  339. } else if (keyCode == XK_0) {
  340. result = dsr::DsrKey_0;
  341. } else if (keyCode == XK_1) {
  342. result = dsr::DsrKey_1;
  343. } else if (keyCode == XK_2) {
  344. result = dsr::DsrKey_2;
  345. } else if (keyCode == XK_3) {
  346. result = dsr::DsrKey_3;
  347. } else if (keyCode == XK_4) {
  348. result = dsr::DsrKey_4;
  349. } else if (keyCode == XK_5) {
  350. result = dsr::DsrKey_5;
  351. } else if (keyCode == XK_6) {
  352. result = dsr::DsrKey_6;
  353. } else if (keyCode == XK_7) {
  354. result = dsr::DsrKey_7;
  355. } else if (keyCode == XK_8) {
  356. result = dsr::DsrKey_8;
  357. } else if (keyCode == XK_9) {
  358. result = dsr::DsrKey_9;
  359. } else if (keyCode == XK_a || keyCode == XK_A) {
  360. result = dsr::DsrKey_A;
  361. } else if (keyCode == XK_b || keyCode == XK_B) {
  362. result = dsr::DsrKey_B;
  363. } else if (keyCode == XK_c || keyCode == XK_C) {
  364. result = dsr::DsrKey_C;
  365. } else if (keyCode == XK_d || keyCode == XK_D) {
  366. result = dsr::DsrKey_D;
  367. } else if (keyCode == XK_e || keyCode == XK_E) {
  368. result = dsr::DsrKey_E;
  369. } else if (keyCode == XK_f || keyCode == XK_F) {
  370. result = dsr::DsrKey_F;
  371. } else if (keyCode == XK_g || keyCode == XK_G) {
  372. result = dsr::DsrKey_G;
  373. } else if (keyCode == XK_h || keyCode == XK_H) {
  374. result = dsr::DsrKey_H;
  375. } else if (keyCode == XK_i || keyCode == XK_I) {
  376. result = dsr::DsrKey_I;
  377. } else if (keyCode == XK_j || keyCode == XK_J) {
  378. result = dsr::DsrKey_J;
  379. } else if (keyCode == XK_k || keyCode == XK_K) {
  380. result = dsr::DsrKey_K;
  381. } else if (keyCode == XK_l || keyCode == XK_L) {
  382. result = dsr::DsrKey_L;
  383. } else if (keyCode == XK_m || keyCode == XK_M) {
  384. result = dsr::DsrKey_M;
  385. } else if (keyCode == XK_n || keyCode == XK_N) {
  386. result = dsr::DsrKey_N;
  387. } else if (keyCode == XK_o || keyCode == XK_O) {
  388. result = dsr::DsrKey_O;
  389. } else if (keyCode == XK_p || keyCode == XK_P) {
  390. result = dsr::DsrKey_P;
  391. } else if (keyCode == XK_q || keyCode == XK_Q) {
  392. result = dsr::DsrKey_Q;
  393. } else if (keyCode == XK_r || keyCode == XK_R) {
  394. result = dsr::DsrKey_R;
  395. } else if (keyCode == XK_s || keyCode == XK_S) {
  396. result = dsr::DsrKey_S;
  397. } else if (keyCode == XK_t || keyCode == XK_T) {
  398. result = dsr::DsrKey_T;
  399. } else if (keyCode == XK_u || keyCode == XK_U) {
  400. result = dsr::DsrKey_U;
  401. } else if (keyCode == XK_v || keyCode == XK_V) {
  402. result = dsr::DsrKey_V;
  403. } else if (keyCode == XK_w || keyCode == XK_W) {
  404. result = dsr::DsrKey_W;
  405. } else if (keyCode == XK_x || keyCode == XK_X) {
  406. result = dsr::DsrKey_X;
  407. } else if (keyCode == XK_y || keyCode == XK_Y) {
  408. result = dsr::DsrKey_Y;
  409. } else if (keyCode == XK_z || keyCode == XK_Z) {
  410. result = dsr::DsrKey_Z;
  411. }
  412. return result;
  413. }
  414. // TODO: Implement support for typing in UNICODE. How can this be tested when even Chinese keyboards use phonetic typing?
  415. static uint32_t getNativeCharacterCode(XEvent& event) {
  416. KeySym key; char text[255]; uint32_t character = '\0';
  417. if (XLookupString(&event.xkey, text, 255, &key, 0) == 1) { character = text[0]; }
  418. return character;
  419. }
  420. // Also locked, but cannot change the name when overriding
  421. void X11Window::prefetchEvents() {
  422. // Only prefetch new events if nothing else is using the communication link
  423. if (windowLock.try_lock()) {
  424. if (this->display) {
  425. while (XPending(this->display)) {
  426. // Ensure that full-screen applications have keyboard focus if interacted with in any way
  427. if (this->windowState == 2) {
  428. XSetInputFocus(this->display, this->window, RevertToNone, CurrentTime);
  429. }
  430. // Get the current event
  431. XEvent currentEvent;
  432. XNextEvent(this->display, &currentEvent);
  433. // See if there's another event
  434. XEvent nextEvent;
  435. bool hasNextEvent = XPending(this->display);
  436. if (hasNextEvent) {
  437. XPeekEvent(this->display, &nextEvent);
  438. }
  439. if (currentEvent.type == Expose && currentEvent.xexpose.count == 0) {
  440. // Redraw
  441. this->queueInputEvent(new dsr::WindowEvent(dsr::WindowEventType::Redraw, this->windowWidth, this->windowHeight));
  442. } else if (currentEvent.type == KeyPress || currentEvent.type == KeyRelease) {
  443. // Key down/up
  444. uint32_t character = getNativeCharacterCode(currentEvent);
  445. KeySym nativeKey = XLookupKeysym(&currentEvent.xkey, 0);
  446. dsr::DsrKey dsrKey = getDsrKey(nativeKey);
  447. KeySym nextNativeKey = hasNextEvent ? XLookupKeysym(&nextEvent.xkey, 0) : 0;
  448. // Distinguish between fake and physical repeats using time stamps
  449. if (hasNextEvent
  450. && currentEvent.type == KeyRelease && nextEvent.type == KeyPress
  451. && currentEvent.xkey.time == nextEvent.xkey.time
  452. && nativeKey == nextNativeKey) {
  453. // Repeated typing
  454. this->queueInputEvent(new dsr::KeyboardEvent(dsr::KeyboardEventType::KeyType, character, dsrKey));
  455. // Skip next event
  456. XNextEvent(this->display, &currentEvent);
  457. } else {
  458. if (currentEvent.type == KeyPress) {
  459. // Physical key down
  460. this->queueInputEvent(new dsr::KeyboardEvent(dsr::KeyboardEventType::KeyDown, character, dsrKey));
  461. // First press typing
  462. this->queueInputEvent(new dsr::KeyboardEvent(dsr::KeyboardEventType::KeyType, character, dsrKey));
  463. } else { // currentEvent.type == KeyRelease
  464. // Physical key up
  465. this->queueInputEvent(new dsr::KeyboardEvent(dsr::KeyboardEventType::KeyUp, character, dsrKey));
  466. }
  467. }
  468. } else if (currentEvent.type == ButtonPress) {
  469. // Mouse down
  470. dsr::MouseKeyEnum key = getMouseKey(currentEvent.xbutton.button);
  471. this->queueInputEvent(new dsr::MouseEvent(isVerticalScrollKey(key) ? dsr::MouseEventType::Scroll : dsr::MouseEventType::MouseDown, key, dsr::IVector2D(currentEvent.xbutton.x, currentEvent.xbutton.y)));
  472. } else if (currentEvent.type == ButtonRelease) {
  473. // Mouse up
  474. dsr::MouseKeyEnum key = getMouseKey(currentEvent.xbutton.button);
  475. // Scroll events are already captured from the mouse down signal
  476. if (!isVerticalScrollKey(key)) {
  477. this->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::MouseUp, key, dsr::IVector2D(currentEvent.xbutton.x, currentEvent.xbutton.y)));
  478. }
  479. } else if (currentEvent.type == MotionNotify) {
  480. // Mouse move
  481. this->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, dsr::IVector2D(currentEvent.xmotion.x, currentEvent.xmotion.y)));
  482. } else if (currentEvent.type == ClientMessage) {
  483. // Close
  484. // Assume WM_DELETE_WINDOW since it is the only registered client message
  485. this->queueInputEvent(new dsr::WindowEvent(dsr::WindowEventType::Close, this->windowWidth, this->windowHeight));
  486. } else if (currentEvent.type == ConfigureNotify) {
  487. XConfigureEvent xce = currentEvent.xconfigure;
  488. if (this->windowWidth != xce.width || this->windowHeight != xce.height) {
  489. this->windowWidth = xce.width;
  490. this->windowHeight = xce.height;
  491. // Make a request to resize the canvas
  492. this->receivedWindowResize(xce.width, xce.height);
  493. }
  494. }
  495. }
  496. }
  497. windowLock.unlock();
  498. }
  499. }
  500. // Locked because it overrides
  501. void X11Window::resizeCanvas(int width, int height) {
  502. windowLock.lock();
  503. if (this->display) {
  504. unsigned int defaultDepth = DefaultDepth(this->display, XDefaultScreen(this->display));
  505. for (int b = 0; b < bufferCount; b++) {
  506. // Create a new canvas
  507. this->canvas[b] = dsr::image_create_RgbaU8_native(width, height, this->packOrderIndex);
  508. // Get a pointer to the pixels
  509. uint8_t* rawData = dsr::image_dangerous_getData(this->canvas[b]);
  510. // Create an image in XLib using the pointer
  511. // XLib takes ownership of the data
  512. this->canvasX[b] = XCreateImage(
  513. this->display, CopyFromParent, defaultDepth, ZPixmap, 0, (char*)rawData,
  514. dsr::image_getWidth(this->canvas[b]), dsr::image_getHeight(this->canvas[b]), 32, dsr::image_getStride(this->canvas[b])
  515. );
  516. // When the canvas image buffer is garbage collected, the destructor will call XLib to free the memory
  517. XImage *image = this->canvasX[b];
  518. dsr::image_dangerous_replaceDestructor(this->canvas[b], [image](uint8_t *data) { XDestroyImage(image); });
  519. }
  520. }
  521. windowLock.unlock();
  522. }
  523. X11Window::~X11Window() {
  524. #ifndef DISABLE_MULTI_THREADING
  525. // Wait for the last update of the window to finish so that it doesn't try to operate on freed resources
  526. if (this->displayFuture.valid()) {
  527. this->displayFuture.wait();
  528. }
  529. #endif
  530. windowLock.lock();
  531. if (this->display) {
  532. XFreeGC(this->display, this->graphicsContext);
  533. XDestroyWindow(this->display, this->window);
  534. XCloseDisplay(this->display);
  535. this->display = nullptr;
  536. }
  537. windowLock.unlock();
  538. }
  539. void X11Window::showCanvas() {
  540. if (this->display) {
  541. #ifndef DISABLE_MULTI_THREADING
  542. // Wait for the previous update to finish, to avoid flooding the system with new threads waiting for windowLock
  543. if (this->displayFuture.valid()) {
  544. this->displayFuture.wait();
  545. }
  546. #endif
  547. this->drawIndex = (this->drawIndex + 1) % bufferCount;
  548. this->showIndex = (this->showIndex + 1) % bufferCount;
  549. this->prefetchEvents();
  550. int displayIndex = this->showIndex;
  551. windowLock.lock();
  552. std::function<void()> task = [this, displayIndex]() {
  553. // Clamp canvas dimensions to the target window
  554. int width = std::min(dsr::image_getWidth(this->canvas[displayIndex]), this->windowWidth);
  555. int height = std::min(dsr::image_getHeight(this->canvas[displayIndex]), this->windowHeight);
  556. // Display the result
  557. XPutImage(this->display, this->window, this->graphicsContext, this->canvasX[displayIndex], 0, 0, 0, 0, width, height);
  558. windowLock.unlock();
  559. };
  560. #ifdef DISABLE_MULTI_THREADING
  561. // Perform instantly
  562. task();
  563. #else
  564. // Run in the background while doing other things
  565. this->displayFuture = std::async(std::launch::async, task);
  566. #endif
  567. }
  568. }
  569. std::shared_ptr<dsr::BackendWindow> createBackendWindow(const dsr::String& title, int width, int height) {
  570. // Check if a display is available for creating a window
  571. if (XOpenDisplay(nullptr) != nullptr) {
  572. auto backend = std::make_shared<X11Window>(title, width, height);
  573. return std::dynamic_pointer_cast<dsr::BackendWindow>(backend);
  574. } else {
  575. printf("No display detected. Aborting X11 window creation.\n");
  576. return std::shared_ptr<dsr::BackendWindow>();
  577. }
  578. }