BsLinuxPlatform.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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. #include <pwd.h>
  17. namespace bs
  18. {
  19. Event<void(const Vector2I&, const OSPointerButtonStates&)> Platform::onCursorMoved;
  20. Event<void(const Vector2I&, OSMouseButton button, const OSPointerButtonStates&)> Platform::onCursorButtonPressed;
  21. Event<void(const Vector2I&, OSMouseButton button, const OSPointerButtonStates&)> Platform::onCursorButtonReleased;
  22. Event<void(const Vector2I&, const OSPointerButtonStates&)> Platform::onCursorDoubleClick;
  23. Event<void(InputCommandType)> Platform::onInputCommand;
  24. Event<void(float)> Platform::onMouseWheelScrolled;
  25. Event<void(UINT32)> Platform::onCharInput;
  26. Event<void()> Platform::onMouseCaptureChanged;
  27. enum class X11CursorType
  28. {
  29. Arrow,
  30. ArrowDrag,
  31. ArrowLeftRight,
  32. Wait,
  33. IBeam,
  34. SizeTopLeft,
  35. SizeTopRight,
  36. SizeBotLeft,
  37. SizeBotRight,
  38. SizeLeft,
  39. SizeRight,
  40. SizeTop,
  41. SizeBottom,
  42. Deny,
  43. Count
  44. };;
  45. struct Platform::Pimpl
  46. {
  47. ::Display* xDisplay = nullptr;
  48. ::Window mainXWindow = 0;
  49. ::Window fullscreenXWindow = 0;
  50. UnorderedMap<::Window, LinuxWindow*> windowMap;
  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 = 0;
  133. else if(clippedX >= (INT32)data->cursorClipRect.width)
  134. clippedX = data->cursorClipRect.width > 0 ? data->cursorClipRect.width - 1 : 0;
  135. if(clippedY < 0)
  136. clippedY = 0;
  137. else if(clippedY >= (INT32)data->cursorClipRect.height)
  138. clippedY = data->cursorClipRect.height > 0 ? data->cursorClipRect.height - 1 : 0;
  139. clippedX += data->cursorClipRect.x;
  140. clippedY += data->cursorClipRect.y;
  141. if(clippedX != pos.x || clippedY != pos.y)
  142. {
  143. pos.x = clippedX;
  144. pos.y = clippedY;
  145. return true;
  146. }
  147. return false;
  148. }
  149. void setCurrentCursor(Platform::Pimpl* data, ::Cursor cursor)
  150. {
  151. if(data->currentCursor)
  152. XFreeCursor(data->xDisplay, data->currentCursor);
  153. data->currentCursor = cursor;
  154. for(auto& entry : data->windowMap)
  155. applyCurrentCursor(data, entry.first);
  156. }
  157. /**
  158. * Searches the window hierarchy, from top to bottom, looking for the top-most window that contains the specified
  159. * point. Returns 0 if one is not found.
  160. */
  161. ::Window getWindowUnderPoint(::Display* display, ::Window rootWindow, ::Window window, const Vector2I& screenPos)
  162. {
  163. ::Window outRoot, outParent;
  164. ::Window* children;
  165. UINT32 numChildren;
  166. XQueryTree(display, window, &outRoot, &outParent, &children, &numChildren);
  167. if(children == nullptr || numChildren == 0)
  168. return window;
  169. for(UINT32 j = 0; j < numChildren; j++)
  170. {
  171. ::Window curWindow = children[numChildren - j - 1];
  172. XWindowAttributes xwa;
  173. XGetWindowAttributes(display, curWindow, &xwa);
  174. if(xwa.map_state != IsViewable || xwa.c_class != InputOutput)
  175. continue;
  176. // Get position in root window coordinates
  177. ::Window outChild;
  178. Vector2I pos;
  179. if(!XTranslateCoordinates(display, curWindow, rootWindow, 0, 0, &pos.x, &pos.y, &outChild))
  180. continue;
  181. Rect2I area(pos.x, pos.y, (UINT32)xwa.width, (UINT32)xwa.height);
  182. if(area.contains(screenPos))
  183. {
  184. XFree(children);
  185. return getWindowUnderPoint(display, rootWindow, curWindow, screenPos);
  186. }
  187. }
  188. XFree(children);
  189. return 0;
  190. }
  191. int x11ErrorHandler(::Display* display, XErrorEvent* event)
  192. {
  193. // X11 by default crashes the app on error, even though some errors can be just fine. So we provide our own handler.
  194. char buffer[256];
  195. XGetErrorText(display, event->error_code, buffer, sizeof(buffer));
  196. LOGWRN("X11 error: " + String(buffer));
  197. return 0;
  198. }
  199. Platform::Pimpl* Platform::mData = bs_new<Platform::Pimpl>();
  200. Platform::~Platform()
  201. { }
  202. Vector2I Platform::getCursorPosition()
  203. {
  204. Lock lock(mData->lock);
  205. return _getCursorPosition(mData);
  206. }
  207. void Platform::setCursorPosition(const Vector2I& screenPos)
  208. {
  209. Lock lock(mData->lock);
  210. _setCursorPosition(mData, screenPos);
  211. }
  212. void Platform::captureMouse(const RenderWindow& window)
  213. {
  214. Lock lock(mData->lock);
  215. LinuxWindow* linuxWindow;
  216. window.getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  217. UINT32 mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask;
  218. XGrabPointer(mData->xDisplay, linuxWindow->_getXWindow(), False, mask, GrabModeAsync,
  219. GrabModeAsync, None, None, CurrentTime);
  220. XSync(mData->xDisplay, False);
  221. }
  222. void Platform::releaseMouseCapture()
  223. {
  224. Lock lock(mData->lock);
  225. XUngrabPointer(mData->xDisplay, CurrentTime);
  226. XSync(mData->xDisplay, False);
  227. }
  228. bool Platform::isPointOverWindow(const RenderWindow& window, const Vector2I& screenPos)
  229. {
  230. Lock lock(mData->lock);
  231. LinuxWindow* linuxWindow;
  232. window.getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  233. ::Window xWindow = linuxWindow->_getXWindow();
  234. UINT32 screenCount = (UINT32)XScreenCount(mData->xDisplay);
  235. for (UINT32 i = 0; i < screenCount; ++i)
  236. {
  237. ::Window rootWindow = XRootWindow(mData->xDisplay, i);
  238. ::Window curWindow = getWindowUnderPoint(mData->xDisplay, rootWindow, rootWindow, screenPos);
  239. return curWindow == xWindow;
  240. }
  241. return false;
  242. }
  243. void Platform::hideCursor()
  244. {
  245. Lock lock(mData->lock);
  246. mData->isCursorHidden = true;
  247. for(auto& entry : mData->windowMap)
  248. applyCurrentCursor(mData, entry.first);
  249. }
  250. void Platform::showCursor()
  251. {
  252. Lock lock(mData->lock);
  253. mData->isCursorHidden = false;
  254. for(auto& entry : mData->windowMap)
  255. applyCurrentCursor(mData, entry.first);
  256. }
  257. bool Platform::isCursorHidden()
  258. {
  259. Lock lock(mData->lock);
  260. return mData->isCursorHidden;
  261. }
  262. void Platform::clipCursorToWindow(const RenderWindow& window)
  263. {
  264. Lock lock(mData->lock);
  265. LinuxWindow* linuxWindow;
  266. window.getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  267. mData->cursorClipEnabled = true;
  268. mData->cursorClipWindow = linuxWindow;
  269. updateClipBounds(mData, linuxWindow);
  270. Vector2I pos = _getCursorPosition(mData);
  271. if(clipCursor(mData, pos))
  272. _setCursorPosition(mData, pos);
  273. }
  274. void Platform::clipCursorToRect(const Rect2I& screenRect)
  275. {
  276. Lock lock(mData->lock);
  277. mData->cursorClipEnabled = true;
  278. mData->cursorClipRect = screenRect;
  279. mData->cursorClipWindow = nullptr;
  280. Vector2I pos = _getCursorPosition(mData);
  281. if(clipCursor(mData, pos))
  282. _setCursorPosition(mData, pos);
  283. }
  284. void Platform::clipCursorDisable()
  285. {
  286. Lock lock(mData->lock);
  287. mData->cursorClipEnabled = false;
  288. mData->cursorClipWindow = None;
  289. }
  290. void Platform::setCursor(PixelData& pixelData, const Vector2I& hotSpot)
  291. {
  292. SPtr<PixelData> bgraData = PixelData::create(pixelData.getWidth(), pixelData.getHeight(), 1, PF_BGRA8);
  293. PixelUtil::bulkPixelConversion(pixelData, *bgraData);
  294. Lock lock(mData->lock);
  295. XcursorImage* image = XcursorImageCreate((int)bgraData->getWidth(), (int)bgraData->getHeight());
  296. image->xhot = (XcursorDim)hotSpot.x;
  297. image->yhot = (XcursorDim)hotSpot.y;
  298. image->delay = 0;
  299. memcpy(image->pixels, bgraData->getData(), bgraData->getSize());
  300. ::Cursor cursor = XcursorImageLoadCursor(mData->xDisplay, image);
  301. XcursorImageDestroy(image);
  302. setCurrentCursor(mData, cursor);
  303. }
  304. void Platform::setIcon(const PixelData& pixelData)
  305. {
  306. SPtr<PixelData> resizedData = PixelData::create(32, 32, 1, PF_RGBA8);
  307. PixelUtil::scale(pixelData, *resizedData);
  308. if(!mData->mainXWindow)
  309. return;
  310. auto iterFind = mData->windowMap.find(mData->mainXWindow);
  311. if(iterFind == mData->windowMap.end())
  312. return;
  313. LinuxWindow* mainLinuxWindow = iterFind->second;
  314. Lock lock(mData->lock);
  315. mainLinuxWindow->setIcon(pixelData);
  316. }
  317. void Platform::setCaptionNonClientAreas(const ct::RenderWindow& window, const Vector<Rect2I>& nonClientAreas)
  318. {
  319. if(nonClientAreas.size() == 0)
  320. return;
  321. Lock lock(mData->lock);
  322. LinuxWindow* linuxWindow;
  323. window.getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  324. linuxWindow->_setDragZones(nonClientAreas);
  325. }
  326. void Platform::setResizeNonClientAreas(const ct::RenderWindow& window, const Vector<NonClientResizeArea>& nonClientAreas)
  327. {
  328. // Do nothing, resize areas not supported on Linux (but they are provided even on undecorated windows by the WM)
  329. }
  330. void Platform::resetNonClientAreas(const ct::RenderWindow& window)
  331. {
  332. Lock lock(mData->lock);
  333. LinuxWindow* linuxWindow;
  334. window.getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  335. linuxWindow->_setDragZones({});
  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. (void)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. break;
  599. XEvent event;
  600. XNextEvent(mData->xDisplay, &event);
  601. switch (event.type)
  602. {
  603. case ClientMessage:
  604. {
  605. if(LinuxDragAndDrop::handleClientMessage(event.xclient))
  606. break;
  607. // User requested the window to close
  608. if((Atom)event.xclient.data.l[0] == mData->atomDeleteWindow)
  609. {
  610. LinuxWindow* window = getLinuxWindow(mData, event.xclient.window);
  611. if(window != nullptr)
  612. {
  613. // If it's a render window we allow the client code to handle the message
  614. ct::RenderWindow* renderWindow = (ct::RenderWindow*)window->_getUserData();
  615. if(renderWindow != nullptr)
  616. renderWindow->_notifyCloseRequested();
  617. else // If not, we just destroy the window
  618. window->_destroy();
  619. }
  620. }
  621. }
  622. break;
  623. case KeyPress:
  624. {
  625. // Process text input
  626. KeySym keySym = XkbKeycodeToKeysym(mData->xDisplay, (KeyCode)event.xkey.keycode, 0, 0);
  627. //// Check if input manager wants this event. If not, we process it.
  628. if(XFilterEvent(&event, None) == False)
  629. {
  630. // Don't consider Return key a character
  631. if(keySym != XK_Return)
  632. {
  633. Status status;
  634. char buffer[16];
  635. INT32 length = Xutf8LookupString(mData->IC, &event.xkey, buffer, sizeof(buffer), nullptr,
  636. &status);
  637. if (length > 0)
  638. {
  639. buffer[length] = '\0';
  640. U32String utfStr = UTF8::toUTF32(String(buffer));
  641. if (utfStr.length() > 0)
  642. onCharInput((UINT32) utfStr[0]);
  643. }
  644. }
  645. }
  646. // Handle input commands
  647. InputCommandType command = InputCommandType::Backspace;
  648. bool shift = (event.xkey.state & ShiftMask) != 0;
  649. if(parseInputCommand(keySym, shift, command))
  650. {
  651. if(!onInputCommand.empty())
  652. onInputCommand(command);
  653. }
  654. }
  655. break;
  656. case KeyRelease:
  657. // Do nothing
  658. break;
  659. case ButtonPress:
  660. {
  661. UINT32 button = event.xbutton.button;
  662. OSPointerButtonStates btnStates;
  663. btnStates.mouseButtons[0] = (event.xbutton.state & Button1Mask) != 0;
  664. btnStates.mouseButtons[1] = (event.xbutton.state & Button2Mask) != 0;
  665. btnStates.mouseButtons[2] = (event.xbutton.state & Button3Mask) != 0;
  666. OSMouseButton mouseButton;
  667. bool validPress = false;
  668. switch(button)
  669. {
  670. case Button1:
  671. mouseButton = OSMouseButton::Left;
  672. btnStates.mouseButtons[0] = true;
  673. validPress = true;
  674. break;
  675. case Button2:
  676. mouseButton = OSMouseButton::Middle;
  677. btnStates.mouseButtons[1] = true;
  678. validPress = true;
  679. break;
  680. case Button3:
  681. mouseButton = OSMouseButton::Right;
  682. btnStates.mouseButtons[2] = true;
  683. validPress = true;
  684. break;
  685. default:
  686. break;
  687. }
  688. if(validPress)
  689. {
  690. // Send event
  691. Vector2I pos;
  692. pos.x = event.xbutton.x_root;
  693. pos.y = event.xbutton.y_root;
  694. btnStates.ctrl = (event.xbutton.state & ControlMask) != 0;
  695. btnStates.shift = (event.xbutton.state & ShiftMask) != 0;
  696. onCursorButtonPressed(pos, mouseButton, btnStates);
  697. // Handle double-click
  698. if(button == Button1)
  699. {
  700. if (event.xbutton.time < (mData->lastButtonPressTime + DOUBLE_CLICK_MS))
  701. {
  702. onCursorDoubleClick(pos, btnStates);
  703. mData->lastButtonPressTime = 0;
  704. }
  705. else
  706. mData->lastButtonPressTime = event.xbutton.time;
  707. }
  708. }
  709. // Handle window dragging for windows without a title bar
  710. if(button == Button1)
  711. {
  712. LinuxWindow* window = getLinuxWindow(mData, event.xbutton.window);
  713. if(window != nullptr)
  714. window->_dragStart(event.xbutton);
  715. }
  716. break;
  717. }
  718. case ButtonRelease:
  719. {
  720. UINT32 button = event.xbutton.button;
  721. Vector2I pos;
  722. pos.x = event.xbutton.x_root;
  723. pos.y = event.xbutton.y_root;
  724. OSPointerButtonStates btnStates;
  725. btnStates.ctrl = (event.xbutton.state & ControlMask) != 0;
  726. btnStates.shift = (event.xbutton.state & ShiftMask) != 0;
  727. btnStates.mouseButtons[0] = (event.xbutton.state & Button1Mask) != 0;
  728. btnStates.mouseButtons[1] = (event.xbutton.state & Button2Mask) != 0;
  729. btnStates.mouseButtons[2] = (event.xbutton.state & Button3Mask) != 0;
  730. switch(button)
  731. {
  732. case Button1:
  733. btnStates.mouseButtons[0] = false;
  734. onCursorButtonReleased(pos, OSMouseButton::Left, btnStates);
  735. break;
  736. case Button2:
  737. btnStates.mouseButtons[1] = false;
  738. onCursorButtonReleased(pos, OSMouseButton::Middle, btnStates);
  739. break;
  740. case Button3:
  741. btnStates.mouseButtons[2] = false;
  742. onCursorButtonReleased(pos, OSMouseButton::Right, btnStates);
  743. break;
  744. case Button4: // Vertical mouse wheel
  745. case Button5:
  746. {
  747. INT32 delta = button == Button4 ? 1 : -1;
  748. onMouseWheelScrolled((float)delta);
  749. }
  750. break;
  751. default:
  752. break;
  753. }
  754. // Handle window dragging for windows without a title bar
  755. if(button == Button1)
  756. {
  757. LinuxWindow* window = getLinuxWindow(mData, event.xbutton.window);
  758. if(window != nullptr)
  759. window->_dragEnd();
  760. }
  761. break;
  762. }
  763. case MotionNotify:
  764. {
  765. Vector2I pos;
  766. pos.x = event.xmotion.x_root;
  767. pos.y = event.xmotion.y_root;
  768. // Handle clipping if enabled
  769. if(clipCursor(mData, pos))
  770. _setCursorPosition(mData, pos);
  771. // Send event
  772. OSPointerButtonStates btnStates;
  773. btnStates.ctrl = (event.xmotion.state & ControlMask) != 0;
  774. btnStates.shift = (event.xmotion.state & ShiftMask) != 0;
  775. btnStates.mouseButtons[0] = (event.xmotion.state & Button1Mask) != 0;
  776. btnStates.mouseButtons[1] = (event.xmotion.state & Button2Mask) != 0;
  777. btnStates.mouseButtons[2] = (event.xmotion.state & Button3Mask) != 0;
  778. onCursorMoved(pos, btnStates);
  779. }
  780. break;
  781. case EnterNotify:
  782. // Do nothing
  783. break;
  784. case LeaveNotify:
  785. {
  786. if (event.xcrossing.mode == NotifyNormal)
  787. {
  788. Vector2I pos;
  789. pos.x = event.xcrossing.x_root;
  790. pos.y = event.xcrossing.y_root;
  791. if (clipCursor(mData, pos))
  792. _setCursorPosition(mData, pos);
  793. }
  794. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xcrossing.window);
  795. if(renderWindow != nullptr)
  796. renderWindow->_notifyMouseLeft();
  797. }
  798. break;
  799. case ConfigureNotify:
  800. {
  801. LinuxWindow* window = getLinuxWindow(mData, event.xconfigure.window);
  802. if(window != nullptr)
  803. {
  804. updateClipBounds(mData, window);
  805. ct::RenderWindow* renderWindow = (ct::RenderWindow*)window->_getUserData();
  806. if(renderWindow != nullptr)
  807. renderWindow->_windowMovedOrResized();
  808. }
  809. }
  810. break;
  811. case FocusIn:
  812. {
  813. // Update input context focus
  814. XSetICFocus(mData->IC);
  815. // Send event to render window
  816. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xfocus.window);
  817. // Not a render window, so it doesn't care about these events
  818. if (renderWindow != nullptr)
  819. {
  820. if (!renderWindow->getProperties().hasFocus)
  821. renderWindow->_windowFocusReceived();
  822. }
  823. }
  824. break;
  825. case FocusOut:
  826. {
  827. // Update input context focus
  828. XUnsetICFocus(mData->IC);
  829. // Send event to render window
  830. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xfocus.window);
  831. // Not a render window, so it doesn't care about these events
  832. if (renderWindow != nullptr)
  833. {
  834. if (renderWindow->getProperties().hasFocus)
  835. renderWindow->_windowFocusLost();
  836. }
  837. }
  838. break;
  839. case SelectionNotify:
  840. LinuxDragAndDrop::handleSelectionNotify(event.xselection);
  841. break;
  842. case SelectionRequest:
  843. {
  844. // Send the data saved by the last clipboard copy operation
  845. Atom compoundTextAtom = XInternAtom(mData->xDisplay, "COMPOUND_TEXT", 0);
  846. Atom utf8StringAtom = XInternAtom(mData->xDisplay, "UTF8_STRING", 0);
  847. Atom targetsAtom = XInternAtom(mData->xDisplay, "TARGETS", 0);
  848. XSelectionRequestEvent& selReq = event.xselectionrequest;
  849. XEvent response;
  850. if(selReq.target == XA_STRING || selReq.target == compoundTextAtom || selReq.target == utf8StringAtom)
  851. {
  852. String utf8data = UTF8::fromWide(mData->clipboardData);
  853. const UINT8* data = (const UINT8*)utf8data.c_str();
  854. INT32 dataLength = (INT32)utf8data.length();
  855. XChangeProperty(mData->xDisplay, selReq.requestor, selReq.property,
  856. selReq.target, 8, PropModeReplace, data, dataLength);
  857. response.xselection.property = selReq.property;
  858. }
  859. else if(selReq.target == targetsAtom)
  860. {
  861. Atom data[2];
  862. data[0] = utf8StringAtom;
  863. data[1] = XA_STRING;
  864. XChangeProperty (mData->xDisplay, selReq.requestor, selReq.property, selReq.target,
  865. 8, PropModeReplace, (unsigned char*)&data, sizeof (data));
  866. response.xselection.property = selReq.property;
  867. }
  868. else
  869. {
  870. response.xselection.property = None;
  871. }
  872. response.xselection.type = SelectionNotify;
  873. response.xselection.display = selReq.display;
  874. response.xselection.requestor = selReq.requestor;
  875. response.xselection.selection = selReq.selection;
  876. response.xselection.target = selReq.target;
  877. response.xselection.time = selReq.time;
  878. XSendEvent (mData->xDisplay, selReq.requestor, 0, 0, &response);
  879. XFlush (mData->xDisplay);
  880. }
  881. break;
  882. case PropertyNotify:
  883. // Report minimize, maximize and restore events
  884. if(event.xproperty.atom == mData->atomWmState)
  885. {
  886. // Check that the window hasn't been destroyed
  887. if(getLinuxWindow(mData, event.xproperty.window) == nullptr)
  888. break;
  889. Atom type;
  890. INT32 format;
  891. unsigned long count, bytesRemaining;
  892. UINT8* data = nullptr;
  893. INT32 result = XGetWindowProperty(mData->xDisplay, event.xproperty.window, mData->atomWmState,
  894. 0, 1024, False, AnyPropertyType, &type, &format,
  895. &count, &bytesRemaining, &data);
  896. if (result == Success)
  897. {
  898. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xproperty.window);
  899. // Not a render window, so it doesn't care about these events
  900. if(renderWindow == nullptr)
  901. continue;
  902. Atom* atoms = (Atom*)data;
  903. bool foundHorz = false;
  904. bool foundVert = false;
  905. for (unsigned long i = 0; i < count; i++)
  906. {
  907. if (atoms[i] == mData->atomWmStateMaxHorz) foundHorz = true;
  908. if (atoms[i] == mData->atomWmStateMaxVert) foundVert = true;
  909. if (foundVert && foundHorz)
  910. {
  911. if(event.xproperty.state == PropertyNewValue)
  912. renderWindow->_notifyMaximized();
  913. else
  914. renderWindow->_notifyRestored();
  915. }
  916. if(atoms[i] == mData->atomWmStateHidden)
  917. {
  918. if(event.xproperty.state == PropertyNewValue)
  919. renderWindow->_notifyMinimized();
  920. else
  921. renderWindow->_notifyRestored();
  922. }
  923. }
  924. XFree(atoms);
  925. }
  926. }
  927. break;
  928. default:
  929. break;
  930. }
  931. }
  932. }
  933. void Platform::_startUp()
  934. {
  935. Lock lock(mData->lock);
  936. mData->xDisplay = XOpenDisplay(nullptr);
  937. XSetErrorHandler(x11ErrorHandler);
  938. if(XSupportsLocale())
  939. {
  940. XSetLocaleModifiers("@im=none");
  941. mData->IM = XOpenIM(mData->xDisplay, nullptr, nullptr, nullptr);
  942. // Note: Currently our windows don't support pre-edit and status areas, which are used for more complex types
  943. // of character input. Later on it might be beneficial to support them.
  944. mData->IC = XCreateIC(mData->IM, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, nullptr);
  945. }
  946. mData->atomDeleteWindow = XInternAtom(mData->xDisplay, "WM_DELETE_WINDOW", False);
  947. mData->atomWmState = XInternAtom(mData->xDisplay, "_NET_WM_STATE", False);
  948. mData->atomWmStateHidden = XInternAtom(mData->xDisplay, "_NET_WM_STATE_HIDDEN", False);
  949. mData->atomWmStateMaxHorz = XInternAtom(mData->xDisplay, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  950. mData->atomWmStateMaxVert = XInternAtom(mData->xDisplay, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  951. // Drag and drop
  952. LinuxDragAndDrop::startUp(mData->xDisplay);
  953. // Create empty cursor
  954. char data[1];
  955. memset(data, 0, sizeof(data));
  956. Pixmap pixmap = XCreateBitmapFromData(mData->xDisplay, DefaultRootWindow(mData->xDisplay), data, 1, 1);
  957. XColor color;
  958. color.red = color.green = color.blue = 0;
  959. mData->emptyCursor = XCreatePixmapCursor(mData->xDisplay, pixmap, pixmap, &color, &color, 0, 0);
  960. XFreePixmap(mData->xDisplay, pixmap);
  961. }
  962. void Platform::_update()
  963. {
  964. LinuxDragAndDrop::update();
  965. }
  966. void Platform::_coreUpdate()
  967. {
  968. _messagePump();
  969. }
  970. void Platform::_shutDown()
  971. {
  972. Lock lock(mData->lock);
  973. // Free empty cursor
  974. XFreeCursor(mData->xDisplay, mData->emptyCursor);
  975. mData->emptyCursor = None;
  976. // Shutdown drag and drop
  977. LinuxDragAndDrop::shutDown();
  978. if(mData->IC)
  979. {
  980. XDestroyIC(mData->IC);
  981. mData->IC = 0;
  982. }
  983. if(mData->IM)
  984. {
  985. XCloseIM(mData->IM);
  986. mData->IM = 0;
  987. }
  988. XCloseDisplay(mData->xDisplay);
  989. mData->xDisplay = nullptr;
  990. bs_delete(mData);
  991. mData = nullptr;
  992. }
  993. ::Display* LinuxPlatform::getXDisplay()
  994. {
  995. return mData->xDisplay;
  996. }
  997. ::Window LinuxPlatform::getMainXWindow()
  998. {
  999. return mData->mainXWindow;
  1000. }
  1001. Path LinuxPlatform::getHomeDir()
  1002. {
  1003. const char* homeDir = getenv("HOME");
  1004. if(!homeDir)
  1005. homeDir = getpwuid(getuid())->pw_dir;
  1006. return Path(homeDir);
  1007. }
  1008. void LinuxPlatform::lockX()
  1009. {
  1010. mData->lock.lock();
  1011. }
  1012. void LinuxPlatform::unlockX()
  1013. {
  1014. mData->lock.unlock();
  1015. }
  1016. void LinuxPlatform::_registerWindow(::Window xWindow, LinuxWindow* window)
  1017. {
  1018. // First window is assumed to be the main
  1019. if(mData->mainXWindow == 0)
  1020. {
  1021. mData->mainXWindow = xWindow;
  1022. // Input context client window must be set before use
  1023. XSetICValues(mData->IC,
  1024. XNClientWindow, xWindow,
  1025. XNFocusWindow, xWindow,
  1026. nullptr);
  1027. }
  1028. mData->windowMap[xWindow] = window;
  1029. applyCurrentCursor(mData, xWindow);
  1030. }
  1031. void LinuxPlatform::_unregisterWindow(::Window xWindow)
  1032. {
  1033. auto iterFind = mData->windowMap.find(xWindow);
  1034. if(iterFind != mData->windowMap.end())
  1035. {
  1036. if(mData->cursorClipEnabled && mData->cursorClipWindow == iterFind->second)
  1037. clipCursorDisable();
  1038. mData->windowMap.erase(iterFind);
  1039. }
  1040. if(mData->mainXWindow == xWindow)
  1041. mData->mainXWindow = 0;
  1042. }
  1043. Pixmap LinuxPlatform::createPixmap(const PixelData& data, UINT32 depth)
  1044. {
  1045. // Premultiply alpha
  1046. Vector<Color> colors = data.getColors();
  1047. for(auto& color : colors)
  1048. {
  1049. color.r *= color.a;
  1050. color.g *= color.a;
  1051. color.b *= color.a;
  1052. }
  1053. // Convert to BGRA
  1054. SPtr<PixelData> bgraData = PixelData::create(data.getWidth(), data.getHeight(), 1, PF_BGRA8);
  1055. bgraData->setColors(colors);
  1056. XImage* image = XCreateImage(mData->xDisplay, CopyFromParent, depth, ZPixmap, 0,
  1057. (char*)bgraData->getData(), data.getWidth(), data.getHeight(), 32, 0);
  1058. Pixmap pixmap = XCreatePixmap(mData->xDisplay, XDefaultRootWindow(mData->xDisplay),
  1059. data.getWidth(), data.getHeight(), depth);
  1060. XGCValues gcValues;
  1061. GC gc = XCreateGC(mData->xDisplay, pixmap, 0, &gcValues);
  1062. XPutImage(mData->xDisplay, pixmap, gc, image, 0, 0, 0, 0, data.getWidth(), data.getHeight());
  1063. XFreeGC(mData->xDisplay, gc);
  1064. // Make sure XDestroyImage doesn't free the data pointed to by 'data.bytes'
  1065. image->data = nullptr;
  1066. XDestroyImage(image);
  1067. return pixmap;
  1068. }
  1069. }