BsLinuxPlatform.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Image/BsPixelData.h"
  4. #include "Image/BsPixelUtil.h"
  5. #include "String/BsUnicode.h"
  6. #include "Linux/BsLinuxPlatform.h"
  7. #include "Linux/BsLinuxWindow.h"
  8. #include "RenderAPI/BsRenderWindow.h"
  9. #include "BsLinuxDropTarget.h"
  10. #include "BsCoreApplication.h"
  11. #include <X11/X.h>
  12. #include <X11/Xatom.h>
  13. #include <X11/Xcursor/Xcursor.h>
  14. #include <X11/Xlib.h>
  15. #include <X11/XKBlib.h>
  16. namespace bs
  17. {
  18. Event<void(const Vector2I&, const OSPointerButtonStates&)> Platform::onCursorMoved;
  19. Event<void(const Vector2I&, OSMouseButton button, const OSPointerButtonStates&)> Platform::onCursorButtonPressed;
  20. Event<void(const Vector2I&, OSMouseButton button, const OSPointerButtonStates&)> Platform::onCursorButtonReleased;
  21. Event<void(const Vector2I&, const OSPointerButtonStates&)> Platform::onCursorDoubleClick;
  22. Event<void(InputCommandType)> Platform::onInputCommand;
  23. Event<void(float)> Platform::onMouseWheelScrolled;
  24. Event<void(UINT32)> Platform::onCharInput;
  25. Event<void()> Platform::onMouseCaptureChanged;
  26. enum class X11CursorType
  27. {
  28. Arrow,
  29. ArrowDrag,
  30. ArrowLeftRight,
  31. Wait,
  32. IBeam,
  33. SizeTopLeft,
  34. SizeTopRight,
  35. SizeBotLeft,
  36. SizeBotRight,
  37. SizeLeft,
  38. SizeRight,
  39. SizeTop,
  40. SizeBottom,
  41. Deny,
  42. Count
  43. };;
  44. struct Platform::Pimpl
  45. {
  46. ::Display* xDisplay = nullptr;
  47. ::Window mainXWindow = 0;
  48. ::Window fullscreenXWindow = 0;
  49. UnorderedMap<::Window, LinuxWindow*> windowMap;
  50. Vector<::Window> toDestroy;
  51. Mutex lock;
  52. XIM IM;
  53. XIC IC;
  54. Time lastButtonPressTime;
  55. Atom atomDeleteWindow;
  56. Atom atomWmState;
  57. Atom atomWmStateHidden;
  58. Atom atomWmStateMaxVert;
  59. Atom atomWmStateMaxHorz;
  60. // Clipboard
  61. WString clipboardData;
  62. // Cursor
  63. ::Cursor currentCursor = None;
  64. ::Cursor emptyCursor = None;
  65. bool isCursorHidden = false;
  66. Rect2I cursorClipRect;
  67. LinuxWindow* cursorClipWindow = nullptr;
  68. bool cursorClipEnabled = false;
  69. };
  70. static const UINT32 DOUBLE_CLICK_MS = 500;
  71. Vector2I _getCursorPosition(Platform::Pimpl* data)
  72. {
  73. Vector2I pos;
  74. UINT32 screenCount = (UINT32)XScreenCount(data->xDisplay);
  75. for (UINT32 i = 0; i < screenCount; ++i)
  76. {
  77. ::Window outRoot, outChild;
  78. INT32 childX, childY;
  79. UINT32 mask;
  80. if(XQueryPointer(data->xDisplay, XRootWindow(data->xDisplay, i), &outRoot, &outChild, &pos.x,
  81. &pos.y, &childX, &childY, &mask))
  82. break;
  83. }
  84. return pos;
  85. }
  86. void _setCursorPosition(Platform::Pimpl* data, const Vector2I& screenPos)
  87. {
  88. UINT32 screenCount = (UINT32)XScreenCount(data->xDisplay);
  89. // Note assuming screens are laid out horizontally left to right
  90. INT32 screenX = 0;
  91. for(UINT32 i = 0; i < screenCount; ++i)
  92. {
  93. ::Window root = XRootWindow(data->xDisplay, i);
  94. INT32 screenXEnd = screenX + XDisplayWidth(data->xDisplay, i);
  95. if(screenPos.x >= screenX && screenPos.x < screenXEnd)
  96. {
  97. XWarpPointer(data->xDisplay, None, root, 0, 0, 0, 0, screenPos.x, screenPos.y);
  98. XFlush(data->xDisplay);
  99. return;
  100. }
  101. screenX = screenXEnd;
  102. }
  103. }
  104. void applyCurrentCursor(Platform::Pimpl* data, ::Window window)
  105. {
  106. if(data->isCursorHidden)
  107. XDefineCursor(data->xDisplay, window, data->emptyCursor);
  108. else
  109. {
  110. if (data->currentCursor != None)
  111. XDefineCursor(data->xDisplay, window, data->currentCursor);
  112. else
  113. XUndefineCursor(data->xDisplay, window);
  114. }
  115. }
  116. void updateClipBounds(Platform::Pimpl* data, LinuxWindow* window)
  117. {
  118. if(!data->cursorClipEnabled || data->cursorClipWindow != window)
  119. return;
  120. data->cursorClipRect.x = window->getLeft();
  121. data->cursorClipRect.y = window->getTop();
  122. data->cursorClipRect.width = window->getWidth();
  123. data->cursorClipRect.height = window->getHeight();
  124. }
  125. bool clipCursor(Platform::Pimpl* data, Vector2I& pos)
  126. {
  127. if(!data->cursorClipEnabled)
  128. return false;
  129. INT32 clippedX = pos.x - data->cursorClipRect.x;
  130. INT32 clippedY = pos.y - data->cursorClipRect.y;
  131. if(clippedX < 0)
  132. clippedX = data->cursorClipRect.x + data->cursorClipRect.width + clippedX;
  133. else if(clippedX >= (INT32)data->cursorClipRect.width)
  134. clippedX = data->cursorClipRect.x + (clippedX - data->cursorClipRect.width);
  135. else
  136. clippedX = data->cursorClipRect.x + clippedX;
  137. if(clippedY < 0)
  138. clippedY = data->cursorClipRect.y + data->cursorClipRect.height + clippedY;
  139. else if(clippedY >= (INT32)data->cursorClipRect.height)
  140. clippedY = data->cursorClipRect.y + (clippedY - data->cursorClipRect.height);
  141. else
  142. clippedY = data->cursorClipRect.y + clippedY;
  143. if(clippedX != pos.x || clippedY != pos.y)
  144. {
  145. pos.x = clippedX;
  146. pos.y = clippedY;
  147. return true;
  148. }
  149. return false;
  150. }
  151. void setCurrentCursor(Platform::Pimpl* data, ::Cursor cursor)
  152. {
  153. if(data->currentCursor)
  154. XFreeCursor(data->xDisplay, data->currentCursor);
  155. data->currentCursor = cursor;
  156. for(auto& entry : data->windowMap)
  157. applyCurrentCursor(data, entry.first);
  158. }
  159. /**
  160. * Searches the window hierarchy, from top to bottom, looking for the top-most window that contains the specified
  161. * point. Returns 0 if one is not found.
  162. */
  163. ::Window getWindowUnderPoint(::Display* display, ::Window rootWindow, ::Window window, const Vector2I& screenPos)
  164. {
  165. ::Window outRoot, outParent;
  166. ::Window* children;
  167. UINT32 numChildren;
  168. XQueryTree(display, window, &outRoot, &outParent, &children, &numChildren);
  169. if(children == nullptr || numChildren == 0)
  170. return window;
  171. for(UINT32 j = 0; j < numChildren; j++)
  172. {
  173. ::Window curWindow = children[numChildren - j - 1];
  174. XWindowAttributes xwa;
  175. XGetWindowAttributes(display, curWindow, &xwa);
  176. if(xwa.map_state != IsViewable || xwa.c_class != InputOutput)
  177. continue;
  178. // Get position in root window coordinates
  179. ::Window outChild;
  180. Vector2I pos;
  181. if(!XTranslateCoordinates(display, curWindow, rootWindow, 0, 0, &pos.x, &pos.y, &outChild))
  182. continue;
  183. Rect2I area(pos.x, pos.y, (UINT32)xwa.width, (UINT32)xwa.height);
  184. if(area.contains(screenPos))
  185. {
  186. XFree(children);
  187. return getWindowUnderPoint(display, rootWindow, curWindow, screenPos);
  188. }
  189. }
  190. XFree(children);
  191. return 0;
  192. }
  193. int x11ErrorHandler(::Display* display, XErrorEvent* event)
  194. {
  195. // X11 by default crashes the app on error, even though some errors can be just fine. So we provide our own handler.
  196. char buffer[256];
  197. XGetErrorText(display, event->error_code, buffer, sizeof(buffer));
  198. LOGWRN("X11 error: " + String(buffer));
  199. return 0;
  200. }
  201. Platform::Pimpl* Platform::mData = bs_new<Platform::Pimpl>();
  202. Platform::~Platform()
  203. { }
  204. Vector2I Platform::getCursorPosition()
  205. {
  206. Lock lock(mData->lock);
  207. return _getCursorPosition(mData);
  208. }
  209. void Platform::setCursorPosition(const Vector2I& screenPos)
  210. {
  211. Lock lock(mData->lock);
  212. _setCursorPosition(mData, screenPos);
  213. }
  214. void Platform::captureMouse(const RenderWindow& window)
  215. {
  216. Lock lock(mData->lock);
  217. LinuxWindow* linuxWindow;
  218. window.getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  219. UINT32 mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask;
  220. XGrabPointer(mData->xDisplay, linuxWindow->_getXWindow(), False, mask, GrabModeAsync,
  221. GrabModeAsync, None, None, CurrentTime);
  222. XSync(mData->xDisplay, False);
  223. }
  224. void Platform::releaseMouseCapture()
  225. {
  226. Lock lock(mData->lock);
  227. XUngrabPointer(mData->xDisplay, CurrentTime);
  228. XSync(mData->xDisplay, False);
  229. }
  230. bool Platform::isPointOverWindow(const RenderWindow& window, const Vector2I& screenPos)
  231. {
  232. Lock lock(mData->lock);
  233. LinuxWindow* linuxWindow;
  234. window.getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  235. ::Window xWindow = linuxWindow->_getXWindow();
  236. UINT32 screenCount = (UINT32)XScreenCount(mData->xDisplay);
  237. for (UINT32 i = 0; i < screenCount; ++i)
  238. {
  239. ::Window rootWindow = XRootWindow(mData->xDisplay, i);
  240. ::Window curWindow = getWindowUnderPoint(mData->xDisplay, rootWindow, rootWindow, screenPos);
  241. return curWindow == xWindow;
  242. }
  243. return false;
  244. }
  245. void Platform::hideCursor()
  246. {
  247. Lock lock(mData->lock);
  248. mData->isCursorHidden = true;
  249. for(auto& entry : mData->windowMap)
  250. applyCurrentCursor(mData, entry.first);
  251. }
  252. void Platform::showCursor()
  253. {
  254. Lock lock(mData->lock);
  255. mData->isCursorHidden = false;
  256. for(auto& entry : mData->windowMap)
  257. applyCurrentCursor(mData, entry.first);
  258. }
  259. bool Platform::isCursorHidden()
  260. {
  261. Lock lock(mData->lock);
  262. return mData->isCursorHidden;
  263. }
  264. void Platform::clipCursorToWindow(const RenderWindow& window)
  265. {
  266. Lock lock(mData->lock);
  267. LinuxWindow* linuxWindow;
  268. window.getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  269. mData->cursorClipEnabled = true;
  270. mData->cursorClipWindow = linuxWindow;
  271. updateClipBounds(mData, linuxWindow);
  272. Vector2I pos = _getCursorPosition(mData);
  273. if(clipCursor(mData, pos))
  274. _setCursorPosition(mData, pos);
  275. }
  276. void Platform::clipCursorToRect(const Rect2I& screenRect)
  277. {
  278. Lock lock(mData->lock);
  279. mData->cursorClipEnabled = true;
  280. mData->cursorClipRect = screenRect;
  281. mData->cursorClipWindow = nullptr;
  282. Vector2I pos = _getCursorPosition(mData);
  283. if(clipCursor(mData, pos))
  284. _setCursorPosition(mData, pos);
  285. }
  286. void Platform::clipCursorDisable()
  287. {
  288. Lock lock(mData->lock);
  289. mData->cursorClipEnabled = false;
  290. mData->cursorClipWindow = None;
  291. }
  292. void Platform::setCursor(PixelData& pixelData, const Vector2I& hotSpot)
  293. {
  294. SPtr<PixelData> bgraData = PixelData::create(pixelData.getWidth(), pixelData.getHeight(), 1, PF_BGRA8);
  295. PixelUtil::bulkPixelConversion(pixelData, *bgraData);
  296. Lock lock(mData->lock);
  297. XcursorImage* image = XcursorImageCreate((int)bgraData->getWidth(), (int)bgraData->getHeight());
  298. image->xhot = (XcursorDim)hotSpot.x;
  299. image->yhot = (XcursorDim)hotSpot.y;
  300. image->delay = 0;
  301. memcpy(image->pixels, bgraData->getData(), bgraData->getSize());
  302. ::Cursor cursor = XcursorImageLoadCursor(mData->xDisplay, image);
  303. XcursorImageDestroy(image);
  304. setCurrentCursor(mData, cursor);
  305. }
  306. void Platform::setIcon(const PixelData& pixelData)
  307. {
  308. SPtr<PixelData> resizedData = PixelData::create(32, 32, 1, PF_RGBA8);
  309. PixelUtil::scale(pixelData, *resizedData);
  310. if(!mData->mainXWindow)
  311. return;
  312. auto iterFind = mData->windowMap.find(mData->mainXWindow);
  313. if(iterFind == mData->windowMap.end())
  314. return;
  315. LinuxWindow* mainLinuxWindow = iterFind->second;
  316. Lock lock(mData->lock);
  317. mainLinuxWindow->setIcon(pixelData);
  318. }
  319. void Platform::setCaptionNonClientAreas(const ct::RenderWindow& window, const Vector<Rect2I>& nonClientAreas)
  320. {
  321. if(nonClientAreas.size() == 0)
  322. return;
  323. Lock lock(mData->lock);
  324. LinuxWindow* linuxWindow;
  325. window.getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  326. // Note: Only supporting a single area
  327. linuxWindow->_setDragZone(nonClientAreas[0]);
  328. }
  329. void Platform::setResizeNonClientAreas(const ct::RenderWindow& window, const Vector<NonClientResizeArea>& nonClientAreas)
  330. {
  331. // Do nothing, resize areas not supported on Linux (but they are provided even on undecorated windows by the WM)
  332. }
  333. void Platform::resetNonClientAreas(const ct::RenderWindow& window)
  334. {
  335. // Do nothing, resize areas not supported on Linux (but they are provided even on undecorated windows by the WM)
  336. }
  337. void Platform::sleep(UINT32 duration)
  338. {
  339. usleep(duration * 1000);
  340. }
  341. void Platform::copyToClipboard(const WString& string)
  342. {
  343. Lock lock(mData->lock);
  344. mData->clipboardData = string;
  345. Atom clipboardAtom = XInternAtom(mData->xDisplay, "CLIPBOARD", 0);
  346. XSetSelectionOwner(mData->xDisplay, clipboardAtom, mData->mainXWindow, CurrentTime);
  347. }
  348. WString Platform::copyFromClipboard()
  349. {
  350. Lock lock(mData->lock);
  351. Atom clipboardAtom = XInternAtom(mData->xDisplay, "CLIPBOARD", 0);
  352. ::Window selOwner = XGetSelectionOwner(mData->xDisplay, clipboardAtom);
  353. if(selOwner == None)
  354. return L"";
  355. if(selOwner == mData->mainXWindow)
  356. return mData->clipboardData;
  357. XConvertSelection(mData->xDisplay, clipboardAtom, XA_STRING, clipboardAtom, mData->mainXWindow,
  358. CurrentTime);
  359. XFlush(mData->xDisplay);
  360. // Note: This might discard events if there are any in between the one we need. Ideally we let the
  361. // processEvents() handle them
  362. while(true)
  363. {
  364. XEvent event;
  365. XNextEvent(mData->xDisplay, &event);
  366. if(event.type == SelectionNotify && event.xselection.requestor == mData->mainXWindow)
  367. break;
  368. }
  369. Atom actualType;
  370. INT32 actualFormat;
  371. unsigned long length;
  372. unsigned long bytesRemaining;
  373. UINT8* data;
  374. XGetWindowProperty(mData->xDisplay, mData->mainXWindow, clipboardAtom,
  375. 0, 0, False, AnyPropertyType, &actualType, &actualFormat, &length, &bytesRemaining, &data);
  376. if(bytesRemaining > 0)
  377. {
  378. unsigned long unused;
  379. INT32 result = XGetWindowProperty(mData->xDisplay, mData->mainXWindow, clipboardAtom,
  380. 0, bytesRemaining, False, AnyPropertyType, &actualType, &actualFormat, &length,
  381. &unused, &data);
  382. if(result == Success)
  383. return UTF8::toWide(String((const char*)data));
  384. XFree(data);
  385. }
  386. return L"";
  387. }
  388. /** Maps Banshee button codes to X11 names for physical key locations. */
  389. const char* keyCodeToKeyName(ButtonCode code)
  390. {
  391. switch(code)
  392. {
  393. // Row #1
  394. case BC_F1: return "FK01";
  395. case BC_F2: return "FK02";
  396. case BC_F3: return "FK03";
  397. case BC_F4: return "FK04";
  398. case BC_F5: return "FK05";
  399. case BC_F6: return "FK06";
  400. case BC_F7: return "FK07";
  401. case BC_F8: return "FK08";
  402. case BC_F9: return "FK09";
  403. case BC_F10: return "FK10";
  404. case BC_F11: return "FK11";
  405. case BC_F12: return "FK12";
  406. // Row #2
  407. case BC_GRAVE: return "TLDE";
  408. case BC_1: return "AE01";
  409. case BC_2: return "AE02";
  410. case BC_3: return "AE03";
  411. case BC_4: return "AE04";
  412. case BC_5: return "AE05";
  413. case BC_6: return "AE06";
  414. case BC_7: return "AE07";
  415. case BC_8: return "AE08";
  416. case BC_9: return "AE09";
  417. case BC_0: return "AE10";
  418. case BC_MINUS: return "AE11";
  419. case BC_EQUALS: return "AE12";
  420. case BC_BACK: return "BKSP";
  421. // Row #3
  422. case BC_TAB: return "TAB";
  423. case BC_Q: return "AD01";
  424. case BC_W: return "AD02";
  425. case BC_E: return "AD03";
  426. case BC_R: return "AD04";
  427. case BC_T: return "AD05";
  428. case BC_Y: return "AD06";
  429. case BC_U: return "AD07";
  430. case BC_I: return "AD08";
  431. case BC_O: return "AD09";
  432. case BC_P: return "AD10";
  433. case BC_LBRACKET: return "AD11";
  434. case BC_RBRACKET: return "AD12";
  435. // Row #4
  436. case BC_A: return "AC01";
  437. case BC_S: return "AC02";
  438. case BC_D: return "AC03";
  439. case BC_F: return "AC04";
  440. case BC_G: return "AC05";
  441. case BC_H: return "AC06";
  442. case BC_J: return "AC07";
  443. case BC_K: return "AC08";
  444. case BC_L: return "AC09";
  445. case BC_SEMICOLON: return "AC10";
  446. case BC_APOSTROPHE: return "AC11";
  447. case BC_BACKSLASH: return "BKSL";
  448. // Row #5
  449. case BC_Z: return "AB01";
  450. case BC_X: return "AB02";
  451. case BC_C: return "AB03";
  452. case BC_V: return "AB04";
  453. case BC_B: return "AB05";
  454. case BC_N: return "AB06";
  455. case BC_M: return "AB07";
  456. case BC_COMMA: return "AB08";
  457. case BC_PERIOD: return "AB09";
  458. case BC_SLASH: return "AB10";
  459. // Keypad
  460. case BC_NUMPAD0: return "KP0";
  461. case BC_NUMPAD1: return "KP1";
  462. case BC_NUMPAD2: return "KP2";
  463. case BC_NUMPAD3: return "KP3";
  464. case BC_NUMPAD4: return "KP4";
  465. case BC_NUMPAD5: return "KP5";
  466. case BC_NUMPAD6: return "KP6";
  467. case BC_NUMPAD7: return "KP7";
  468. case BC_NUMPAD8: return "KP8";
  469. case BC_NUMPAD9: return "KP9";
  470. default:
  471. break;
  472. }
  473. return nullptr;
  474. }
  475. WString Platform::keyCodeToUnicode(UINT32 buttonCode)
  476. {
  477. Lock lock(mData->lock);
  478. static bool mapInitialized = false;
  479. static UnorderedMap<String, KeyCode> keyMap;
  480. if(!mapInitialized)
  481. {
  482. char name[XkbKeyNameLength + 1];
  483. XkbDescPtr desc = XkbGetMap(mData->xDisplay, 0, XkbUseCoreKbd);
  484. XkbGetNames(mData->xDisplay, XkbKeyNamesMask, desc);
  485. for(UINT32 keyCode = desc->min_key_code; keyCode <= desc->max_key_code; keyCode++)
  486. {
  487. memcpy(name, desc->names->keys[keyCode].name, XkbKeyNameLength);
  488. name[XkbKeyNameLength] = '\0';
  489. keyMap[String(name)] = keyCode;
  490. }
  491. XkbFreeNames(desc, XkbKeyNamesMask, True);
  492. XkbFreeKeyboard(desc, 0, True);
  493. mapInitialized = true;
  494. }
  495. const char* keyName = keyCodeToKeyName((ButtonCode)buttonCode);
  496. if(keyName == nullptr)
  497. {
  498. // Not a printable key
  499. return L"";
  500. }
  501. auto iterFind = keyMap.find(String(keyName));
  502. if(iterFind == keyMap.end())
  503. {
  504. // Cannot find mapping, although this shouldn't really happen
  505. return L"";
  506. }
  507. XKeyPressedEvent event;
  508. bs_zero_out(event);
  509. event.type = KeyPress;
  510. event.keycode = iterFind->second;
  511. event.display = mData->xDisplay;
  512. event.time = CurrentTime;
  513. event.window = mData->mainXWindow;
  514. event.root = RootWindow(mData->xDisplay, XDefaultScreen(mData->xDisplay));
  515. Status status;
  516. char buffer[16];
  517. INT32 length = Xutf8LookupString(mData->IC, &event, buffer, sizeof(buffer), nullptr, &status);
  518. if(length > 0)
  519. {
  520. buffer[length] = '\0';
  521. return UTF8::toWide(String(buffer));
  522. }
  523. return L"";
  524. }
  525. void Platform::openFolder(const Path& path)
  526. {
  527. String pathString = path.toString();
  528. const char* commandPattern = "xdg-open '%s'";
  529. char* commandStr = (char*)bs_stack_alloc((UINT32)pathString.size() + (UINT32)strlen(commandPattern) + 1);
  530. sprintf(commandStr, commandPattern, pathString.c_str());
  531. system(commandStr);
  532. bs_stack_free(commandStr);
  533. }
  534. /**
  535. * Converts an X11 KeySym code into an input command, if possible. Returns true if conversion was done.
  536. *
  537. * @param[in] keySym KeySym to try to translate to a command.
  538. * @param[in] shift True if the shift key was held down when the key was pressed.
  539. * @param[out] command Input command. Only valid if function returns true.
  540. * @return True if the KeySym is an input command.
  541. */
  542. bool parseInputCommand(KeySym keySym, bool shift, InputCommandType& command)
  543. {
  544. switch (keySym)
  545. {
  546. case XK_Left:
  547. command = shift ? InputCommandType::SelectLeft : InputCommandType::CursorMoveLeft;
  548. return true;
  549. case XK_Right:
  550. command = shift ? InputCommandType::SelectRight : InputCommandType::CursorMoveRight;
  551. return true;
  552. case XK_Up:
  553. command = shift ? InputCommandType::SelectUp : InputCommandType::CursorMoveUp;
  554. return true;
  555. case XK_Down:
  556. command = shift ? InputCommandType::SelectDown : InputCommandType::CursorMoveDown;
  557. return true;
  558. case XK_Escape:
  559. command = InputCommandType::Escape;
  560. return true;
  561. case XK_Return:
  562. command = shift ? InputCommandType::Return : InputCommandType::Confirm;
  563. return true;
  564. case XK_BackSpace:
  565. command = InputCommandType::Backspace;
  566. return true;
  567. case XK_Delete:
  568. command = InputCommandType::Delete;
  569. return true;
  570. }
  571. return false;
  572. }
  573. /** Returns a LinuxWindow from a native X11 window handle. */
  574. LinuxWindow* getLinuxWindow(LinuxPlatform::Pimpl* data, ::Window xWindow)
  575. {
  576. auto iterFind = data->windowMap.find(xWindow);
  577. if (iterFind != data->windowMap.end())
  578. {
  579. LinuxWindow* window = iterFind->second;
  580. return window;
  581. }
  582. return nullptr;
  583. }
  584. /** Returns a RenderWindow from a native X11 window handle. Returns null if the window isn't a RenderWindow */
  585. ct::RenderWindow* getRenderWindow(LinuxPlatform::Pimpl* data, ::Window xWindow)
  586. {
  587. LinuxWindow* linuxWindow = getLinuxWindow(data, xWindow);
  588. if(linuxWindow != nullptr)
  589. return (ct::RenderWindow*)linuxWindow->_getUserData();
  590. return nullptr;
  591. }
  592. void Platform::_messagePump()
  593. {
  594. while(true)
  595. {
  596. Lock lock(mData->lock);
  597. if(XPending(mData->xDisplay) <= 0)
  598. {
  599. // No more events, destroy any queued windows
  600. for(auto& entry : mData->toDestroy)
  601. XDestroyWindow(mData->xDisplay, entry);
  602. mData->toDestroy.clear();
  603. XSync(mData->xDisplay, false);
  604. break;
  605. }
  606. XEvent event;
  607. XNextEvent(mData->xDisplay, &event);
  608. switch (event.type)
  609. {
  610. case ClientMessage:
  611. {
  612. if(LinuxDragAndDrop::handleClientMessage(event.xclient))
  613. break;
  614. if((Atom)event.xclient.data.l[0] == mData->atomDeleteWindow)
  615. {
  616. // We queue the window for destruction as soon as we process all current events (since some of those
  617. // events could still refer to this window)
  618. mData->toDestroy.push_back(event.xclient.window);
  619. XUnmapWindow(mData->xDisplay, event.xclient.window);
  620. XSync(mData->xDisplay, false);
  621. }
  622. }
  623. break;
  624. case DestroyNotify:
  625. {
  626. LinuxWindow* window = getLinuxWindow(mData, event.xdestroywindow.window);
  627. if(window != nullptr)
  628. {
  629. CoreApplication::instance().quitRequested();
  630. window->_cleanUp();
  631. if (mData->mainXWindow == 0)
  632. return;
  633. }
  634. }
  635. break;
  636. case KeyPress:
  637. {
  638. // Process text input
  639. KeySym keySym = XkbKeycodeToKeysym(mData->xDisplay, (KeyCode)event.xkey.keycode, 0, 0);
  640. //// Check if input manager wants this event. If not, we process it.
  641. if(XFilterEvent(&event, None) == False)
  642. {
  643. // Don't consider Return key a character
  644. if(keySym != XK_Return)
  645. {
  646. Status status;
  647. char buffer[16];
  648. INT32 length = Xutf8LookupString(mData->IC, &event.xkey, buffer, sizeof(buffer), nullptr,
  649. &status);
  650. if (length > 0)
  651. {
  652. buffer[length] = '\0';
  653. U32String utfStr = UTF8::toUTF32(String(buffer));
  654. if (utfStr.length() > 0)
  655. onCharInput((UINT32) utfStr[0]);
  656. }
  657. }
  658. }
  659. // Handle input commands
  660. InputCommandType command = InputCommandType::Backspace;
  661. bool shift = (event.xkey.state & ShiftMask) != 0;
  662. if(parseInputCommand(keySym, shift, command))
  663. {
  664. if(!onInputCommand.empty())
  665. onInputCommand(command);
  666. }
  667. }
  668. break;
  669. case KeyRelease:
  670. // Do nothing
  671. break;
  672. case ButtonPress:
  673. {
  674. UINT32 button = event.xbutton.button;
  675. OSMouseButton mouseButton;
  676. bool validPress = false;
  677. switch(button)
  678. {
  679. case Button1:
  680. mouseButton = OSMouseButton::Left;
  681. validPress = true;
  682. break;
  683. case Button2:
  684. mouseButton = OSMouseButton::Middle;
  685. validPress = true;
  686. break;
  687. case Button3:
  688. mouseButton = OSMouseButton::Right;
  689. validPress = true;
  690. break;
  691. default:
  692. break;
  693. }
  694. if(validPress)
  695. {
  696. // Send event
  697. Vector2I pos;
  698. pos.x = event.xbutton.x_root;
  699. pos.y = event.xbutton.y_root;
  700. OSPointerButtonStates btnStates;
  701. btnStates.ctrl = (event.xbutton.state & ControlMask) != 0;
  702. btnStates.shift = (event.xbutton.state & ShiftMask) != 0;
  703. btnStates.mouseButtons[0] = (event.xbutton.state & Button1Mask) != 0;
  704. btnStates.mouseButtons[1] = (event.xbutton.state & Button2Mask) != 0;
  705. btnStates.mouseButtons[2] = (event.xbutton.state & Button3Mask) != 0;
  706. onCursorButtonPressed(pos, mouseButton, btnStates);
  707. // Handle double-click
  708. if(button == Button1)
  709. {
  710. if (event.xbutton.time < (mData->lastButtonPressTime + DOUBLE_CLICK_MS))
  711. {
  712. onCursorDoubleClick(pos, btnStates);
  713. mData->lastButtonPressTime = 0;
  714. }
  715. else
  716. mData->lastButtonPressTime = event.xbutton.time;
  717. }
  718. }
  719. // Handle window dragging for windows without a title bar
  720. if(button == Button1)
  721. {
  722. LinuxWindow* window = getLinuxWindow(mData, event.xbutton.window);
  723. if(window != nullptr)
  724. window->_dragStart(event.xbutton.x, event.xbutton.y);
  725. }
  726. break;
  727. }
  728. case ButtonRelease:
  729. {
  730. UINT32 button = event.xbutton.button;
  731. Vector2I pos;
  732. pos.x = event.xbutton.x_root;
  733. pos.y = event.xbutton.y_root;
  734. OSPointerButtonStates btnStates;
  735. btnStates.ctrl = (event.xbutton.state & ControlMask) != 0;
  736. btnStates.shift = (event.xbutton.state & ShiftMask) != 0;
  737. btnStates.mouseButtons[0] = (event.xbutton.state & Button1Mask) != 0;
  738. btnStates.mouseButtons[1] = (event.xbutton.state & Button2Mask) != 0;
  739. btnStates.mouseButtons[2] = (event.xbutton.state & Button3Mask) != 0;
  740. switch(button)
  741. {
  742. case Button1:
  743. onCursorButtonReleased(pos, OSMouseButton::Left, btnStates);
  744. break;
  745. case Button2:
  746. onCursorButtonReleased(pos, OSMouseButton::Middle, btnStates);
  747. break;
  748. case Button3:
  749. onCursorButtonReleased(pos, OSMouseButton::Right, btnStates);
  750. break;
  751. case Button4: // Vertical mouse wheel
  752. case Button5:
  753. {
  754. INT32 delta = button == Button4 ? 1 : -1;
  755. onMouseWheelScrolled((float)delta);
  756. }
  757. break;
  758. default:
  759. break;
  760. }
  761. // Handle window dragging for windows without a title bar
  762. if(button == Button1)
  763. {
  764. LinuxWindow* window = getLinuxWindow(mData, event.xbutton.window);
  765. if(window != nullptr)
  766. window->_dragEnd();
  767. }
  768. break;
  769. }
  770. case MotionNotify:
  771. {
  772. Vector2I pos;
  773. pos.x = event.xmotion.x_root;
  774. pos.y = event.xmotion.y_root;
  775. // Handle clipping if enabled
  776. if(clipCursor(mData, pos))
  777. _setCursorPosition(mData, pos);
  778. // Send event
  779. OSPointerButtonStates btnStates;
  780. btnStates.ctrl = (event.xmotion.state & ControlMask) != 0;
  781. btnStates.shift = (event.xmotion.state & ShiftMask) != 0;
  782. btnStates.mouseButtons[0] = (event.xmotion.state & Button1Mask) != 0;
  783. btnStates.mouseButtons[1] = (event.xmotion.state & Button2Mask) != 0;
  784. btnStates.mouseButtons[2] = (event.xmotion.state & Button3Mask) != 0;
  785. onCursorMoved(pos, btnStates);
  786. // Handle window dragging for windows without a title bar
  787. LinuxWindow* window = getLinuxWindow(mData, event.xmotion.window);
  788. if(window != nullptr)
  789. window->_dragUpdate(event.xmotion.x, event.xmotion.y);
  790. }
  791. break;
  792. case EnterNotify:
  793. // Do nothing
  794. break;
  795. case LeaveNotify:
  796. {
  797. if (event.xcrossing.mode == NotifyNormal)
  798. {
  799. Vector2I pos;
  800. pos.x = event.xcrossing.x_root;
  801. pos.y = event.xcrossing.y_root;
  802. if (clipCursor(mData, pos))
  803. _setCursorPosition(mData, pos);
  804. }
  805. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xcrossing.window);
  806. if(renderWindow != nullptr)
  807. renderWindow->_notifyMouseLeft();
  808. }
  809. break;
  810. case ConfigureNotify:
  811. {
  812. LinuxWindow* window = getLinuxWindow(mData, event.xconfigure.window);
  813. if(window != nullptr)
  814. {
  815. updateClipBounds(mData, window);
  816. ct::RenderWindow* renderWindow = (ct::RenderWindow*)window->_getUserData();
  817. if(renderWindow != nullptr)
  818. renderWindow->_windowMovedOrResized();
  819. }
  820. }
  821. break;
  822. case FocusIn:
  823. {
  824. // Update input context focus
  825. XSetICFocus(mData->IC);
  826. // Send event to render window
  827. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xfocus.window);
  828. // Not a render window, so it doesn't care about these events
  829. if (renderWindow != nullptr)
  830. {
  831. if (!renderWindow->getProperties().hasFocus)
  832. renderWindow->_windowFocusReceived();
  833. }
  834. }
  835. break;
  836. case FocusOut:
  837. {
  838. // Update input context focus
  839. XUnsetICFocus(mData->IC);
  840. // Send event to render window
  841. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xfocus.window);
  842. // Not a render window, so it doesn't care about these events
  843. if (renderWindow != nullptr)
  844. {
  845. if (renderWindow->getProperties().hasFocus)
  846. renderWindow->_windowFocusLost();
  847. }
  848. }
  849. break;
  850. case SelectionNotify:
  851. LinuxDragAndDrop::handleSelectionNotify(event.xselection);
  852. break;
  853. case SelectionRequest:
  854. {
  855. // Send the data saved by the last clipboard copy operation
  856. Atom compoundTextAtom = XInternAtom(mData->xDisplay, "COMPOUND_TEXT", 0);
  857. Atom utf8StringAtom = XInternAtom(mData->xDisplay, "UTF8_STRING", 0);
  858. Atom targetsAtom = XInternAtom(mData->xDisplay, "TARGETS", 0);
  859. XSelectionRequestEvent& selReq = event.xselectionrequest;
  860. XEvent response;
  861. if(selReq.target == XA_STRING || selReq.target == compoundTextAtom || selReq.target == utf8StringAtom)
  862. {
  863. String utf8data = UTF8::fromWide(mData->clipboardData);
  864. const UINT8* data = (const UINT8*)utf8data.c_str();
  865. INT32 dataLength = (INT32)utf8data.length();
  866. XChangeProperty(mData->xDisplay, selReq.requestor, selReq.property,
  867. selReq.target, 8, PropModeReplace, data, dataLength);
  868. response.xselection.property = selReq.property;
  869. }
  870. else if(selReq.target == targetsAtom)
  871. {
  872. Atom data[2];
  873. data[0] = utf8StringAtom;
  874. data[1] = XA_STRING;
  875. XChangeProperty (mData->xDisplay, selReq.requestor, selReq.property, selReq.target,
  876. 8, PropModeReplace, (unsigned char*)&data, sizeof (data));
  877. response.xselection.property = selReq.property;
  878. }
  879. else
  880. {
  881. response.xselection.property = None;
  882. }
  883. response.xselection.type = SelectionNotify;
  884. response.xselection.display = selReq.display;
  885. response.xselection.requestor = selReq.requestor;
  886. response.xselection.selection = selReq.selection;
  887. response.xselection.target = selReq.target;
  888. response.xselection.time = selReq.time;
  889. XSendEvent (mData->xDisplay, selReq.requestor, 0, 0, &response);
  890. XFlush (mData->xDisplay);
  891. }
  892. break;
  893. case PropertyNotify:
  894. // Report minimize, maximize and restore events
  895. if(event.xproperty.atom == mData->atomWmState)
  896. {
  897. Atom type;
  898. INT32 format;
  899. unsigned long count, bytesRemaining;
  900. UINT8* data = nullptr;
  901. INT32 result = XGetWindowProperty(mData->xDisplay, event.xproperty.window, mData->atomWmState,
  902. 0, 1024, False, AnyPropertyType, &type, &format,
  903. &count, &bytesRemaining, &data);
  904. if (result == Success)
  905. {
  906. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xproperty.window);
  907. // Not a render window, so it doesn't care about these events
  908. if(renderWindow == nullptr)
  909. continue;
  910. Atom* atoms = (Atom*)data;
  911. bool foundHorz = false;
  912. bool foundVert = false;
  913. for (unsigned long i = 0; i < count; i++)
  914. {
  915. if (atoms[i] == mData->atomWmStateMaxHorz) foundHorz = true;
  916. if (atoms[i] == mData->atomWmStateMaxVert) foundVert = true;
  917. if (foundVert && foundHorz)
  918. {
  919. if(event.xproperty.state == PropertyNewValue)
  920. renderWindow->_notifyMaximized();
  921. else
  922. renderWindow->_notifyRestored();
  923. }
  924. if(atoms[i] == mData->atomWmStateHidden)
  925. {
  926. if(event.xproperty.state == PropertyNewValue)
  927. renderWindow->_notifyMinimized();
  928. else
  929. renderWindow->_notifyRestored();
  930. }
  931. }
  932. XFree(atoms);
  933. }
  934. }
  935. break;
  936. default:
  937. break;
  938. }
  939. }
  940. }
  941. void Platform::_startUp()
  942. {
  943. Lock lock(mData->lock);
  944. mData->xDisplay = XOpenDisplay(nullptr);
  945. XSetErrorHandler(x11ErrorHandler);
  946. if(XSupportsLocale())
  947. {
  948. XSetLocaleModifiers("@im=none");
  949. mData->IM = XOpenIM(mData->xDisplay, nullptr, nullptr, nullptr);
  950. // Note: Currently our windows don't support pre-edit and status areas, which are used for more complex types
  951. // of character input. Later on it might be beneficial to support them.
  952. mData->IC = XCreateIC(mData->IM, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, nullptr);
  953. }
  954. mData->atomDeleteWindow = XInternAtom(mData->xDisplay, "WM_DELETE_WINDOW", False);
  955. mData->atomWmState = XInternAtom(mData->xDisplay, "_NET_WM_STATE", False);
  956. mData->atomWmStateHidden = XInternAtom(mData->xDisplay, "_NET_WM_STATE_HIDDEN", False);
  957. mData->atomWmStateMaxHorz = XInternAtom(mData->xDisplay, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  958. mData->atomWmStateMaxVert = XInternAtom(mData->xDisplay, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  959. // Drag and drop
  960. LinuxDragAndDrop::startUp(mData->xDisplay);
  961. // Create empty cursor
  962. char data[1];
  963. memset(data, 0, sizeof(data));
  964. Pixmap pixmap = XCreateBitmapFromData(mData->xDisplay, DefaultRootWindow(mData->xDisplay), data, 1, 1);
  965. XColor color;
  966. color.red = color.green = color.blue = 0;
  967. mData->emptyCursor = XCreatePixmapCursor(mData->xDisplay, pixmap, pixmap, &color, &color, 0, 0);
  968. XFreePixmap(mData->xDisplay, pixmap);
  969. }
  970. void Platform::_update()
  971. {
  972. LinuxDragAndDrop::update();
  973. }
  974. void Platform::_coreUpdate()
  975. {
  976. _messagePump();
  977. }
  978. void Platform::_shutDown()
  979. {
  980. Lock lock(mData->lock);
  981. // Free empty cursor
  982. XFreeCursor(mData->xDisplay, mData->emptyCursor);
  983. mData->emptyCursor = None;
  984. // Shutdown drag and drop
  985. LinuxDragAndDrop::shutDown();
  986. if(mData->IC)
  987. {
  988. XDestroyIC(mData->IC);
  989. mData->IC = 0;
  990. }
  991. if(mData->IM)
  992. {
  993. XCloseIM(mData->IM);
  994. mData->IM = 0;
  995. }
  996. XCloseDisplay(mData->xDisplay);
  997. mData->xDisplay = nullptr;
  998. bs_delete(mData);
  999. mData = nullptr;
  1000. }
  1001. ::Display* LinuxPlatform::getXDisplay()
  1002. {
  1003. return mData->xDisplay;
  1004. }
  1005. ::Window LinuxPlatform::getMainXWindow()
  1006. {
  1007. return mData->mainXWindow;
  1008. }
  1009. void LinuxPlatform::lockX()
  1010. {
  1011. mData->lock.lock();
  1012. }
  1013. void LinuxPlatform::unlockX()
  1014. {
  1015. mData->lock.unlock();
  1016. }
  1017. void LinuxPlatform::_registerWindow(::Window xWindow, LinuxWindow* window)
  1018. {
  1019. // First window is assumed to be the main
  1020. if(mData->mainXWindow == 0)
  1021. {
  1022. mData->mainXWindow = xWindow;
  1023. // Input context client window must be set before use
  1024. XSetICValues(mData->IC,
  1025. XNClientWindow, xWindow,
  1026. XNFocusWindow, xWindow,
  1027. nullptr);
  1028. }
  1029. mData->windowMap[xWindow] = window;
  1030. applyCurrentCursor(mData, xWindow);
  1031. }
  1032. void LinuxPlatform::_unregisterWindow(::Window xWindow)
  1033. {
  1034. auto iterFind = mData->windowMap.find(xWindow);
  1035. if(iterFind != mData->windowMap.end())
  1036. {
  1037. if(mData->cursorClipEnabled && mData->cursorClipWindow == iterFind->second)
  1038. clipCursorDisable();
  1039. mData->windowMap.erase(iterFind);
  1040. }
  1041. if(mData->mainXWindow == xWindow)
  1042. mData->mainXWindow = 0;
  1043. }
  1044. Pixmap LinuxPlatform::createPixmap(const PixelData& data)
  1045. {
  1046. SPtr<PixelData> bgraData = PixelData::create(data.getWidth(), data.getHeight(), 1, PF_BGRA8);
  1047. PixelUtil::bulkPixelConversion(data, *bgraData);
  1048. UINT32 depth = (UINT32)XDefaultDepth(mData->xDisplay, 0);
  1049. XImage* image = XCreateImage(mData->xDisplay, XDefaultVisual(mData->xDisplay, 0), depth, ZPixmap, 0,
  1050. (char*)bgraData->getData(), data.getWidth(), data.getHeight(), 32, 0);
  1051. Pixmap pixmap = XCreatePixmap(mData->xDisplay, XDefaultRootWindow(mData->xDisplay),
  1052. data.getWidth(), data.getHeight(), depth);
  1053. XGCValues gcValues;
  1054. GC gc = XCreateGC(mData->xDisplay, pixmap, 0, &gcValues);
  1055. XPutImage(mData->xDisplay, pixmap, gc, image, 0, 0, 0, 0, data.getWidth(), data.getHeight());
  1056. XFreeGC(mData->xDisplay, gc);
  1057. // Make sure XDestroyImage doesn't free the data pointed to by 'data.bytes'
  1058. image->data = nullptr;
  1059. XDestroyImage(image);
  1060. return pixmap;
  1061. }
  1062. }