X11Window.cpp 32 KB

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