BsLinuxPlatform.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  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. 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. OSMouseButton mouseButton;
  663. bool validPress = false;
  664. switch(button)
  665. {
  666. case Button1:
  667. mouseButton = OSMouseButton::Left;
  668. validPress = true;
  669. break;
  670. case Button2:
  671. mouseButton = OSMouseButton::Middle;
  672. validPress = true;
  673. break;
  674. case Button3:
  675. mouseButton = OSMouseButton::Right;
  676. validPress = true;
  677. break;
  678. default:
  679. break;
  680. }
  681. if(validPress)
  682. {
  683. // Send event
  684. Vector2I pos;
  685. pos.x = event.xbutton.x_root;
  686. pos.y = event.xbutton.y_root;
  687. OSPointerButtonStates btnStates;
  688. btnStates.ctrl = (event.xbutton.state & ControlMask) != 0;
  689. btnStates.shift = (event.xbutton.state & ShiftMask) != 0;
  690. btnStates.mouseButtons[0] = (event.xbutton.state & Button1Mask) != 0;
  691. btnStates.mouseButtons[1] = (event.xbutton.state & Button2Mask) != 0;
  692. btnStates.mouseButtons[2] = (event.xbutton.state & Button3Mask) != 0;
  693. onCursorButtonPressed(pos, mouseButton, btnStates);
  694. // Handle double-click
  695. if(button == Button1)
  696. {
  697. if (event.xbutton.time < (mData->lastButtonPressTime + DOUBLE_CLICK_MS))
  698. {
  699. onCursorDoubleClick(pos, btnStates);
  700. mData->lastButtonPressTime = 0;
  701. }
  702. else
  703. mData->lastButtonPressTime = event.xbutton.time;
  704. }
  705. }
  706. // Handle window dragging for windows without a title bar
  707. if(button == Button1)
  708. {
  709. LinuxWindow* window = getLinuxWindow(mData, event.xbutton.window);
  710. if(window != nullptr)
  711. window->_dragStart(event.xbutton);
  712. }
  713. break;
  714. }
  715. case ButtonRelease:
  716. {
  717. UINT32 button = event.xbutton.button;
  718. Vector2I pos;
  719. pos.x = event.xbutton.x_root;
  720. pos.y = event.xbutton.y_root;
  721. OSPointerButtonStates btnStates;
  722. btnStates.ctrl = (event.xbutton.state & ControlMask) != 0;
  723. btnStates.shift = (event.xbutton.state & ShiftMask) != 0;
  724. btnStates.mouseButtons[0] = (event.xbutton.state & Button1Mask) != 0;
  725. btnStates.mouseButtons[1] = (event.xbutton.state & Button2Mask) != 0;
  726. btnStates.mouseButtons[2] = (event.xbutton.state & Button3Mask) != 0;
  727. switch(button)
  728. {
  729. case Button1:
  730. onCursorButtonReleased(pos, OSMouseButton::Left, btnStates);
  731. break;
  732. case Button2:
  733. onCursorButtonReleased(pos, OSMouseButton::Middle, btnStates);
  734. break;
  735. case Button3:
  736. onCursorButtonReleased(pos, OSMouseButton::Right, btnStates);
  737. break;
  738. case Button4: // Vertical mouse wheel
  739. case Button5:
  740. {
  741. INT32 delta = button == Button4 ? 1 : -1;
  742. onMouseWheelScrolled((float)delta);
  743. }
  744. break;
  745. default:
  746. break;
  747. }
  748. // Handle window dragging for windows without a title bar
  749. if(button == Button1)
  750. {
  751. LinuxWindow* window = getLinuxWindow(mData, event.xbutton.window);
  752. if(window != nullptr)
  753. window->_dragEnd();
  754. }
  755. break;
  756. }
  757. case MotionNotify:
  758. {
  759. Vector2I pos;
  760. pos.x = event.xmotion.x_root;
  761. pos.y = event.xmotion.y_root;
  762. // Handle clipping if enabled
  763. if(clipCursor(mData, pos))
  764. _setCursorPosition(mData, pos);
  765. // Send event
  766. OSPointerButtonStates btnStates;
  767. btnStates.ctrl = (event.xmotion.state & ControlMask) != 0;
  768. btnStates.shift = (event.xmotion.state & ShiftMask) != 0;
  769. btnStates.mouseButtons[0] = (event.xmotion.state & Button1Mask) != 0;
  770. btnStates.mouseButtons[1] = (event.xmotion.state & Button2Mask) != 0;
  771. btnStates.mouseButtons[2] = (event.xmotion.state & Button3Mask) != 0;
  772. onCursorMoved(pos, btnStates);
  773. }
  774. break;
  775. case EnterNotify:
  776. // Do nothing
  777. break;
  778. case LeaveNotify:
  779. {
  780. if (event.xcrossing.mode == NotifyNormal)
  781. {
  782. Vector2I pos;
  783. pos.x = event.xcrossing.x_root;
  784. pos.y = event.xcrossing.y_root;
  785. if (clipCursor(mData, pos))
  786. _setCursorPosition(mData, pos);
  787. }
  788. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xcrossing.window);
  789. if(renderWindow != nullptr)
  790. renderWindow->_notifyMouseLeft();
  791. }
  792. break;
  793. case ConfigureNotify:
  794. {
  795. LinuxWindow* window = getLinuxWindow(mData, event.xconfigure.window);
  796. if(window != nullptr)
  797. {
  798. updateClipBounds(mData, window);
  799. ct::RenderWindow* renderWindow = (ct::RenderWindow*)window->_getUserData();
  800. if(renderWindow != nullptr)
  801. renderWindow->_windowMovedOrResized();
  802. }
  803. }
  804. break;
  805. case FocusIn:
  806. {
  807. // Update input context focus
  808. XSetICFocus(mData->IC);
  809. // Send event to render window
  810. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xfocus.window);
  811. // Not a render window, so it doesn't care about these events
  812. if (renderWindow != nullptr)
  813. {
  814. if (!renderWindow->getProperties().hasFocus)
  815. renderWindow->_windowFocusReceived();
  816. }
  817. }
  818. break;
  819. case FocusOut:
  820. {
  821. // Update input context focus
  822. XUnsetICFocus(mData->IC);
  823. // Send event to render window
  824. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xfocus.window);
  825. // Not a render window, so it doesn't care about these events
  826. if (renderWindow != nullptr)
  827. {
  828. if (renderWindow->getProperties().hasFocus)
  829. renderWindow->_windowFocusLost();
  830. }
  831. }
  832. break;
  833. case SelectionNotify:
  834. LinuxDragAndDrop::handleSelectionNotify(event.xselection);
  835. break;
  836. case SelectionRequest:
  837. {
  838. // Send the data saved by the last clipboard copy operation
  839. Atom compoundTextAtom = XInternAtom(mData->xDisplay, "COMPOUND_TEXT", 0);
  840. Atom utf8StringAtom = XInternAtom(mData->xDisplay, "UTF8_STRING", 0);
  841. Atom targetsAtom = XInternAtom(mData->xDisplay, "TARGETS", 0);
  842. XSelectionRequestEvent& selReq = event.xselectionrequest;
  843. XEvent response;
  844. if(selReq.target == XA_STRING || selReq.target == compoundTextAtom || selReq.target == utf8StringAtom)
  845. {
  846. String utf8data = UTF8::fromWide(mData->clipboardData);
  847. const UINT8* data = (const UINT8*)utf8data.c_str();
  848. INT32 dataLength = (INT32)utf8data.length();
  849. XChangeProperty(mData->xDisplay, selReq.requestor, selReq.property,
  850. selReq.target, 8, PropModeReplace, data, dataLength);
  851. response.xselection.property = selReq.property;
  852. }
  853. else if(selReq.target == targetsAtom)
  854. {
  855. Atom data[2];
  856. data[0] = utf8StringAtom;
  857. data[1] = XA_STRING;
  858. XChangeProperty (mData->xDisplay, selReq.requestor, selReq.property, selReq.target,
  859. 8, PropModeReplace, (unsigned char*)&data, sizeof (data));
  860. response.xselection.property = selReq.property;
  861. }
  862. else
  863. {
  864. response.xselection.property = None;
  865. }
  866. response.xselection.type = SelectionNotify;
  867. response.xselection.display = selReq.display;
  868. response.xselection.requestor = selReq.requestor;
  869. response.xselection.selection = selReq.selection;
  870. response.xselection.target = selReq.target;
  871. response.xselection.time = selReq.time;
  872. XSendEvent (mData->xDisplay, selReq.requestor, 0, 0, &response);
  873. XFlush (mData->xDisplay);
  874. }
  875. break;
  876. case PropertyNotify:
  877. // Report minimize, maximize and restore events
  878. if(event.xproperty.atom == mData->atomWmState)
  879. {
  880. // Check that the window hasn't been destroyed
  881. if(getLinuxWindow(mData, event.xproperty.window) == nullptr)
  882. break;
  883. Atom type;
  884. INT32 format;
  885. unsigned long count, bytesRemaining;
  886. UINT8* data = nullptr;
  887. INT32 result = XGetWindowProperty(mData->xDisplay, event.xproperty.window, mData->atomWmState,
  888. 0, 1024, False, AnyPropertyType, &type, &format,
  889. &count, &bytesRemaining, &data);
  890. if (result == Success)
  891. {
  892. ct::RenderWindow* renderWindow = getRenderWindow(mData, event.xproperty.window);
  893. // Not a render window, so it doesn't care about these events
  894. if(renderWindow == nullptr)
  895. continue;
  896. Atom* atoms = (Atom*)data;
  897. bool foundHorz = false;
  898. bool foundVert = false;
  899. for (unsigned long i = 0; i < count; i++)
  900. {
  901. if (atoms[i] == mData->atomWmStateMaxHorz) foundHorz = true;
  902. if (atoms[i] == mData->atomWmStateMaxVert) foundVert = true;
  903. if (foundVert && foundHorz)
  904. {
  905. if(event.xproperty.state == PropertyNewValue)
  906. renderWindow->_notifyMaximized();
  907. else
  908. renderWindow->_notifyRestored();
  909. }
  910. if(atoms[i] == mData->atomWmStateHidden)
  911. {
  912. if(event.xproperty.state == PropertyNewValue)
  913. renderWindow->_notifyMinimized();
  914. else
  915. renderWindow->_notifyRestored();
  916. }
  917. }
  918. XFree(atoms);
  919. }
  920. }
  921. break;
  922. default:
  923. break;
  924. }
  925. }
  926. }
  927. void Platform::_startUp()
  928. {
  929. Lock lock(mData->lock);
  930. mData->xDisplay = XOpenDisplay(nullptr);
  931. XSetErrorHandler(x11ErrorHandler);
  932. if(XSupportsLocale())
  933. {
  934. XSetLocaleModifiers("@im=none");
  935. mData->IM = XOpenIM(mData->xDisplay, nullptr, nullptr, nullptr);
  936. // Note: Currently our windows don't support pre-edit and status areas, which are used for more complex types
  937. // of character input. Later on it might be beneficial to support them.
  938. mData->IC = XCreateIC(mData->IM, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, nullptr);
  939. }
  940. mData->atomDeleteWindow = XInternAtom(mData->xDisplay, "WM_DELETE_WINDOW", False);
  941. mData->atomWmState = XInternAtom(mData->xDisplay, "_NET_WM_STATE", False);
  942. mData->atomWmStateHidden = XInternAtom(mData->xDisplay, "_NET_WM_STATE_HIDDEN", False);
  943. mData->atomWmStateMaxHorz = XInternAtom(mData->xDisplay, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  944. mData->atomWmStateMaxVert = XInternAtom(mData->xDisplay, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  945. // Drag and drop
  946. LinuxDragAndDrop::startUp(mData->xDisplay);
  947. // Create empty cursor
  948. char data[1];
  949. memset(data, 0, sizeof(data));
  950. Pixmap pixmap = XCreateBitmapFromData(mData->xDisplay, DefaultRootWindow(mData->xDisplay), data, 1, 1);
  951. XColor color;
  952. color.red = color.green = color.blue = 0;
  953. mData->emptyCursor = XCreatePixmapCursor(mData->xDisplay, pixmap, pixmap, &color, &color, 0, 0);
  954. XFreePixmap(mData->xDisplay, pixmap);
  955. }
  956. void Platform::_update()
  957. {
  958. LinuxDragAndDrop::update();
  959. }
  960. void Platform::_coreUpdate()
  961. {
  962. _messagePump();
  963. }
  964. void Platform::_shutDown()
  965. {
  966. Lock lock(mData->lock);
  967. // Free empty cursor
  968. XFreeCursor(mData->xDisplay, mData->emptyCursor);
  969. mData->emptyCursor = None;
  970. // Shutdown drag and drop
  971. LinuxDragAndDrop::shutDown();
  972. if(mData->IC)
  973. {
  974. XDestroyIC(mData->IC);
  975. mData->IC = 0;
  976. }
  977. if(mData->IM)
  978. {
  979. XCloseIM(mData->IM);
  980. mData->IM = 0;
  981. }
  982. XCloseDisplay(mData->xDisplay);
  983. mData->xDisplay = nullptr;
  984. bs_delete(mData);
  985. mData = nullptr;
  986. }
  987. ::Display* LinuxPlatform::getXDisplay()
  988. {
  989. return mData->xDisplay;
  990. }
  991. ::Window LinuxPlatform::getMainXWindow()
  992. {
  993. return mData->mainXWindow;
  994. }
  995. Path LinuxPlatform::getHomeDir()
  996. {
  997. const char* homeDir = getenv("HOME");
  998. if(!homeDir)
  999. homeDir = getpwuid(getuid())->pw_dir;
  1000. return Path(homeDir);
  1001. }
  1002. void LinuxPlatform::lockX()
  1003. {
  1004. mData->lock.lock();
  1005. }
  1006. void LinuxPlatform::unlockX()
  1007. {
  1008. mData->lock.unlock();
  1009. }
  1010. void LinuxPlatform::_registerWindow(::Window xWindow, LinuxWindow* window)
  1011. {
  1012. // First window is assumed to be the main
  1013. if(mData->mainXWindow == 0)
  1014. {
  1015. mData->mainXWindow = xWindow;
  1016. // Input context client window must be set before use
  1017. XSetICValues(mData->IC,
  1018. XNClientWindow, xWindow,
  1019. XNFocusWindow, xWindow,
  1020. nullptr);
  1021. }
  1022. mData->windowMap[xWindow] = window;
  1023. applyCurrentCursor(mData, xWindow);
  1024. }
  1025. void LinuxPlatform::_unregisterWindow(::Window xWindow)
  1026. {
  1027. auto iterFind = mData->windowMap.find(xWindow);
  1028. if(iterFind != mData->windowMap.end())
  1029. {
  1030. if(mData->cursorClipEnabled && mData->cursorClipWindow == iterFind->second)
  1031. clipCursorDisable();
  1032. mData->windowMap.erase(iterFind);
  1033. }
  1034. if(mData->mainXWindow == xWindow)
  1035. mData->mainXWindow = 0;
  1036. }
  1037. Pixmap LinuxPlatform::createPixmap(const PixelData& data, UINT32 depth)
  1038. {
  1039. // Premultiply alpha
  1040. Vector<Color> colors = data.getColors();
  1041. for(auto& color : colors)
  1042. {
  1043. color.r *= color.a;
  1044. color.g *= color.a;
  1045. color.b *= color.a;
  1046. }
  1047. // Convert to BGRA
  1048. SPtr<PixelData> bgraData = PixelData::create(data.getWidth(), data.getHeight(), 1, PF_BGRA8);
  1049. bgraData->setColors(colors);
  1050. XImage* image = XCreateImage(mData->xDisplay, CopyFromParent, depth, ZPixmap, 0,
  1051. (char*)bgraData->getData(), data.getWidth(), data.getHeight(), 32, 0);
  1052. Pixmap pixmap = XCreatePixmap(mData->xDisplay, XDefaultRootWindow(mData->xDisplay),
  1053. data.getWidth(), data.getHeight(), depth);
  1054. XGCValues gcValues;
  1055. GC gc = XCreateGC(mData->xDisplay, pixmap, 0, &gcValues);
  1056. XPutImage(mData->xDisplay, pixmap, gc, image, 0, 0, 0, 0, data.getWidth(), data.getHeight());
  1057. XFreeGC(mData->xDisplay, gc);
  1058. // Make sure XDestroyImage doesn't free the data pointed to by 'data.bytes'
  1059. image->data = nullptr;
  1060. XDestroyImage(image);
  1061. return pixmap;
  1062. }
  1063. }