X11Window.cpp 24 KB

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