X11Window.cpp 32 KB

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