X11Window.cpp 26 KB

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