The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3366 lines
130KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. #include <unordered_map>
  14. namespace juce
  15. {
  16. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  17. #define JUCE_DEBUG_XERRORS 1
  18. #endif
  19. #if JUCE_MODULE_AVAILABLE_juce_gui_extra
  20. #define JUCE_X11_SUPPORTS_XEMBED 1
  21. #else
  22. #define JUCE_X11_SUPPORTS_XEMBED 0
  23. #endif
  24. //==============================================================================
  25. XWindowSystemUtilities::ScopedXLock::ScopedXLock()
  26. {
  27. if (auto* xWindow = XWindowSystem::getInstanceWithoutCreating())
  28. if (auto* d = xWindow->getDisplay())
  29. X11Symbols::getInstance()->xLockDisplay (d);
  30. }
  31. XWindowSystemUtilities::ScopedXLock::~ScopedXLock()
  32. {
  33. if (auto* xWindow = XWindowSystem::getInstanceWithoutCreating())
  34. if (auto* d = xWindow->getDisplay())
  35. X11Symbols::getInstance()->xUnlockDisplay (d);
  36. }
  37. //==============================================================================
  38. XWindowSystemUtilities::Atoms::Atoms (::Display* display)
  39. {
  40. protocols = getIfExists (display, "WM_PROTOCOLS");
  41. protocolList [TAKE_FOCUS] = getIfExists (display, "WM_TAKE_FOCUS");
  42. protocolList [DELETE_WINDOW] = getIfExists (display, "WM_DELETE_WINDOW");
  43. protocolList [PING] = getIfExists (display, "_NET_WM_PING");
  44. changeState = getIfExists (display, "WM_CHANGE_STATE");
  45. state = getIfExists (display, "WM_STATE");
  46. userTime = getCreating (display, "_NET_WM_USER_TIME");
  47. activeWin = getCreating (display, "_NET_ACTIVE_WINDOW");
  48. pid = getCreating (display, "_NET_WM_PID");
  49. windowType = getIfExists (display, "_NET_WM_WINDOW_TYPE");
  50. windowState = getIfExists (display, "_NET_WM_STATE");
  51. XdndAware = getCreating (display, "XdndAware");
  52. XdndEnter = getCreating (display, "XdndEnter");
  53. XdndLeave = getCreating (display, "XdndLeave");
  54. XdndPosition = getCreating (display, "XdndPosition");
  55. XdndStatus = getCreating (display, "XdndStatus");
  56. XdndDrop = getCreating (display, "XdndDrop");
  57. XdndFinished = getCreating (display, "XdndFinished");
  58. XdndSelection = getCreating (display, "XdndSelection");
  59. XdndTypeList = getCreating (display, "XdndTypeList");
  60. XdndActionList = getCreating (display, "XdndActionList");
  61. XdndActionCopy = getCreating (display, "XdndActionCopy");
  62. XdndActionPrivate = getCreating (display, "XdndActionPrivate");
  63. XdndActionDescription = getCreating (display, "XdndActionDescription");
  64. XembedMsgType = getCreating (display, "_XEMBED");
  65. XembedInfo = getCreating (display, "_XEMBED_INFO");
  66. allowedMimeTypes[0] = getCreating (display, "UTF8_STRING");
  67. allowedMimeTypes[1] = getCreating (display, "text/plain;charset=utf-8");
  68. allowedMimeTypes[2] = getCreating (display, "text/plain");
  69. allowedMimeTypes[3] = getCreating (display, "text/uri-list");
  70. allowedActions[0] = getCreating (display, "XdndActionMove");
  71. allowedActions[1] = XdndActionCopy;
  72. allowedActions[2] = getCreating (display, "XdndActionLink");
  73. allowedActions[3] = getCreating (display, "XdndActionAsk");
  74. allowedActions[4] = XdndActionPrivate;
  75. utf8String = getCreating (display, "UTF8_STRING");
  76. clipboard = getCreating (display, "CLIPBOARD");
  77. targets = getCreating (display, "TARGETS");
  78. }
  79. Atom XWindowSystemUtilities::Atoms::getIfExists (::Display* display, const char* name)
  80. {
  81. return X11Symbols::getInstance()->xInternAtom (display, name, True);
  82. }
  83. Atom XWindowSystemUtilities::Atoms::getCreating (::Display* display, const char* name)
  84. {
  85. return X11Symbols::getInstance()->xInternAtom (display, name, False);
  86. }
  87. String XWindowSystemUtilities::Atoms::getName (::Display* display, Atom atom)
  88. {
  89. if (atom == None)
  90. return "None";
  91. return X11Symbols::getInstance()->xGetAtomName (display, atom);
  92. }
  93. bool XWindowSystemUtilities::Atoms::isMimeTypeFile (::Display* display, Atom atom)
  94. {
  95. return getName (display, atom).equalsIgnoreCase ("text/uri-list");
  96. }
  97. //==============================================================================
  98. XWindowSystemUtilities::GetXProperty::GetXProperty (Window window, Atom atom, long offset,
  99. long length, bool shouldDelete, Atom requestedType)
  100. {
  101. success = (X11Symbols::getInstance()->xGetWindowProperty (XWindowSystem::getInstance()->getDisplay(),
  102. window, atom, offset, length,
  103. (Bool) shouldDelete, requestedType, &actualType,
  104. &actualFormat, &numItems, &bytesLeft, &data) == Success)
  105. && data != nullptr;
  106. }
  107. XWindowSystemUtilities::GetXProperty::~GetXProperty()
  108. {
  109. if (data != nullptr)
  110. X11Symbols::getInstance()->xFree (data);
  111. }
  112. //==============================================================================
  113. using WindowMessageReceiveCallback = void (*) (XEvent&);
  114. using SelectionRequestCallback = void (*) (XSelectionRequestEvent&);
  115. static WindowMessageReceiveCallback dispatchWindowMessage = nullptr;
  116. SelectionRequestCallback handleSelectionRequest = nullptr;
  117. ::Window juce_messageWindowHandle;
  118. XContext windowHandleXContext;
  119. #if JUCE_X11_SUPPORTS_XEMBED
  120. bool juce_handleXEmbedEvent (ComponentPeer*, void*);
  121. unsigned long juce_getCurrentFocusWindow (ComponentPeer*);
  122. #endif
  123. struct MotifWmHints
  124. {
  125. unsigned long flags = 0, functions = 0, decorations = 0, status = 0;
  126. long input_mode = 0;
  127. };
  128. //=============================== X11 - Error Handling =========================
  129. namespace X11ErrorHandling
  130. {
  131. static XErrorHandler oldErrorHandler = {};
  132. static XIOErrorHandler oldIOErrorHandler = {};
  133. // Usually happens when client-server connection is broken
  134. static int ioErrorHandler (::Display*)
  135. {
  136. DBG ("ERROR: connection to X server broken.. terminating.");
  137. if (JUCEApplicationBase::isStandaloneApp())
  138. MessageManager::getInstance()->stopDispatchLoop();
  139. return 0;
  140. }
  141. static int errorHandler (::Display* display, XErrorEvent* event)
  142. {
  143. ignoreUnused (display, event);
  144. #if JUCE_DEBUG_XERRORS
  145. char errorStr[64] = { 0 };
  146. char requestStr[64] = { 0 };
  147. X11Symbols::getInstance()->xGetErrorText (display, event->error_code, errorStr, 64);
  148. X11Symbols::getInstance()->xGetErrorDatabaseText (display, "XRequest", String (event->request_code).toUTF8(), "Unknown", requestStr, 64);
  149. DBG ("ERROR: X returned " << errorStr << " for operation " << requestStr);
  150. #endif
  151. return 0;
  152. }
  153. static void installXErrorHandlers()
  154. {
  155. oldIOErrorHandler = X11Symbols::getInstance()->xSetIOErrorHandler (ioErrorHandler);
  156. oldErrorHandler = X11Symbols::getInstance()->xSetErrorHandler (errorHandler);
  157. }
  158. static void removeXErrorHandlers()
  159. {
  160. X11Symbols::getInstance()->xSetIOErrorHandler (oldIOErrorHandler);
  161. oldIOErrorHandler = {};
  162. X11Symbols::getInstance()->xSetErrorHandler (oldErrorHandler);
  163. oldErrorHandler = {};
  164. }
  165. }
  166. //=============================== X11 - Keys ===================================
  167. namespace Keys
  168. {
  169. enum MouseButtons
  170. {
  171. NoButton = 0,
  172. LeftButton = 1,
  173. MiddleButton = 2,
  174. RightButton = 3,
  175. WheelUp = 4,
  176. WheelDown = 5
  177. };
  178. static int AltMask = 0;
  179. static int NumLockMask = 0;
  180. static bool numLock = false;
  181. static bool capsLock = false;
  182. static char keyStates [32];
  183. static constexpr int extendedKeyModifier = 0x10000000;
  184. }
  185. const int KeyPress::spaceKey = XK_space & 0xff;
  186. const int KeyPress::returnKey = XK_Return & 0xff;
  187. const int KeyPress::escapeKey = XK_Escape & 0xff;
  188. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  189. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  190. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  191. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  192. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  193. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  194. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  195. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  196. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  197. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  198. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  199. const int KeyPress::tabKey = XK_Tab & 0xff;
  200. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  201. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  202. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  203. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  204. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  205. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  206. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  207. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  208. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  209. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  210. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  211. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  212. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  213. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  214. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  215. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  216. const int KeyPress::F17Key = (XK_F17 & 0xff) | Keys::extendedKeyModifier;
  217. const int KeyPress::F18Key = (XK_F18 & 0xff) | Keys::extendedKeyModifier;
  218. const int KeyPress::F19Key = (XK_F19 & 0xff) | Keys::extendedKeyModifier;
  219. const int KeyPress::F20Key = (XK_F20 & 0xff) | Keys::extendedKeyModifier;
  220. const int KeyPress::F21Key = (XK_F21 & 0xff) | Keys::extendedKeyModifier;
  221. const int KeyPress::F22Key = (XK_F22 & 0xff) | Keys::extendedKeyModifier;
  222. const int KeyPress::F23Key = (XK_F23 & 0xff) | Keys::extendedKeyModifier;
  223. const int KeyPress::F24Key = (XK_F24 & 0xff) | Keys::extendedKeyModifier;
  224. const int KeyPress::F25Key = (XK_F25 & 0xff) | Keys::extendedKeyModifier;
  225. const int KeyPress::F26Key = (XK_F26 & 0xff) | Keys::extendedKeyModifier;
  226. const int KeyPress::F27Key = (XK_F27 & 0xff) | Keys::extendedKeyModifier;
  227. const int KeyPress::F28Key = (XK_F28 & 0xff) | Keys::extendedKeyModifier;
  228. const int KeyPress::F29Key = (XK_F29 & 0xff) | Keys::extendedKeyModifier;
  229. const int KeyPress::F30Key = (XK_F30 & 0xff) | Keys::extendedKeyModifier;
  230. const int KeyPress::F31Key = (XK_F31 & 0xff) | Keys::extendedKeyModifier;
  231. const int KeyPress::F32Key = (XK_F32 & 0xff) | Keys::extendedKeyModifier;
  232. const int KeyPress::F33Key = (XK_F33 & 0xff) | Keys::extendedKeyModifier;
  233. const int KeyPress::F34Key = (XK_F34 & 0xff) | Keys::extendedKeyModifier;
  234. const int KeyPress::F35Key = (XK_F35 & 0xff) | Keys::extendedKeyModifier;
  235. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  236. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  237. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  238. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  239. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  240. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  241. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  242. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff) | Keys::extendedKeyModifier;
  243. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff) | Keys::extendedKeyModifier;
  244. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff) | Keys::extendedKeyModifier;
  245. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff) | Keys::extendedKeyModifier;
  246. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff) | Keys::extendedKeyModifier;
  247. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff) | Keys::extendedKeyModifier;
  248. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff) | Keys::extendedKeyModifier;
  249. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff) | Keys::extendedKeyModifier;
  250. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff) | Keys::extendedKeyModifier;
  251. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff) | Keys::extendedKeyModifier;
  252. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff) | Keys::extendedKeyModifier;
  253. const int KeyPress::playKey = ((int) 0xffeeff00) | Keys::extendedKeyModifier;
  254. const int KeyPress::stopKey = ((int) 0xffeeff01) | Keys::extendedKeyModifier;
  255. const int KeyPress::fastForwardKey = ((int) 0xffeeff02) | Keys::extendedKeyModifier;
  256. const int KeyPress::rewindKey = ((int) 0xffeeff03) | Keys::extendedKeyModifier;
  257. static void updateKeyStates (int keycode, bool press) noexcept
  258. {
  259. auto keybyte = keycode >> 3;
  260. auto keybit = (1 << (keycode & 7));
  261. if (press)
  262. Keys::keyStates [keybyte] |= keybit;
  263. else
  264. Keys::keyStates [keybyte] &= ~keybit;
  265. }
  266. static void updateKeyModifiers (int status) noexcept
  267. {
  268. int keyMods = 0;
  269. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  270. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  271. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  272. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  273. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  274. Keys::capsLock = ((status & LockMask) != 0);
  275. }
  276. static bool updateKeyModifiersFromSym (KeySym sym, bool press) noexcept
  277. {
  278. int modifier = 0;
  279. bool isModifier = true;
  280. switch (sym)
  281. {
  282. case XK_Shift_L:
  283. case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
  284. case XK_Control_L:
  285. case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
  286. case XK_Alt_L:
  287. case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
  288. case XK_Num_Lock:
  289. if (press)
  290. Keys::numLock = ! Keys::numLock;
  291. break;
  292. case XK_Caps_Lock:
  293. if (press)
  294. Keys::capsLock = ! Keys::capsLock;
  295. break;
  296. case XK_Scroll_Lock:
  297. break;
  298. default:
  299. isModifier = false;
  300. break;
  301. }
  302. ModifierKeys::currentModifiers = press ? ModifierKeys::currentModifiers.withFlags (modifier)
  303. : ModifierKeys::currentModifiers.withoutFlags (modifier);
  304. return isModifier;
  305. }
  306. enum
  307. {
  308. KeyPressEventType = 2
  309. };
  310. //================================== X11 - Shm =================================
  311. #if JUCE_USE_XSHM
  312. namespace XSHMHelpers
  313. {
  314. static int trappedErrorCode = 0;
  315. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  316. {
  317. trappedErrorCode = err->error_code;
  318. return 0;
  319. }
  320. static bool isShmAvailable (::Display* display)
  321. {
  322. static bool isChecked = false;
  323. static bool isAvailable = false;
  324. if (! isChecked)
  325. {
  326. isChecked = true;
  327. if (display != nullptr)
  328. {
  329. int major, minor;
  330. Bool pixmaps;
  331. XWindowSystemUtilities::ScopedXLock xLock;
  332. if (X11Symbols::getInstance()->xShmQueryVersion (display, &major, &minor, &pixmaps))
  333. {
  334. trappedErrorCode = 0;
  335. auto oldHandler = X11Symbols::getInstance()->xSetErrorHandler (errorTrapHandler);
  336. XShmSegmentInfo segmentInfo;
  337. zerostruct (segmentInfo);
  338. if (auto* xImage = X11Symbols::getInstance()->xShmCreateImage (display,
  339. X11Symbols::getInstance()->xDefaultVisual (display, X11Symbols::getInstance()->xDefaultScreen (display)),
  340. 24, ZPixmap, nullptr, &segmentInfo, 50, 50))
  341. {
  342. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  343. (size_t) (xImage->bytes_per_line * xImage->height),
  344. IPC_CREAT | 0777)) >= 0)
  345. {
  346. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, nullptr, 0);
  347. if (segmentInfo.shmaddr != (void*) -1)
  348. {
  349. segmentInfo.readOnly = False;
  350. xImage->data = segmentInfo.shmaddr;
  351. X11Symbols::getInstance()->xSync (display, False);
  352. if (X11Symbols::getInstance()->xShmAttach (display, &segmentInfo) != 0)
  353. {
  354. X11Symbols::getInstance()->xSync (display, False);
  355. X11Symbols::getInstance()->xShmDetach (display, &segmentInfo);
  356. isAvailable = true;
  357. }
  358. }
  359. X11Symbols::getInstance()->xFlush (display);
  360. X11Symbols::getInstance()->xDestroyImage (xImage);
  361. shmdt (segmentInfo.shmaddr);
  362. }
  363. shmctl (segmentInfo.shmid, IPC_RMID, nullptr);
  364. X11Symbols::getInstance()->xSetErrorHandler (oldHandler);
  365. if (trappedErrorCode != 0)
  366. isAvailable = false;
  367. }
  368. }
  369. }
  370. }
  371. return isAvailable;
  372. }
  373. }
  374. #endif
  375. //=============================== X11 - Render =================================
  376. #if JUCE_USE_XRENDER
  377. namespace XRender
  378. {
  379. static bool isAvailable (::Display* display)
  380. {
  381. int major, minor;
  382. return X11Symbols::getInstance()->xRenderQueryVersion (display, &major, &minor);
  383. }
  384. static bool hasCompositingWindowManager (::Display* display)
  385. {
  386. return display != nullptr
  387. && X11Symbols::getInstance()->xGetSelectionOwner (display,
  388. XWindowSystemUtilities::Atoms::getCreating (display, "_NET_WM_CM_S0")) != 0;
  389. }
  390. static XRenderPictFormat* findPictureFormat (::Display* display)
  391. {
  392. XWindowSystemUtilities::ScopedXLock xLock;
  393. if (isAvailable (display))
  394. {
  395. if (auto* pictFormat = X11Symbols::getInstance()->xRenderFindStandardFormat (display, PictStandardARGB32))
  396. {
  397. XRenderPictFormat desiredFormat;
  398. desiredFormat.type = PictTypeDirect;
  399. desiredFormat.depth = 32;
  400. desiredFormat.direct.alphaMask = 0xff;
  401. desiredFormat.direct.redMask = 0xff;
  402. desiredFormat.direct.greenMask = 0xff;
  403. desiredFormat.direct.blueMask = 0xff;
  404. desiredFormat.direct.alpha = 24;
  405. desiredFormat.direct.red = 16;
  406. desiredFormat.direct.green = 8;
  407. desiredFormat.direct.blue = 0;
  408. pictFormat = X11Symbols::getInstance()->xRenderFindFormat (display,
  409. PictFormatType | PictFormatDepth
  410. | PictFormatRedMask | PictFormatRed
  411. | PictFormatGreenMask | PictFormatGreen
  412. | PictFormatBlueMask | PictFormatBlue
  413. | PictFormatAlphaMask | PictFormatAlpha,
  414. &desiredFormat,
  415. 0);
  416. return pictFormat;
  417. }
  418. }
  419. return nullptr;
  420. }
  421. }
  422. #endif
  423. //================================ X11 - Visuals ===============================
  424. namespace Visuals
  425. {
  426. static Visual* findVisualWithDepth (::Display* display, int desiredDepth)
  427. {
  428. XWindowSystemUtilities::ScopedXLock xLock;
  429. Visual* visual = nullptr;
  430. int numVisuals = 0;
  431. auto desiredMask = VisualNoMask;
  432. XVisualInfo desiredVisual;
  433. desiredVisual.screen = X11Symbols::getInstance()->xDefaultScreen (display);
  434. desiredVisual.depth = desiredDepth;
  435. desiredMask = VisualScreenMask | VisualDepthMask;
  436. if (desiredDepth == 32)
  437. {
  438. desiredVisual.c_class = TrueColor;
  439. desiredVisual.red_mask = 0x00FF0000;
  440. desiredVisual.green_mask = 0x0000FF00;
  441. desiredVisual.blue_mask = 0x000000FF;
  442. desiredVisual.bits_per_rgb = 8;
  443. desiredMask |= VisualClassMask;
  444. desiredMask |= VisualRedMaskMask;
  445. desiredMask |= VisualGreenMaskMask;
  446. desiredMask |= VisualBlueMaskMask;
  447. desiredMask |= VisualBitsPerRGBMask;
  448. }
  449. if (auto* xvinfos = X11Symbols::getInstance()->xGetVisualInfo (display, desiredMask, &desiredVisual, &numVisuals))
  450. {
  451. for (int i = 0; i < numVisuals; i++)
  452. {
  453. if (xvinfos[i].depth == desiredDepth)
  454. {
  455. visual = xvinfos[i].visual;
  456. break;
  457. }
  458. }
  459. X11Symbols::getInstance()->xFree (xvinfos);
  460. }
  461. return visual;
  462. }
  463. static Visual* findVisualFormat (::Display* display, int desiredDepth, int& matchedDepth)
  464. {
  465. Visual* visual = nullptr;
  466. if (desiredDepth == 32)
  467. {
  468. #if JUCE_USE_XSHM
  469. if (XSHMHelpers::isShmAvailable (display))
  470. {
  471. #if JUCE_USE_XRENDER
  472. if (XRender::isAvailable (display))
  473. {
  474. if (XRender::findPictureFormat (display) != nullptr)
  475. {
  476. int numVisuals = 0;
  477. XVisualInfo desiredVisual;
  478. desiredVisual.screen = X11Symbols::getInstance()->xDefaultScreen (display);
  479. desiredVisual.depth = 32;
  480. desiredVisual.bits_per_rgb = 8;
  481. if (auto xvinfos = X11Symbols::getInstance()->xGetVisualInfo (display,
  482. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  483. &desiredVisual, &numVisuals))
  484. {
  485. for (int i = 0; i < numVisuals; ++i)
  486. {
  487. auto pictVisualFormat = X11Symbols::getInstance()->xRenderFindVisualFormat (display, xvinfos[i].visual);
  488. if (pictVisualFormat != nullptr
  489. && pictVisualFormat->type == PictTypeDirect
  490. && pictVisualFormat->direct.alphaMask)
  491. {
  492. visual = xvinfos[i].visual;
  493. matchedDepth = 32;
  494. break;
  495. }
  496. }
  497. X11Symbols::getInstance()->xFree (xvinfos);
  498. }
  499. }
  500. }
  501. #endif
  502. if (visual == nullptr)
  503. {
  504. visual = findVisualWithDepth (display, 32);
  505. if (visual != nullptr)
  506. matchedDepth = 32;
  507. }
  508. }
  509. #endif
  510. }
  511. if (visual == nullptr && desiredDepth >= 24)
  512. {
  513. visual = findVisualWithDepth (display, 24);
  514. if (visual != nullptr)
  515. matchedDepth = 24;
  516. }
  517. if (visual == nullptr && desiredDepth >= 16)
  518. {
  519. visual = findVisualWithDepth (display, 16);
  520. if (visual != nullptr)
  521. matchedDepth = 16;
  522. }
  523. return visual;
  524. }
  525. }
  526. //================================= X11 - Bitmap ===============================
  527. static std::unordered_map<::Window, int> shmPaintsPendingMap;
  528. class XBitmapImage : public ImagePixelData
  529. {
  530. public:
  531. XBitmapImage (::Display* d, Image::PixelFormat format, int w, int h,
  532. bool clearImage, unsigned int imageDepth_, Visual* visual)
  533. : ImagePixelData (format, w, h),
  534. imageDepth (imageDepth_),
  535. display (d)
  536. {
  537. jassert (format == Image::RGB || format == Image::ARGB);
  538. pixelStride = (format == Image::RGB) ? 3 : 4;
  539. lineStride = ((w * pixelStride + 3) & ~3);
  540. XWindowSystemUtilities::ScopedXLock xLock;
  541. #if JUCE_USE_XSHM
  542. usingXShm = false;
  543. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable (display))
  544. {
  545. zerostruct (segmentInfo);
  546. segmentInfo.shmid = -1;
  547. segmentInfo.shmaddr = (char *) -1;
  548. segmentInfo.readOnly = False;
  549. xImage = X11Symbols::getInstance()->xShmCreateImage (display, visual, imageDepth, ZPixmap, nullptr,
  550. &segmentInfo, (unsigned int) w, (unsigned int) h);
  551. if (xImage != nullptr)
  552. {
  553. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  554. (size_t) (xImage->bytes_per_line * xImage->height),
  555. IPC_CREAT | 0777)) >= 0)
  556. {
  557. if (segmentInfo.shmid != -1)
  558. {
  559. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, nullptr, 0);
  560. if (segmentInfo.shmaddr != (void*) -1)
  561. {
  562. segmentInfo.readOnly = False;
  563. xImage->data = segmentInfo.shmaddr;
  564. imageData = (uint8*) segmentInfo.shmaddr;
  565. if (X11Symbols::getInstance()->xShmAttach (display, &segmentInfo) != 0)
  566. usingXShm = true;
  567. else
  568. jassertfalse;
  569. }
  570. else
  571. {
  572. shmctl (segmentInfo.shmid, IPC_RMID, nullptr);
  573. }
  574. }
  575. }
  576. }
  577. }
  578. if (! isUsingXShm())
  579. #endif
  580. {
  581. imageDataAllocated.allocate ((size_t) (lineStride * h), format == Image::ARGB && clearImage);
  582. imageData = imageDataAllocated;
  583. xImage = (XImage*) ::calloc (1, sizeof (XImage));
  584. xImage->width = w;
  585. xImage->height = h;
  586. xImage->xoffset = 0;
  587. xImage->format = ZPixmap;
  588. xImage->data = (char*) imageData;
  589. xImage->byte_order = X11Symbols::getInstance()->xImageByteOrder (display);
  590. xImage->bitmap_unit = X11Symbols::getInstance()->xBitmapUnit (display);
  591. xImage->bitmap_bit_order = X11Symbols::getInstance()->xBitmapBitOrder (display);
  592. xImage->bitmap_pad = 32;
  593. xImage->depth = pixelStride * 8;
  594. xImage->bytes_per_line = lineStride;
  595. xImage->bits_per_pixel = pixelStride * 8;
  596. xImage->red_mask = 0x00FF0000;
  597. xImage->green_mask = 0x0000FF00;
  598. xImage->blue_mask = 0x000000FF;
  599. if (imageDepth == 16)
  600. {
  601. int pixStride = 2;
  602. auto stride = ((w * pixStride + 3) & ~3);
  603. imageData16Bit.malloc (stride * h);
  604. xImage->data = imageData16Bit;
  605. xImage->bitmap_pad = 16;
  606. xImage->depth = pixStride * 8;
  607. xImage->bytes_per_line = stride;
  608. xImage->bits_per_pixel = pixStride * 8;
  609. xImage->red_mask = visual->red_mask;
  610. xImage->green_mask = visual->green_mask;
  611. xImage->blue_mask = visual->blue_mask;
  612. }
  613. if (! X11Symbols::getInstance()->xInitImage (xImage))
  614. jassertfalse;
  615. }
  616. }
  617. ~XBitmapImage() override
  618. {
  619. XWindowSystemUtilities::ScopedXLock xLock;
  620. if (gc != None)
  621. X11Symbols::getInstance()->xFreeGC (display, gc);
  622. #if JUCE_USE_XSHM
  623. if (isUsingXShm())
  624. {
  625. X11Symbols::getInstance()->xShmDetach (display, &segmentInfo);
  626. X11Symbols::getInstance()->xFlush (display);
  627. X11Symbols::getInstance()->xDestroyImage (xImage);
  628. shmdt (segmentInfo.shmaddr);
  629. shmctl (segmentInfo.shmid, IPC_RMID, nullptr);
  630. }
  631. else
  632. #endif
  633. {
  634. xImage->data = nullptr;
  635. X11Symbols::getInstance()->xDestroyImage (xImage);
  636. }
  637. }
  638. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
  639. {
  640. sendDataChangeMessage();
  641. return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (this));
  642. }
  643. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y,
  644. Image::BitmapData::ReadWriteMode mode) override
  645. {
  646. bitmap.data = imageData + x * pixelStride + y * lineStride;
  647. bitmap.pixelFormat = pixelFormat;
  648. bitmap.lineStride = lineStride;
  649. bitmap.pixelStride = pixelStride;
  650. if (mode != Image::BitmapData::readOnly)
  651. sendDataChangeMessage();
  652. }
  653. ImagePixelData::Ptr clone() override
  654. {
  655. jassertfalse;
  656. return nullptr;
  657. }
  658. std::unique_ptr<ImageType> createType() const override { return std::make_unique<NativeImageType>(); }
  659. void blitToWindow (::Window window, int dx, int dy, unsigned int dw, unsigned int dh, int sx, int sy)
  660. {
  661. XWindowSystemUtilities::ScopedXLock xLock;
  662. if (gc == None)
  663. {
  664. XGCValues gcvalues;
  665. gcvalues.foreground = None;
  666. gcvalues.background = None;
  667. gcvalues.function = GXcopy;
  668. gcvalues.plane_mask = AllPlanes;
  669. gcvalues.clip_mask = None;
  670. gcvalues.graphics_exposures = False;
  671. gc = X11Symbols::getInstance()->xCreateGC (display, window,
  672. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  673. &gcvalues);
  674. }
  675. if (imageDepth == 16)
  676. {
  677. auto rMask = (uint32) xImage->red_mask;
  678. auto gMask = (uint32) xImage->green_mask;
  679. auto bMask = (uint32) xImage->blue_mask;
  680. auto rShiftL = (uint32) jmax (0, getShiftNeeded (rMask));
  681. auto rShiftR = (uint32) jmax (0, -getShiftNeeded (rMask));
  682. auto gShiftL = (uint32) jmax (0, getShiftNeeded (gMask));
  683. auto gShiftR = (uint32) jmax (0, -getShiftNeeded (gMask));
  684. auto bShiftL = (uint32) jmax (0, getShiftNeeded (bMask));
  685. auto bShiftR = (uint32) jmax (0, -getShiftNeeded (bMask));
  686. Image::BitmapData srcData (Image (this), Image::BitmapData::readOnly);
  687. for (int y = sy; y < sy + (int) dh; ++y)
  688. {
  689. auto* p = srcData.getPixelPointer (sx, y);
  690. for (int x = sx; x < sx + (int) dw; ++x)
  691. {
  692. auto* pixel = (PixelRGB*) p;
  693. p += srcData.pixelStride;
  694. X11Symbols::getInstance()->xPutPixel (xImage, x, y,
  695. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  696. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  697. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  698. }
  699. }
  700. }
  701. // blit results to screen.
  702. #if JUCE_USE_XSHM
  703. if (isUsingXShm())
  704. {
  705. X11Symbols::getInstance()->xShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  706. ++shmPaintsPendingMap[window];
  707. }
  708. else
  709. #endif
  710. X11Symbols::getInstance()->xPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  711. }
  712. #if JUCE_USE_XSHM
  713. bool isUsingXShm() const noexcept { return usingXShm; }
  714. #endif
  715. private:
  716. //==============================================================================
  717. XImage* xImage = nullptr;
  718. const unsigned int imageDepth;
  719. HeapBlock<uint8> imageDataAllocated;
  720. HeapBlock<char> imageData16Bit;
  721. int pixelStride, lineStride;
  722. uint8* imageData = nullptr;
  723. GC gc = None;
  724. ::Display* display = nullptr;
  725. #if JUCE_USE_XSHM
  726. XShmSegmentInfo segmentInfo;
  727. bool usingXShm;
  728. #endif
  729. static int getShiftNeeded (const uint32 mask) noexcept
  730. {
  731. for (int i = 32; --i >= 0;)
  732. if (((mask >> i) & 1) != 0)
  733. return i - 7;
  734. jassertfalse;
  735. return 0;
  736. }
  737. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage)
  738. };
  739. //=============================== X11 - Displays ===============================
  740. namespace DisplayHelpers
  741. {
  742. static double getDisplayDPI (::Display* display, int index)
  743. {
  744. auto widthMM = X11Symbols::getInstance()->xDisplayWidthMM (display, index);
  745. auto heightMM = X11Symbols::getInstance()->xDisplayHeightMM (display, index);
  746. if (widthMM > 0 && heightMM > 0)
  747. return (((X11Symbols::getInstance()->xDisplayWidth (display, index) * 25.4) / widthMM)
  748. + ((X11Symbols::getInstance()->xDisplayHeight (display, index) * 25.4) / heightMM)) / 2.0;
  749. return 96.0;
  750. }
  751. static double getDisplayScale (const String& name, double dpi)
  752. {
  753. if (name.isNotEmpty())
  754. {
  755. // Ubuntu and derived distributions now save a per-display scale factor as a configuration
  756. // variable. This can be changed in the Monitor system settings panel.
  757. ChildProcess dconf;
  758. if (File ("/usr/bin/dconf").existsAsFile()
  759. && dconf.start ("/usr/bin/dconf read /com/ubuntu/user-interface/scale-factor", ChildProcess::wantStdOut))
  760. {
  761. if (dconf.waitForProcessToFinish (200))
  762. {
  763. auto jsonOutput = dconf.readAllProcessOutput().replaceCharacter ('\'', '"');
  764. if (dconf.getExitCode() == 0 && jsonOutput.isNotEmpty())
  765. {
  766. auto jsonVar = JSON::parse (jsonOutput);
  767. if (auto* object = jsonVar.getDynamicObject())
  768. {
  769. auto scaleFactorVar = object->getProperty (name);
  770. if (! scaleFactorVar.isVoid())
  771. {
  772. auto scaleFactor = ((double) scaleFactorVar) / 8.0;
  773. if (scaleFactor > 0.0)
  774. return scaleFactor;
  775. }
  776. }
  777. }
  778. }
  779. }
  780. }
  781. {
  782. // Other gnome based distros now use gsettings for a global scale factor
  783. ChildProcess gsettings;
  784. if (File ("/usr/bin/gsettings").existsAsFile()
  785. && gsettings.start ("/usr/bin/gsettings get org.gnome.desktop.interface scaling-factor", ChildProcess::wantStdOut))
  786. {
  787. if (gsettings.waitForProcessToFinish (200))
  788. {
  789. auto gsettingsOutput = StringArray::fromTokens (gsettings.readAllProcessOutput(), true);
  790. if (gsettingsOutput.size() >= 2 && gsettingsOutput[1].length() > 0)
  791. {
  792. auto scaleFactor = gsettingsOutput[1].getDoubleValue();
  793. if (scaleFactor > 0.0)
  794. return scaleFactor;
  795. return 1.0;
  796. }
  797. }
  798. }
  799. }
  800. // If no scale factor is set by GNOME or Ubuntu then calculate from monitor dpi
  801. // We use the same approach as chromium which simply divides the dpi by 96
  802. // and then rounds the result
  803. return round (dpi / 96.0);
  804. }
  805. #if JUCE_USE_XINERAMA
  806. static Array<XineramaScreenInfo> xineramaQueryDisplays (::Display* display)
  807. {
  808. int major_opcode, first_event, first_error;
  809. if (X11Symbols::getInstance()->xQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  810. && (X11Symbols::getInstance()->xineramaIsActive (display) != 0))
  811. {
  812. int numScreens;
  813. if (auto* xinfo = X11Symbols::getInstance()->xineramaQueryScreens (display, &numScreens))
  814. {
  815. Array<XineramaScreenInfo> infos (xinfo, numScreens);
  816. X11Symbols::getInstance()->xFree (xinfo);
  817. return infos;
  818. }
  819. }
  820. return {};
  821. }
  822. #endif
  823. }
  824. //=============================== X11 - Pixmap =================================
  825. namespace PixmapHelpers
  826. {
  827. static Pixmap createColourPixmapFromImage (::Display* display, const Image& image)
  828. {
  829. XWindowSystemUtilities::ScopedXLock xLock;
  830. auto width = (unsigned int) image.getWidth();
  831. auto height = (unsigned int) image.getHeight();
  832. HeapBlock<uint32> colour (width * height);
  833. int index = 0;
  834. for (int y = 0; y < (int) height; ++y)
  835. for (int x = 0; x < (int) width; ++x)
  836. colour[index++] = image.getPixelAt (x, y).getARGB();
  837. auto* ximage = X11Symbols::getInstance()->xCreateImage (display, (Visual*) CopyFromParent, 24, ZPixmap,
  838. 0, reinterpret_cast<const char*> (colour.getData()),
  839. width, height, 32, 0);
  840. auto pixmap = X11Symbols::getInstance()->xCreatePixmap (display,
  841. X11Symbols::getInstance()->xDefaultRootWindow (display),
  842. width, height, 24);
  843. auto gc = X11Symbols::getInstance()->xCreateGC (display, pixmap, 0, nullptr);
  844. X11Symbols::getInstance()->xPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  845. X11Symbols::getInstance()->xFreeGC (display, gc);
  846. X11Symbols::getInstance()->xFree (ximage);
  847. return pixmap;
  848. }
  849. static Pixmap createMaskPixmapFromImage (::Display* display, const Image& image)
  850. {
  851. XWindowSystemUtilities::ScopedXLock xLock;
  852. auto width = (unsigned int) image.getWidth();
  853. auto height = (unsigned int) image.getHeight();
  854. auto stride = (width + 7) >> 3;
  855. HeapBlock<char> mask;
  856. mask.calloc (stride * height);
  857. auto msbfirst = (X11Symbols::getInstance()->xBitmapBitOrder (display) == MSBFirst);
  858. for (unsigned int y = 0; y < height; ++y)
  859. {
  860. for (unsigned int x = 0; x < width; ++x)
  861. {
  862. auto bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  863. auto offset = y * stride + (x >> 3);
  864. if (image.getPixelAt ((int) x, (int) y).getAlpha() >= 128)
  865. mask[offset] |= bit;
  866. }
  867. }
  868. return X11Symbols::getInstance()->xCreatePixmapFromBitmapData (display, X11Symbols::getInstance()->xDefaultRootWindow (display),
  869. mask.getData(), width, height, 1, 0, 1);
  870. }
  871. }
  872. //=============================== X11 - Clipboard ==============================
  873. namespace ClipboardHelpers
  874. {
  875. //==============================================================================
  876. // Read the content of a window property as either a locale-dependent string or an utf8 string
  877. // works only for strings shorter than 1000000 bytes
  878. static String readWindowProperty (::Display* display, Window window, Atom atom)
  879. {
  880. if (display != nullptr)
  881. {
  882. XWindowSystemUtilities::GetXProperty prop (window, atom, 0L, 100000, false, AnyPropertyType);
  883. if (prop.success)
  884. {
  885. if (prop.actualType == XWindowSystem::getInstance()->getAtoms().utf8String&& prop.actualFormat == 8)
  886. return String::fromUTF8 ((const char*) prop.data, (int) prop.numItems);
  887. if (prop.actualType == XA_STRING && prop.actualFormat == 8)
  888. return String ((const char*) prop.data, prop.numItems);
  889. }
  890. }
  891. return {};
  892. }
  893. //==============================================================================
  894. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  895. static bool requestSelectionContent (::Display* display, String& selectionContent, Atom selection, Atom requestedFormat)
  896. {
  897. auto property_name = X11Symbols::getInstance()->xInternAtom (display, "JUCE_SEL", false);
  898. // The selection owner will be asked to set the JUCE_SEL property on the
  899. // juce_messageWindowHandle with the selection content
  900. X11Symbols::getInstance()->xConvertSelection (display, selection, requestedFormat, property_name,
  901. juce_messageWindowHandle, CurrentTime);
  902. int count = 50; // will wait at most for 200 ms
  903. while (--count >= 0)
  904. {
  905. XEvent event;
  906. if (X11Symbols::getInstance()->xCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  907. {
  908. if (event.xselection.property == property_name)
  909. {
  910. jassert (event.xselection.requestor == juce_messageWindowHandle);
  911. selectionContent = readWindowProperty (display, event.xselection.requestor, event.xselection.property);
  912. return true;
  913. }
  914. return false; // the format we asked for was denied.. (event.xselection.property == None)
  915. }
  916. // not very elegant.. we could do a select() or something like that...
  917. // however clipboard content requesting is inherently slow on x11, it
  918. // often takes 50ms or more so...
  919. Thread::sleep (4);
  920. }
  921. return false;
  922. }
  923. //==============================================================================
  924. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  925. static void handleSelection (XSelectionRequestEvent& evt)
  926. {
  927. // the selection content is sent to the target window as a window property
  928. XSelectionEvent reply;
  929. reply.type = SelectionNotify;
  930. reply.display = evt.display;
  931. reply.requestor = evt.requestor;
  932. reply.selection = evt.selection;
  933. reply.target = evt.target;
  934. reply.property = None; // == "fail"
  935. reply.time = evt.time;
  936. HeapBlock<char> data;
  937. int propertyFormat = 0;
  938. size_t numDataItems = 0;
  939. if (evt.selection == XA_PRIMARY || evt.selection == XWindowSystem::getInstance()->getAtoms().clipboard)
  940. {
  941. if (evt.target == XA_STRING || evt.target == XWindowSystem::getInstance()->getAtoms().utf8String)
  942. {
  943. auto localContent = XWindowSystem::getInstance()->getLocalClipboardContent();
  944. // translate to utf8
  945. numDataItems = localContent.getNumBytesAsUTF8() + 1;
  946. data.calloc (numDataItems + 1);
  947. localContent.copyToUTF8 (data, numDataItems);
  948. propertyFormat = 8; // bits/item
  949. }
  950. else if (evt.target == XWindowSystem::getInstance()->getAtoms().targets)
  951. {
  952. // another application wants to know what we are able to send
  953. numDataItems = 2;
  954. propertyFormat = 32; // atoms are 32-bit
  955. data.calloc (numDataItems * 4);
  956. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  957. atoms[0] = XWindowSystem::getInstance()->getAtoms().utf8String;
  958. atoms[1] = XA_STRING;
  959. evt.target = XA_ATOM;
  960. }
  961. }
  962. else
  963. {
  964. DBG ("requested unsupported clipboard");
  965. }
  966. if (data != nullptr)
  967. {
  968. const size_t maxReasonableSelectionSize = 1000000;
  969. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  970. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  971. {
  972. X11Symbols::getInstance()->xChangeProperty (evt.display, evt.requestor,
  973. evt.property, evt.target,
  974. propertyFormat /* 8 or 32 */, PropModeReplace,
  975. reinterpret_cast<const unsigned char*> (data.getData()), (int) numDataItems);
  976. reply.property = evt.property; // " == success"
  977. }
  978. }
  979. X11Symbols::getInstance()->xSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  980. }
  981. }
  982. //==============================================================================
  983. typedef void (*SelectionRequestCallback) (XSelectionRequestEvent&);
  984. extern SelectionRequestCallback handleSelectionRequest;
  985. struct ClipboardCallbackInitialiser
  986. {
  987. ClipboardCallbackInitialiser()
  988. {
  989. handleSelectionRequest = ClipboardHelpers::handleSelection;
  990. }
  991. };
  992. static ClipboardCallbackInitialiser clipboardInitialiser;
  993. //==============================================================================
  994. ComponentPeer* getPeerFor (::Window windowH)
  995. {
  996. if (windowH == 0)
  997. return nullptr;
  998. XPointer peer = nullptr;
  999. if (auto* display = XWindowSystem::getInstance()->getDisplay())
  1000. {
  1001. XWindowSystemUtilities::ScopedXLock xLock;
  1002. X11Symbols::getInstance()->xFindContext (display, (XID) windowH, windowHandleXContext, &peer);
  1003. }
  1004. return reinterpret_cast<ComponentPeer*> (peer);
  1005. }
  1006. //==============================================================================
  1007. static std::unordered_map<LinuxComponentPeer<::Window>*, X11DragState> dragAndDropStateMap;
  1008. XWindowSystem::XWindowSystem()
  1009. {
  1010. xIsAvailable = X11Symbols::getInstance()->areXFunctionsAvailable();
  1011. if (! xIsAvailable)
  1012. {
  1013. X11Symbols::deleteInstance();
  1014. return;
  1015. }
  1016. if (JUCEApplicationBase::isStandaloneApp())
  1017. {
  1018. // Initialise xlib for multiple thread support
  1019. static bool initThreadCalled = false;
  1020. if (! initThreadCalled)
  1021. {
  1022. if (! X11Symbols::getInstance()->xInitThreads())
  1023. {
  1024. // This is fatal! Print error and closedown
  1025. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  1026. Process::terminate();
  1027. return;
  1028. }
  1029. initThreadCalled = true;
  1030. }
  1031. X11ErrorHandling::installXErrorHandlers();
  1032. }
  1033. initialiseXDisplay();
  1034. }
  1035. XWindowSystem::~XWindowSystem()
  1036. {
  1037. if (xIsAvailable)
  1038. {
  1039. destroyXDisplay();
  1040. if (JUCEApplicationBase::isStandaloneApp())
  1041. X11ErrorHandling::removeXErrorHandlers();
  1042. X11Symbols::deleteInstance();
  1043. }
  1044. clearSingletonInstance();
  1045. }
  1046. //==============================================================================
  1047. static int getAllEventsMask (bool ignoresMouseClicks)
  1048. {
  1049. return NoEventMask | KeyPressMask | KeyReleaseMask
  1050. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  1051. | ExposureMask | StructureNotifyMask | FocusChangeMask
  1052. | (ignoresMouseClicks ? 0 : (ButtonPressMask | ButtonReleaseMask));
  1053. }
  1054. ::Window XWindowSystem::createWindow (::Window parentToAddTo, LinuxComponentPeer<::Window>* peer) const
  1055. {
  1056. auto styleFlags = peer->getStyleFlags();
  1057. // can't open a window on a system that doesn't have X11 installed!
  1058. jassert (X11Symbols::getInstance()->areXFunctionsAvailable());
  1059. XWindowSystemUtilities::ScopedXLock xLock;
  1060. // Set up the window attributes
  1061. XSetWindowAttributes swa;
  1062. swa.border_pixel = 0;
  1063. swa.background_pixmap = None;
  1064. swa.colormap = colormap;
  1065. swa.override_redirect = ((styleFlags & ComponentPeer::windowIsTemporary) != 0) ? True : False;
  1066. swa.event_mask = getAllEventsMask (styleFlags & ComponentPeer::windowIgnoresMouseClicks);
  1067. auto root = X11Symbols::getInstance()->xRootWindow (display, X11Symbols::getInstance()->xDefaultScreen (display));
  1068. auto windowH = X11Symbols::getInstance()->xCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  1069. 0, 0, 1, 1,
  1070. 0, depth, InputOutput, visual,
  1071. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  1072. &swa);
  1073. // Set the window context to identify the window handle object
  1074. if (X11Symbols::getInstance()->xSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) peer))
  1075. {
  1076. // Failed
  1077. jassertfalse;
  1078. Logger::outputDebugString ("Failed to create context information for window.\n");
  1079. X11Symbols::getInstance()->xDestroyWindow (display, windowH);
  1080. return 0;
  1081. }
  1082. // Set window manager hints
  1083. auto* wmHints = X11Symbols::getInstance()->xAllocWMHints();
  1084. wmHints->flags = InputHint | StateHint;
  1085. wmHints->input = True;
  1086. wmHints->initial_state = NormalState;
  1087. X11Symbols::getInstance()->xSetWMHints (display, windowH, wmHints);
  1088. X11Symbols::getInstance()->xFree (wmHints);
  1089. // Set the window type
  1090. setWindowType (windowH, styleFlags);
  1091. // Define decoration
  1092. if ((styleFlags & ComponentPeer::windowHasTitleBar) == 0)
  1093. removeWindowDecorations (windowH);
  1094. else
  1095. addWindowButtons (windowH, styleFlags);
  1096. // Associate the PID, allowing to be shut down when something goes wrong
  1097. auto pid = (unsigned long) getpid();
  1098. xchangeProperty (windowH, atoms->pid, XA_CARDINAL, 32, &pid, 1);
  1099. // Set window manager protocols
  1100. xchangeProperty (windowH, atoms->protocols, XA_ATOM, 32, atoms->protocolList, 2);
  1101. // Set drag and drop flags
  1102. xchangeProperty (windowH, atoms->XdndTypeList, XA_ATOM, 32, atoms->allowedMimeTypes, numElementsInArray (atoms->allowedMimeTypes));
  1103. xchangeProperty (windowH, atoms->XdndActionList, XA_ATOM, 32, atoms->allowedActions, numElementsInArray (atoms->allowedActions));
  1104. xchangeProperty (windowH, atoms->XdndActionDescription, XA_STRING, 8, "", 0);
  1105. auto dndVersion = XWindowSystemUtilities::Atoms::DndVersion;
  1106. xchangeProperty (windowH, atoms->XdndAware, XA_ATOM, 32, &dndVersion, 1);
  1107. unsigned long info[2] = { 0, 1 };
  1108. xchangeProperty (windowH, atoms->XembedInfo, atoms->XembedInfo, 32, (unsigned char*) info, 2);
  1109. return windowH;
  1110. }
  1111. void XWindowSystem::destroyWindow (::Window windowH)
  1112. {
  1113. auto* peer = dynamic_cast<LinuxComponentPeer<::Window>*> (getPeerFor (windowH));
  1114. jassert (peer != nullptr);
  1115. #if JUCE_X11_SUPPORTS_XEMBED
  1116. juce_handleXEmbedEvent (peer, nullptr);
  1117. #endif
  1118. deleteIconPixmaps (windowH);
  1119. dragAndDropStateMap.erase (peer);
  1120. XWindowSystemUtilities::ScopedXLock xLock;
  1121. XPointer handlePointer;
  1122. if (! X11Symbols::getInstance()->xFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  1123. X11Symbols::getInstance()->xDeleteContext (display, (XID) windowH, windowHandleXContext);
  1124. X11Symbols::getInstance()->xDestroyWindow (display, windowH);
  1125. // Wait for it to complete and then remove any events for this
  1126. // window from the event queue.
  1127. X11Symbols::getInstance()->xSync (display, false);
  1128. XEvent event;
  1129. while (X11Symbols::getInstance()->xCheckWindowEvent (display, windowH,
  1130. getAllEventsMask (peer->getStyleFlags() & ComponentPeer::windowIgnoresMouseClicks),
  1131. &event) == True)
  1132. {}
  1133. shmPaintsPendingMap.erase (windowH);
  1134. }
  1135. //==============================================================================
  1136. void XWindowSystem::setTitle (::Window windowH, const String& title) const
  1137. {
  1138. jassert (windowH != 0);
  1139. XTextProperty nameProperty;
  1140. char* strings[] = { const_cast<char*> (title.toRawUTF8()) };
  1141. XWindowSystemUtilities::ScopedXLock xLock;
  1142. if (X11Symbols::getInstance()->xStringListToTextProperty (strings, 1, &nameProperty))
  1143. {
  1144. X11Symbols::getInstance()->xSetWMName (display, windowH, &nameProperty);
  1145. X11Symbols::getInstance()->xSetWMIconName (display, windowH, &nameProperty);
  1146. X11Symbols::getInstance()->xFree (nameProperty.value);
  1147. }
  1148. }
  1149. void XWindowSystem::setIcon (::Window windowH, const Image& newIcon) const
  1150. {
  1151. jassert (windowH != 0);
  1152. auto dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  1153. HeapBlock<unsigned long> data (dataSize);
  1154. int index = 0;
  1155. data[index++] = (unsigned long) newIcon.getWidth();
  1156. data[index++] = (unsigned long) newIcon.getHeight();
  1157. for (int y = 0; y < newIcon.getHeight(); ++y)
  1158. for (int x = 0; x < newIcon.getWidth(); ++x)
  1159. data[index++] = (unsigned long) newIcon.getPixelAt (x, y).getARGB();
  1160. XWindowSystemUtilities::ScopedXLock xLock;
  1161. xchangeProperty (windowH, XWindowSystemUtilities::Atoms::getCreating (display, "_NET_WM_ICON"),
  1162. XA_CARDINAL, 32, data.getData(), dataSize);
  1163. deleteIconPixmaps (windowH);
  1164. auto* wmHints = X11Symbols::getInstance()->xGetWMHints (display, windowH);
  1165. if (wmHints == nullptr)
  1166. wmHints = X11Symbols::getInstance()->xAllocWMHints();
  1167. wmHints->flags |= IconPixmapHint | IconMaskHint;
  1168. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  1169. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  1170. X11Symbols::getInstance()->xSetWMHints (display, windowH, wmHints);
  1171. X11Symbols::getInstance()->xFree (wmHints);
  1172. X11Symbols::getInstance()->xSync (display, False);
  1173. }
  1174. void XWindowSystem::setVisible (::Window windowH, bool shouldBeVisible) const
  1175. {
  1176. jassert (windowH != 0);
  1177. XWindowSystemUtilities::ScopedXLock xLock;
  1178. if (shouldBeVisible)
  1179. X11Symbols::getInstance()->xMapWindow (display, windowH);
  1180. else
  1181. X11Symbols::getInstance()->xUnmapWindow (display, windowH);
  1182. }
  1183. void XWindowSystem::setBounds (::Window windowH, Rectangle<int> newBounds, bool isFullScreen) const
  1184. {
  1185. jassert (windowH != 0);
  1186. if (auto* peer = getPeerFor (windowH))
  1187. {
  1188. if (peer->isFullScreen() && ! isFullScreen)
  1189. {
  1190. // When transitioning back from fullscreen, we might need to remove
  1191. // the FULLSCREEN window property
  1192. Atom fs = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_STATE_FULLSCREEN");
  1193. if (fs != None)
  1194. {
  1195. auto root = X11Symbols::getInstance()->xRootWindow (display, X11Symbols::getInstance()->xDefaultScreen (display));
  1196. XClientMessageEvent clientMsg;
  1197. clientMsg.display = display;
  1198. clientMsg.window = windowH;
  1199. clientMsg.type = ClientMessage;
  1200. clientMsg.format = 32;
  1201. clientMsg.message_type = atoms->windowState;
  1202. clientMsg.data.l[0] = 0; // Remove
  1203. clientMsg.data.l[1] = (long) fs;
  1204. clientMsg.data.l[2] = 0;
  1205. clientMsg.data.l[3] = 1; // Normal Source
  1206. XWindowSystemUtilities::ScopedXLock xLock;
  1207. X11Symbols::getInstance()->xSendEvent (display, root, false,
  1208. SubstructureRedirectMask | SubstructureNotifyMask,
  1209. (XEvent*) &clientMsg);
  1210. }
  1211. }
  1212. XWindowSystemUtilities::ScopedXLock xLock;
  1213. auto* hints = X11Symbols::getInstance()->xAllocSizeHints();
  1214. hints->flags = USSize | USPosition;
  1215. hints->x = newBounds.getX();
  1216. hints->y = newBounds.getY();
  1217. hints->width = newBounds.getWidth();
  1218. hints->height = newBounds.getHeight();
  1219. if ((peer->getStyleFlags() & ComponentPeer::windowIsResizable) == 0)
  1220. {
  1221. hints->min_width = hints->max_width = hints->width;
  1222. hints->min_height = hints->max_height = hints->height;
  1223. hints->flags |= PMinSize | PMaxSize;
  1224. }
  1225. X11Symbols::getInstance()->xSetWMNormalHints (display, windowH, hints);
  1226. X11Symbols::getInstance()->xFree (hints);
  1227. auto windowBorder = peer->getFrameSize();
  1228. X11Symbols::getInstance()->xMoveResizeWindow (display, windowH,
  1229. newBounds.getX() - windowBorder.getLeft(),
  1230. newBounds.getY() - windowBorder.getTop(),
  1231. (unsigned int) newBounds.getWidth(),
  1232. (unsigned int) newBounds.getHeight());
  1233. }
  1234. }
  1235. bool XWindowSystem::contains (::Window windowH, Point<int> localPos) const
  1236. {
  1237. ::Window root, child;
  1238. int wx, wy;
  1239. unsigned int ww, wh, bw, bitDepth;
  1240. XWindowSystemUtilities::ScopedXLock xLock;
  1241. return X11Symbols::getInstance()->xGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth)
  1242. && X11Symbols::getInstance()->xTranslateCoordinates (display, windowH, windowH, localPos.getX(), localPos.getY(), &wx, &wy, &child)
  1243. && child == None;
  1244. }
  1245. BorderSize<int> XWindowSystem::getBorderSize (::Window windowH) const
  1246. {
  1247. jassert (windowH != 0);
  1248. XWindowSystemUtilities::ScopedXLock xLock;
  1249. auto hints = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_FRAME_EXTENTS");
  1250. if (hints != None)
  1251. {
  1252. XWindowSystemUtilities::GetXProperty prop (windowH, hints, 0, 4, false, XA_CARDINAL);
  1253. if (prop.success && prop.actualFormat == 32)
  1254. {
  1255. auto data = prop.data;
  1256. std::array<unsigned long, 4> sizes;
  1257. for (auto& size : sizes)
  1258. {
  1259. memcpy (&size, data, sizeof (unsigned long));
  1260. data += sizeof (unsigned long);
  1261. }
  1262. return { (int) sizes[2], (int) sizes[0], (int) sizes[3], (int) sizes[1] };
  1263. }
  1264. }
  1265. return {};
  1266. }
  1267. Rectangle<int> XWindowSystem::getWindowBounds (::Window windowH, ::Window parentWindow)
  1268. {
  1269. jassert (windowH != 0);
  1270. Window root, child;
  1271. int wx = 0, wy = 0;
  1272. unsigned int ww = 0, wh = 0, bw, bitDepth;
  1273. XWindowSystemUtilities::ScopedXLock xLock;
  1274. if (X11Symbols::getInstance()->xGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth))
  1275. {
  1276. int rootX = 0, rootY = 0;
  1277. if (! X11Symbols::getInstance()->xTranslateCoordinates (display, windowH, root, 0, 0, &rootX, &rootY, &child))
  1278. rootX = rootY = 0;
  1279. if (parentWindow == 0)
  1280. {
  1281. wx = rootX;
  1282. wy = rootY;
  1283. }
  1284. else
  1285. {
  1286. parentScreenPosition = Desktop::getInstance().getDisplays().physicalToLogical (Point<int> (rootX, rootY));
  1287. }
  1288. }
  1289. return { wx, wy, (int) ww, (int) wh };
  1290. }
  1291. Point<int> XWindowSystem::getParentScreenPosition() const
  1292. {
  1293. return parentScreenPosition;
  1294. }
  1295. void XWindowSystem::setMinimised (::Window windowH, bool shouldBeMinimised) const
  1296. {
  1297. jassert (windowH != 0);
  1298. if (shouldBeMinimised)
  1299. {
  1300. auto root = X11Symbols::getInstance()->xRootWindow (display, X11Symbols::getInstance()->xDefaultScreen (display));
  1301. XClientMessageEvent clientMsg;
  1302. clientMsg.display = display;
  1303. clientMsg.window = windowH;
  1304. clientMsg.type = ClientMessage;
  1305. clientMsg.format = 32;
  1306. clientMsg.message_type = atoms->changeState;
  1307. clientMsg.data.l[0] = IconicState;
  1308. XWindowSystemUtilities::ScopedXLock xLock;
  1309. X11Symbols::getInstance()->xSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  1310. }
  1311. }
  1312. bool XWindowSystem::isMinimised (::Window windowH) const
  1313. {
  1314. jassert (windowH != 0);
  1315. XWindowSystemUtilities::ScopedXLock xLock;
  1316. XWindowSystemUtilities::GetXProperty prop (windowH, atoms->state, 0, 64, false, atoms->state);
  1317. if (prop.success && prop.actualType == atoms->state
  1318. && prop.actualFormat == 32 && prop.numItems > 0)
  1319. {
  1320. unsigned long state;
  1321. memcpy (&state, prop.data, sizeof (unsigned long));
  1322. return state == IconicState;
  1323. }
  1324. return false;
  1325. }
  1326. void XWindowSystem::toFront (::Window windowH, bool) const
  1327. {
  1328. jassert (windowH != 0);
  1329. XWindowSystemUtilities::ScopedXLock xLock;
  1330. XEvent ev;
  1331. ev.xclient.type = ClientMessage;
  1332. ev.xclient.serial = 0;
  1333. ev.xclient.send_event = True;
  1334. ev.xclient.message_type = atoms->activeWin;
  1335. ev.xclient.window = windowH;
  1336. ev.xclient.format = 32;
  1337. ev.xclient.data.l[0] = 2;
  1338. ev.xclient.data.l[1] = getUserTime (windowH);
  1339. ev.xclient.data.l[2] = 0;
  1340. ev.xclient.data.l[3] = 0;
  1341. ev.xclient.data.l[4] = 0;
  1342. X11Symbols::getInstance()->xSendEvent (display, X11Symbols::getInstance()->xRootWindow (display, X11Symbols::getInstance()->xDefaultScreen (display)),
  1343. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  1344. X11Symbols::getInstance()->xSync (display, False);
  1345. }
  1346. void XWindowSystem::toBehind (::Window windowH, ::Window otherWindow) const
  1347. {
  1348. jassert (windowH != 0 && otherWindow != 0);
  1349. Window newStack[] = { otherWindow, windowH };
  1350. XWindowSystemUtilities::ScopedXLock xLock;
  1351. X11Symbols::getInstance()->xRestackWindows (display, newStack, 2);
  1352. }
  1353. bool XWindowSystem::isFocused (::Window windowH) const
  1354. {
  1355. jassert (windowH != 0);
  1356. int revert = 0;
  1357. Window focusedWindow = 0;
  1358. XWindowSystemUtilities::ScopedXLock xLock;
  1359. X11Symbols::getInstance()->xGetInputFocus (display, &focusedWindow, &revert);
  1360. if (focusedWindow == PointerRoot)
  1361. return false;
  1362. return isParentWindowOf (windowH, focusedWindow);
  1363. }
  1364. ::Window XWindowSystem::getFocusWindow (::Window windowH) const
  1365. {
  1366. jassert (windowH != 0);
  1367. #if JUCE_X11_SUPPORTS_XEMBED
  1368. if (auto w = (::Window) juce_getCurrentFocusWindow (dynamic_cast<LinuxComponentPeer<::Window>*> (getPeerFor (windowH))))
  1369. return w;
  1370. #endif
  1371. return windowH;
  1372. }
  1373. bool XWindowSystem::grabFocus (::Window windowH) const
  1374. {
  1375. jassert (windowH != 0);
  1376. XWindowAttributes atts;
  1377. XWindowSystemUtilities::ScopedXLock xLock;
  1378. if (windowH != 0
  1379. && X11Symbols::getInstance()->xGetWindowAttributes (display, windowH, &atts)
  1380. && atts.map_state == IsViewable
  1381. && ! isFocused (windowH))
  1382. {
  1383. X11Symbols::getInstance()->xSetInputFocus (display, getFocusWindow (windowH), RevertToParent, (::Time) getUserTime (windowH));
  1384. return true;
  1385. }
  1386. return false;
  1387. }
  1388. bool XWindowSystem::canUseSemiTransparentWindows() const
  1389. {
  1390. #if JUCE_USE_XRENDER
  1391. if (XRender::hasCompositingWindowManager (display))
  1392. {
  1393. int matchedDepth = 0, desiredDepth = 32;
  1394. return Visuals::findVisualFormat (display, desiredDepth, matchedDepth) != nullptr
  1395. && matchedDepth == desiredDepth;
  1396. }
  1397. #endif
  1398. return false;
  1399. }
  1400. bool XWindowSystem::canUseARGBImages() const
  1401. {
  1402. static bool canUseARGB = false;
  1403. #if JUCE_USE_XSHM
  1404. static bool checked = false;
  1405. if (! checked)
  1406. {
  1407. if (XSHMHelpers::isShmAvailable (display))
  1408. {
  1409. XWindowSystemUtilities::ScopedXLock xLock;
  1410. XShmSegmentInfo segmentinfo;
  1411. auto testImage = X11Symbols::getInstance()->xShmCreateImage (display,
  1412. X11Symbols::getInstance()->xDefaultVisual (display, X11Symbols::getInstance()->xDefaultScreen (display)),
  1413. 24, ZPixmap, nullptr, &segmentinfo, 64, 64);
  1414. canUseARGB = (testImage->bits_per_pixel == 32);
  1415. X11Symbols::getInstance()->xDestroyImage (testImage);
  1416. }
  1417. else
  1418. {
  1419. canUseARGB = false;
  1420. }
  1421. checked = true;
  1422. }
  1423. #endif
  1424. return canUseARGB;
  1425. }
  1426. Image XWindowSystem::createImage (int width, int height, bool argb) const
  1427. {
  1428. #if JUCE_USE_XSHM
  1429. return Image (new XBitmapImage (display, argb ? Image::ARGB : Image::RGB,
  1430. #else
  1431. return Image (new XBitmapImage (display, Image::RGB,
  1432. #endif
  1433. (width + 31) & ~31,
  1434. (height + 31) & ~31,
  1435. false, (unsigned int) depth, visual));
  1436. }
  1437. void XWindowSystem::blitToWindow (::Window windowH, Image image, Rectangle<int> destinationRect, Rectangle<int> totalRect) const
  1438. {
  1439. jassert (windowH != 0);
  1440. auto* xbitmap = static_cast<XBitmapImage*> (image.getPixelData());
  1441. xbitmap->blitToWindow (windowH,
  1442. destinationRect.getX(), destinationRect.getY(),
  1443. (unsigned int) destinationRect.getWidth(),
  1444. (unsigned int) destinationRect.getHeight(),
  1445. destinationRect.getX() - totalRect.getX(), destinationRect.getY() - totalRect.getY());
  1446. }
  1447. int XWindowSystem::getNumPaintsPending (::Window windowH) const
  1448. {
  1449. #if JUCE_USE_XSHM
  1450. if (shmPaintsPendingMap[windowH] != 0)
  1451. {
  1452. XWindowSystemUtilities::ScopedXLock xLock;
  1453. XEvent evt;
  1454. while (X11Symbols::getInstance()->xCheckTypedWindowEvent (display, windowH, shmCompletionEvent, &evt))
  1455. --shmPaintsPendingMap[windowH];
  1456. }
  1457. #endif
  1458. return shmPaintsPendingMap[windowH];
  1459. }
  1460. void XWindowSystem::setScreenSaverEnabled (bool enabled) const
  1461. {
  1462. using tXScreenSaverSuspend = void (*) (Display*, Bool);
  1463. static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
  1464. if (xScreenSaverSuspend == nullptr)
  1465. if (void* h = dlopen ("libXss.so.1", RTLD_GLOBAL | RTLD_NOW))
  1466. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  1467. XWindowSystemUtilities::ScopedXLock xLock;
  1468. if (xScreenSaverSuspend != nullptr)
  1469. xScreenSaverSuspend (display, ! enabled);
  1470. }
  1471. Point<float> XWindowSystem::getCurrentMousePosition() const
  1472. {
  1473. Window root, child;
  1474. int x, y, winx, winy;
  1475. unsigned int mask;
  1476. XWindowSystemUtilities::ScopedXLock xLock;
  1477. if (X11Symbols::getInstance()->xQueryPointer (display,
  1478. X11Symbols::getInstance()->xRootWindow (display,
  1479. X11Symbols::getInstance()->xDefaultScreen (display)),
  1480. &root, &child,
  1481. &x, &y, &winx, &winy, &mask) == False)
  1482. {
  1483. x = y = -1;
  1484. }
  1485. return { (float) x, (float) y };
  1486. }
  1487. void XWindowSystem::setMousePosition (Point<float> pos) const
  1488. {
  1489. XWindowSystemUtilities::ScopedXLock xLock;
  1490. auto root = X11Symbols::getInstance()->xRootWindow (display,
  1491. X11Symbols::getInstance()->xDefaultScreen (display));
  1492. X11Symbols::getInstance()->xWarpPointer (display, None, root, 0, 0, 0, 0,
  1493. roundToInt (pos.getX()), roundToInt (pos.getY()));
  1494. }
  1495. void* XWindowSystem::createCustomMouseCursorInfo (const Image& image, Point<int> hotspot) const
  1496. {
  1497. if (display == nullptr)
  1498. return nullptr;
  1499. XWindowSystemUtilities::ScopedXLock xLock;
  1500. auto imageW = (unsigned int) image.getWidth();
  1501. auto imageH = (unsigned int) image.getHeight();
  1502. auto hotspotX = hotspot.x;
  1503. auto hotspotY = hotspot.y;
  1504. #if JUCE_USE_XCURSOR
  1505. if (auto* xcImage = X11Symbols::getInstance()->xcursorImageCreate ((int) imageW, (int) imageH))
  1506. {
  1507. xcImage->xhot = (XcursorDim) hotspotX;
  1508. xcImage->yhot = (XcursorDim) hotspotY;
  1509. auto* dest = xcImage->pixels;
  1510. for (int y = 0; y < (int) imageH; ++y)
  1511. for (int x = 0; x < (int) imageW; ++x)
  1512. *dest++ = image.getPixelAt (x, y).getARGB();
  1513. auto* result = (void*) X11Symbols::getInstance()->xcursorImageLoadCursor (display, xcImage);
  1514. X11Symbols::getInstance()->xcursorImageDestroy (xcImage);
  1515. if (result != nullptr)
  1516. return result;
  1517. }
  1518. #endif
  1519. auto root = X11Symbols::getInstance()->xRootWindow (display,
  1520. X11Symbols::getInstance()->xDefaultScreen (display));
  1521. unsigned int cursorW, cursorH;
  1522. if (! X11Symbols::getInstance()->xQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  1523. return nullptr;
  1524. Image im (Image::ARGB, (int) cursorW, (int) cursorH, true);
  1525. {
  1526. Graphics g (im);
  1527. if (imageW > cursorW || imageH > cursorH)
  1528. {
  1529. hotspotX = (hotspotX * (int) cursorW) / (int) imageW;
  1530. hotspotY = (hotspotY * (int) cursorH) / (int) imageH;
  1531. g.drawImage (image, Rectangle<float> ((float) imageW, (float) imageH),
  1532. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize);
  1533. }
  1534. else
  1535. {
  1536. g.drawImageAt (image, 0, 0);
  1537. }
  1538. }
  1539. auto stride = (cursorW + 7) >> 3;
  1540. HeapBlock<char> maskPlane, sourcePlane;
  1541. maskPlane.calloc (stride * cursorH);
  1542. sourcePlane.calloc (stride * cursorH);
  1543. auto msbfirst = (X11Symbols::getInstance()->xBitmapBitOrder (display) == MSBFirst);
  1544. for (auto y = (int) cursorH; --y >= 0;)
  1545. {
  1546. for (auto x = (int) cursorW; --x >= 0;)
  1547. {
  1548. auto mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  1549. auto offset = (unsigned int) y * stride + ((unsigned int) x >> 3);
  1550. auto c = im.getPixelAt (x, y);
  1551. if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
  1552. if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
  1553. }
  1554. }
  1555. auto sourcePixmap = X11Symbols::getInstance()->xCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  1556. auto maskPixmap = X11Symbols::getInstance()->xCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  1557. XColor white, black;
  1558. black.red = black.green = black.blue = 0;
  1559. white.red = white.green = white.blue = 0xffff;
  1560. auto* result = (void*) X11Symbols::getInstance()->xCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black,
  1561. (unsigned int) hotspotX, (unsigned int) hotspotY);
  1562. X11Symbols::getInstance()->xFreePixmap (display, sourcePixmap);
  1563. X11Symbols::getInstance()->xFreePixmap (display, maskPixmap);
  1564. return result;
  1565. }
  1566. void XWindowSystem::deleteMouseCursor (void* cursorHandle) const
  1567. {
  1568. if (cursorHandle != nullptr && display != nullptr)
  1569. {
  1570. XWindowSystemUtilities::ScopedXLock xLock;
  1571. X11Symbols::getInstance()->xFreeCursor (display, (Cursor) cursorHandle);
  1572. }
  1573. }
  1574. void* createDraggingHandCursor()
  1575. {
  1576. static unsigned char dragHandData[] = {
  1577. 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,16,0,
  1578. 0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,132,117,151,116,132,146,248,60,209,138,98,22,203,
  1579. 114,34,236,37,52,77,217, 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59
  1580. };
  1581. size_t dragHandDataSize = 99;
  1582. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), { 8, 7 }).create();
  1583. }
  1584. void* XWindowSystem::createStandardMouseCursor (MouseCursor::StandardCursorType type) const
  1585. {
  1586. if (display == nullptr)
  1587. return None;
  1588. unsigned int shape;
  1589. switch (type)
  1590. {
  1591. case MouseCursor::NormalCursor:
  1592. case MouseCursor::ParentCursor: return None; // Use parent cursor
  1593. case MouseCursor::NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), {}).create();
  1594. case MouseCursor::WaitCursor: shape = XC_watch; break;
  1595. case MouseCursor::IBeamCursor: shape = XC_xterm; break;
  1596. case MouseCursor::PointingHandCursor: shape = XC_hand2; break;
  1597. case MouseCursor::LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  1598. case MouseCursor::UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  1599. case MouseCursor::UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  1600. case MouseCursor::TopEdgeResizeCursor: shape = XC_top_side; break;
  1601. case MouseCursor::BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  1602. case MouseCursor::LeftEdgeResizeCursor: shape = XC_left_side; break;
  1603. case MouseCursor::RightEdgeResizeCursor: shape = XC_right_side; break;
  1604. case MouseCursor::TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  1605. case MouseCursor::TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  1606. case MouseCursor::BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  1607. case MouseCursor::BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  1608. case MouseCursor::CrosshairCursor: shape = XC_crosshair; break;
  1609. case MouseCursor::DraggingHandCursor: return createDraggingHandCursor();
  1610. case MouseCursor::CopyingCursor:
  1611. {
  1612. static unsigned char copyCursorData[] = {
  1613. 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,
  1614. 21,0,21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,78,133,218,215,137,31,82,154,100,200,
  1615. 86,91,202,142,12,108,212,87,235,174,15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  1616. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0
  1617. };
  1618. static constexpr int copyCursorSize = 119;
  1619. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), { 1, 3 }).create();
  1620. }
  1621. case MouseCursor::NumStandardCursorTypes:
  1622. default:
  1623. {
  1624. jassertfalse;
  1625. return None;
  1626. }
  1627. }
  1628. XWindowSystemUtilities::ScopedXLock xLock;
  1629. return (void*) X11Symbols::getInstance()->xCreateFontCursor (display, shape);
  1630. }
  1631. void XWindowSystem::showCursor (::Window windowH, void* cursorHandle) const
  1632. {
  1633. jassert (windowH != 0);
  1634. XWindowSystemUtilities::ScopedXLock xLock;
  1635. X11Symbols::getInstance()->xDefineCursor (display, windowH, (Cursor) cursorHandle);
  1636. }
  1637. bool XWindowSystem::isKeyCurrentlyDown (int keyCode) const
  1638. {
  1639. int keysym;
  1640. if (keyCode & Keys::extendedKeyModifier)
  1641. {
  1642. keysym = 0xff00 | (keyCode & 0xff);
  1643. }
  1644. else
  1645. {
  1646. keysym = keyCode;
  1647. if (keysym == (XK_Tab & 0xff)
  1648. || keysym == (XK_Return & 0xff)
  1649. || keysym == (XK_Escape & 0xff)
  1650. || keysym == (XK_BackSpace & 0xff))
  1651. {
  1652. keysym |= 0xff00;
  1653. }
  1654. }
  1655. XWindowSystemUtilities::ScopedXLock xLock;
  1656. auto keycode = X11Symbols::getInstance()->xKeysymToKeycode (display, (KeySym) keysym);
  1657. auto keybyte = keycode >> 3;
  1658. auto keybit = (1 << (keycode & 7));
  1659. return (Keys::keyStates [keybyte] & keybit) != 0;
  1660. }
  1661. ModifierKeys XWindowSystem::getNativeRealtimeModifiers() const
  1662. {
  1663. ::Window root, child;
  1664. int x, y, winx, winy;
  1665. unsigned int mask;
  1666. int mouseMods = 0;
  1667. XWindowSystemUtilities::ScopedXLock xLock;
  1668. if (X11Symbols::getInstance()->xQueryPointer (display,
  1669. X11Symbols::getInstance()->xRootWindow (display,
  1670. X11Symbols::getInstance()->xDefaultScreen (display)),
  1671. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  1672. {
  1673. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  1674. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  1675. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  1676. }
  1677. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1678. return ModifierKeys::currentModifiers;
  1679. }
  1680. Array<Displays::Display> XWindowSystem::findDisplays (float masterScale) const
  1681. {
  1682. Array<Displays::Display> displays;
  1683. Atom hints = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WORKAREA");
  1684. auto getWorkAreaPropertyData = [&] (int screenNum) -> unsigned char*
  1685. {
  1686. if (hints != None)
  1687. {
  1688. XWindowSystemUtilities::GetXProperty prop (X11Symbols::getInstance()->xRootWindow (display, screenNum), hints, 0, 4, false, XA_CARDINAL);
  1689. if (prop.success && prop.actualType == XA_CARDINAL && prop.actualFormat == 32 && prop.numItems == 4)
  1690. return prop.data;
  1691. }
  1692. return nullptr;
  1693. };
  1694. #if JUCE_USE_XRANDR
  1695. {
  1696. int major_opcode, first_event, first_error;
  1697. if (X11Symbols::getInstance()->xQueryExtension (display, "RANDR", &major_opcode, &first_event, &first_error))
  1698. {
  1699. auto numMonitors = X11Symbols::getInstance()->xScreenCount (display);
  1700. auto mainDisplay = X11Symbols::getInstance()->xRRGetOutputPrimary (display, X11Symbols::getInstance()->xRootWindow (display, 0));
  1701. for (int i = 0; i < numMonitors; ++i)
  1702. {
  1703. if (getWorkAreaPropertyData (i) == nullptr)
  1704. continue;
  1705. if (auto* screens = X11Symbols::getInstance()->xRRGetScreenResources (display,
  1706. X11Symbols::getInstance()->xRootWindow (display, i)))
  1707. {
  1708. for (int j = 0; j < screens->noutput; ++j)
  1709. {
  1710. if (screens->outputs[j])
  1711. {
  1712. // Xrandr on the raspberry pi fails to determine the main display (mainDisplay == 0)!
  1713. // Detect this edge case and make the first found display the main display
  1714. if (! mainDisplay)
  1715. mainDisplay = screens->outputs[j];
  1716. if (auto* output = X11Symbols::getInstance()->xRRGetOutputInfo (display, screens, screens->outputs[j]))
  1717. {
  1718. if (output->crtc)
  1719. {
  1720. if (auto* crtc = X11Symbols::getInstance()->xRRGetCrtcInfo (display, screens, output->crtc))
  1721. {
  1722. Displays::Display d;
  1723. d.totalArea = { crtc->x, crtc->y, (int) crtc->width, (int) crtc->height };
  1724. d.isMain = (mainDisplay == screens->outputs[j]) && (i == 0);
  1725. d.dpi = DisplayHelpers::getDisplayDPI (display, 0);
  1726. // The raspberry pi returns a zero sized display, so we need to guard for divide-by-zero
  1727. if (output->mm_width > 0 && output->mm_height > 0)
  1728. d.dpi = ((static_cast<double> (crtc->width) * 25.4 * 0.5) / static_cast<double> (output->mm_width))
  1729. + ((static_cast<double> (crtc->height) * 25.4 * 0.5) / static_cast<double> (output->mm_height));
  1730. auto scale = DisplayHelpers::getDisplayScale (output->name, d.dpi);
  1731. scale = (scale <= 0.1 ? 1.0 : scale);
  1732. d.scale = masterScale * scale;
  1733. if (d.isMain)
  1734. displays.insert (0, d);
  1735. else
  1736. displays.add (d);
  1737. X11Symbols::getInstance()->xRRFreeCrtcInfo (crtc);
  1738. }
  1739. }
  1740. X11Symbols::getInstance()->xRRFreeOutputInfo (output);
  1741. }
  1742. }
  1743. }
  1744. X11Symbols::getInstance()->xRRFreeScreenResources (screens);
  1745. }
  1746. }
  1747. if (! displays.isEmpty() && ! displays.getReference (0).isMain)
  1748. displays.getReference (0).isMain = true;
  1749. }
  1750. }
  1751. if (displays.isEmpty())
  1752. #endif
  1753. #if JUCE_USE_XINERAMA
  1754. {
  1755. auto screens = DisplayHelpers::xineramaQueryDisplays (display);
  1756. auto numMonitors = screens.size();
  1757. for (int index = 0; index < numMonitors; ++index)
  1758. {
  1759. for (auto j = numMonitors; --j >= 0;)
  1760. {
  1761. if (screens[j].screen_number == index)
  1762. {
  1763. Displays::Display d;
  1764. d.totalArea = { screens[j].x_org, screens[j].y_org,
  1765. screens[j].width, screens[j].height };
  1766. d.isMain = (index == 0);
  1767. d.scale = masterScale;
  1768. d.dpi = DisplayHelpers::getDisplayDPI (display, 0); // (all screens share the same DPI)
  1769. displays.add (d);
  1770. }
  1771. }
  1772. }
  1773. }
  1774. if (displays.isEmpty())
  1775. #endif
  1776. {
  1777. if (hints != None)
  1778. {
  1779. auto numMonitors = X11Symbols::getInstance()->xScreenCount (display);
  1780. for (int i = 0; i < numMonitors; ++i)
  1781. {
  1782. if (auto* positionData = getWorkAreaPropertyData (i))
  1783. {
  1784. std::array<long, 4> position;
  1785. for (auto& p : position)
  1786. {
  1787. memcpy (&p, positionData, sizeof (long));
  1788. positionData += sizeof (long);
  1789. }
  1790. Displays::Display d;
  1791. d.totalArea = { (int) position[0], (int) position[1],
  1792. (int) position[2], (int) position[3] };
  1793. d.isMain = displays.isEmpty();
  1794. d.scale = masterScale;
  1795. d.dpi = DisplayHelpers::getDisplayDPI (display, i);
  1796. displays.add (d);
  1797. }
  1798. }
  1799. }
  1800. if (displays.isEmpty())
  1801. {
  1802. Displays::Display d;
  1803. d.totalArea = { X11Symbols::getInstance()->xDisplayWidth (display, X11Symbols::getInstance()->xDefaultScreen (display)),
  1804. X11Symbols::getInstance()->xDisplayHeight (display, X11Symbols::getInstance()->xDefaultScreen (display)) };
  1805. d.isMain = true;
  1806. d.scale = masterScale;
  1807. d.dpi = DisplayHelpers::getDisplayDPI (display, 0);
  1808. displays.add (d);
  1809. }
  1810. }
  1811. for (auto& d : displays)
  1812. d.userArea = d.totalArea; // JUCE currently does not support requesting the user area on Linux
  1813. return displays;
  1814. }
  1815. ::Window XWindowSystem::createKeyProxy (::Window windowH) const
  1816. {
  1817. jassert (windowH != 0);
  1818. XSetWindowAttributes swa;
  1819. swa.event_mask = KeyPressMask | KeyReleaseMask | FocusChangeMask;
  1820. auto keyProxy = X11Symbols::getInstance()->xCreateWindow (display, windowH,
  1821. -1, -1, 1, 1, 0, 0,
  1822. InputOnly, CopyFromParent,
  1823. CWEventMask,
  1824. &swa);
  1825. X11Symbols::getInstance()->xMapWindow (display, keyProxy);
  1826. X11Symbols::getInstance()->xSaveContext (display, (XID) keyProxy, windowHandleXContext, (XPointer) this);
  1827. return keyProxy;
  1828. }
  1829. void XWindowSystem::deleteKeyProxy (::Window keyProxy) const
  1830. {
  1831. jassert (keyProxy != 0);
  1832. XPointer handlePointer;
  1833. if (! X11Symbols::getInstance()->xFindContext (display, (XID) keyProxy, windowHandleXContext, &handlePointer))
  1834. X11Symbols::getInstance()->xDeleteContext (display, (XID) keyProxy, windowHandleXContext);
  1835. X11Symbols::getInstance()->xDestroyWindow (display, keyProxy);
  1836. X11Symbols::getInstance()->xSync (display, false);
  1837. XEvent event;
  1838. while (X11Symbols::getInstance()->xCheckWindowEvent (display, keyProxy, getAllEventsMask (false), &event) == True)
  1839. {}
  1840. }
  1841. bool XWindowSystem::externalDragFileInit (LinuxComponentPeer<::Window>* peer, const StringArray& files, bool, std::function<void()>&& callback) const
  1842. {
  1843. auto& dragState = dragAndDropStateMap[peer];
  1844. if (dragState.isDragging())
  1845. return false;
  1846. StringArray uriList;
  1847. for (auto& f : files)
  1848. {
  1849. if (f.matchesWildcard ("?*://*", false))
  1850. uriList.add (f);
  1851. else
  1852. uriList.add ("file://" + f);
  1853. }
  1854. return dragState.externalDragInit ((::Window) peer->getNativeHandle(), false, uriList.joinIntoString ("\r\n"), std::move (callback));
  1855. }
  1856. bool XWindowSystem::externalDragTextInit (LinuxComponentPeer<::Window>* peer, const String& text, std::function<void()>&& callback) const
  1857. {
  1858. auto& dragState = dragAndDropStateMap[peer];
  1859. if (dragState.isDragging())
  1860. return false;
  1861. return dragState.externalDragInit ((::Window) peer->getNativeHandle(), true, text, std::move (callback));
  1862. }
  1863. void XWindowSystem::copyTextToClipboard (const String& clipText)
  1864. {
  1865. localClipboardContent = clipText;
  1866. X11Symbols::getInstance()->xSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  1867. X11Symbols::getInstance()->xSetSelectionOwner (display, atoms->clipboard, juce_messageWindowHandle, CurrentTime);
  1868. }
  1869. String XWindowSystem::getTextFromClipboard() const
  1870. {
  1871. String content;
  1872. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  1873. level" clipboard that is supposed to be filled by ctrl-C
  1874. etc). When a clipboard manager is running, the content of this
  1875. selection is preserved even when the original selection owner
  1876. exits.
  1877. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  1878. filled by good old x11 apps such as xterm)
  1879. */
  1880. auto selection = XA_PRIMARY;
  1881. Window selectionOwner = None;
  1882. if ((selectionOwner = X11Symbols::getInstance()->xGetSelectionOwner (display, selection)) == None)
  1883. {
  1884. selection = atoms->clipboard;
  1885. selectionOwner = X11Symbols::getInstance()->xGetSelectionOwner (display, selection);
  1886. }
  1887. if (selectionOwner != None)
  1888. {
  1889. if (selectionOwner == juce_messageWindowHandle)
  1890. content = localClipboardContent;
  1891. else if (! ClipboardHelpers::requestSelectionContent (display, content, selection, atoms->utf8String))
  1892. ClipboardHelpers::requestSelectionContent (display, content, selection, XA_STRING);
  1893. }
  1894. return content;
  1895. }
  1896. //==============================================================================
  1897. bool XWindowSystem::isParentWindowOf (::Window windowH, ::Window possibleChild) const
  1898. {
  1899. if (windowH != 0 && possibleChild != 0)
  1900. {
  1901. if (possibleChild == windowH)
  1902. return true;
  1903. Window* windowList = nullptr;
  1904. uint32 windowListSize = 0;
  1905. Window parent, root;
  1906. XWindowSystemUtilities::ScopedXLock xLock;
  1907. if (X11Symbols::getInstance()->xQueryTree (display, possibleChild, &root, &parent, &windowList, &windowListSize) != 0)
  1908. {
  1909. if (windowList != nullptr)
  1910. X11Symbols::getInstance()->xFree (windowList);
  1911. if (parent == root)
  1912. return false;
  1913. return isParentWindowOf (windowH, parent);
  1914. }
  1915. }
  1916. return false;
  1917. }
  1918. bool XWindowSystem::isFrontWindow (::Window windowH) const
  1919. {
  1920. jassert (windowH != 0);
  1921. Window* windowList = nullptr;
  1922. uint32 windowListSize = 0;
  1923. bool result = false;
  1924. XWindowSystemUtilities::ScopedXLock xLock;
  1925. Window parent;
  1926. auto root = X11Symbols::getInstance()->xRootWindow (display, X11Symbols::getInstance()->xDefaultScreen (display));
  1927. if (X11Symbols::getInstance()->xQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  1928. {
  1929. for (int i = (int) windowListSize; --i >= 0;)
  1930. {
  1931. if (auto* peer = dynamic_cast<LinuxComponentPeer<::Window>*> (getPeerFor (windowList[i])))
  1932. {
  1933. result = (peer == dynamic_cast<LinuxComponentPeer<::Window>*> (getPeerFor (windowH)));
  1934. break;
  1935. }
  1936. }
  1937. }
  1938. if (windowList != nullptr)
  1939. X11Symbols::getInstance()->xFree (windowList);
  1940. return result;
  1941. }
  1942. void XWindowSystem::xchangeProperty (::Window windowH, Atom property, Atom type, int format, const void* data, int numElements) const
  1943. {
  1944. jassert (windowH != 0);
  1945. X11Symbols::getInstance()->xChangeProperty (display, windowH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  1946. }
  1947. void XWindowSystem::removeWindowDecorations (::Window windowH) const
  1948. {
  1949. jassert (windowH != 0);
  1950. Atom hints = XWindowSystemUtilities::Atoms::getIfExists (display, "_MOTIF_WM_HINTS");
  1951. if (hints != None)
  1952. {
  1953. MotifWmHints motifHints;
  1954. zerostruct (motifHints);
  1955. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  1956. motifHints.decorations = 0;
  1957. XWindowSystemUtilities::ScopedXLock xLock;
  1958. xchangeProperty (windowH, hints, hints, 32, &motifHints, 4);
  1959. }
  1960. hints = XWindowSystemUtilities::Atoms::getIfExists (display, "_WIN_HINTS");
  1961. if (hints != None)
  1962. {
  1963. long gnomeHints = 0;
  1964. XWindowSystemUtilities::ScopedXLock xLock;
  1965. xchangeProperty (windowH, hints, hints, 32, &gnomeHints, 1);
  1966. }
  1967. hints = XWindowSystemUtilities::Atoms::getIfExists (display, "KWM_WIN_DECORATION");
  1968. if (hints != None)
  1969. {
  1970. long kwmHints = 2; /*KDE_tinyDecoration*/
  1971. XWindowSystemUtilities::ScopedXLock xLock;
  1972. xchangeProperty (windowH, hints, hints, 32, &kwmHints, 1);
  1973. }
  1974. hints = XWindowSystemUtilities::Atoms::getIfExists (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  1975. if (hints != None)
  1976. {
  1977. XWindowSystemUtilities::ScopedXLock xLock;
  1978. xchangeProperty (windowH, atoms->windowType, XA_ATOM, 32, &hints, 1);
  1979. }
  1980. }
  1981. void XWindowSystem::addWindowButtons (::Window windowH, int styleFlags) const
  1982. {
  1983. jassert (windowH != 0);
  1984. XWindowSystemUtilities::ScopedXLock xLock;
  1985. Atom hints = XWindowSystemUtilities::Atoms::getIfExists (display, "_MOTIF_WM_HINTS");
  1986. if (hints != None)
  1987. {
  1988. MotifWmHints motifHints;
  1989. zerostruct (motifHints);
  1990. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  1991. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  1992. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  1993. if ((styleFlags & ComponentPeer::windowHasCloseButton) != 0)
  1994. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  1995. if ((styleFlags & ComponentPeer::windowHasMinimiseButton) != 0)
  1996. {
  1997. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  1998. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  1999. }
  2000. if ((styleFlags & ComponentPeer::windowHasMaximiseButton) != 0)
  2001. {
  2002. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  2003. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  2004. }
  2005. if ((styleFlags & ComponentPeer::windowIsResizable) != 0)
  2006. {
  2007. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  2008. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  2009. }
  2010. xchangeProperty (windowH, hints, hints, 32, &motifHints, 5);
  2011. }
  2012. hints = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_ALLOWED_ACTIONS");
  2013. if (hints != None)
  2014. {
  2015. Atom netHints [6];
  2016. int num = 0;
  2017. if ((styleFlags & ComponentPeer::windowIsResizable) != 0)
  2018. netHints [num++] = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_ACTION_RESIZE");
  2019. if ((styleFlags & ComponentPeer::windowHasMaximiseButton) != 0)
  2020. netHints [num++] = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_ACTION_FULLSCREEN");
  2021. if ((styleFlags & ComponentPeer::windowHasMinimiseButton) != 0)
  2022. netHints [num++] = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_ACTION_MINIMIZE");
  2023. if ((styleFlags & ComponentPeer::windowHasCloseButton) != 0)
  2024. netHints [num++] = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_ACTION_CLOSE");
  2025. xchangeProperty (windowH, hints, XA_ATOM, 32, &netHints, num);
  2026. }
  2027. }
  2028. void XWindowSystem::setWindowType (::Window windowH, int styleFlags) const
  2029. {
  2030. jassert (windowH != 0);
  2031. Atom netHints [2];
  2032. if ((styleFlags & ComponentPeer::windowIsTemporary) != 0
  2033. || ((styleFlags & ComponentPeer::windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  2034. netHints [0] = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_WINDOW_TYPE_COMBO");
  2035. else
  2036. netHints [0] = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_WINDOW_TYPE_NORMAL");
  2037. xchangeProperty (windowH, atoms->windowType, XA_ATOM, 32, &netHints, 1);
  2038. int numHints = 0;
  2039. if ((styleFlags & ComponentPeer::windowAppearsOnTaskbar) == 0)
  2040. netHints [numHints++] = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_STATE_SKIP_TASKBAR");
  2041. if (getPeerFor (windowH)->getComponent().isAlwaysOnTop())
  2042. netHints [numHints++] = XWindowSystemUtilities::Atoms::getIfExists (display, "_NET_WM_STATE_ABOVE");
  2043. if (numHints > 0)
  2044. xchangeProperty (windowH, atoms->windowState, XA_ATOM, 32, &netHints, numHints);
  2045. }
  2046. void XWindowSystem::initialisePointerMap()
  2047. {
  2048. auto numButtons = X11Symbols::getInstance()->xGetPointerMapping (display, nullptr, 0);
  2049. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2050. if (numButtons == 2)
  2051. {
  2052. pointerMap[0] = Keys::LeftButton;
  2053. pointerMap[1] = Keys::RightButton;
  2054. }
  2055. else if (numButtons >= 3)
  2056. {
  2057. pointerMap[0] = Keys::LeftButton;
  2058. pointerMap[1] = Keys::MiddleButton;
  2059. pointerMap[2] = Keys::RightButton;
  2060. if (numButtons >= 5)
  2061. {
  2062. pointerMap[3] = Keys::WheelUp;
  2063. pointerMap[4] = Keys::WheelDown;
  2064. }
  2065. }
  2066. }
  2067. void XWindowSystem::deleteIconPixmaps (::Window windowH) const
  2068. {
  2069. jassert (windowH != 0);
  2070. XWindowSystemUtilities::ScopedXLock xLock;
  2071. if (auto* wmHints = X11Symbols::getInstance()->xGetWMHints (display, windowH))
  2072. {
  2073. if ((wmHints->flags & IconPixmapHint) != 0)
  2074. {
  2075. wmHints->flags &= ~IconPixmapHint;
  2076. X11Symbols::getInstance()->xFreePixmap (display, wmHints->icon_pixmap);
  2077. }
  2078. if ((wmHints->flags & IconMaskHint) != 0)
  2079. {
  2080. wmHints->flags &= ~IconMaskHint;
  2081. X11Symbols::getInstance()->xFreePixmap (display, wmHints->icon_mask);
  2082. }
  2083. X11Symbols::getInstance()->xSetWMHints (display, windowH, wmHints);
  2084. X11Symbols::getInstance()->xFree (wmHints);
  2085. }
  2086. }
  2087. // Alt and Num lock are not defined by standard X modifier constants: check what they're mapped to
  2088. void XWindowSystem::updateModifierMappings() const
  2089. {
  2090. XWindowSystemUtilities::ScopedXLock xLock;
  2091. auto altLeftCode = X11Symbols::getInstance()->xKeysymToKeycode (display, XK_Alt_L);
  2092. auto numLockCode = X11Symbols::getInstance()->xKeysymToKeycode (display, XK_Num_Lock);
  2093. Keys::AltMask = 0;
  2094. Keys::NumLockMask = 0;
  2095. if (auto* mapping = X11Symbols::getInstance()->xGetModifierMapping (display))
  2096. {
  2097. for (int modifierIdx = 0; modifierIdx < 8; ++modifierIdx)
  2098. {
  2099. for (int keyIndex = 0; keyIndex < mapping->max_keypermod; ++keyIndex)
  2100. {
  2101. auto key = mapping->modifiermap[(modifierIdx * mapping->max_keypermod) + keyIndex];
  2102. if (key == altLeftCode)
  2103. Keys::AltMask = 1 << modifierIdx;
  2104. else if (key == numLockCode)
  2105. Keys::NumLockMask = 1 << modifierIdx;
  2106. }
  2107. }
  2108. X11Symbols::getInstance()->xFreeModifiermap (mapping);
  2109. }
  2110. }
  2111. long XWindowSystem::getUserTime (::Window windowH) const
  2112. {
  2113. jassert (windowH != 0);
  2114. XWindowSystemUtilities::GetXProperty prop (windowH, atoms->userTime, 0, 65536, false, XA_CARDINAL);
  2115. if (! prop.success)
  2116. return 0;
  2117. long result = 0;
  2118. memcpy (&result, prop.data, sizeof (long));
  2119. return result;
  2120. }
  2121. //==============================================================================
  2122. void XWindowSystem::initialiseXDisplay()
  2123. {
  2124. jassert (display == nullptr);
  2125. String displayName (getenv ("DISPLAY"));
  2126. if (displayName.isEmpty())
  2127. displayName = ":0.0";
  2128. // it seems that on some systems XOpenDisplay will occasionally
  2129. // fail the first time, but succeed on a second attempt..
  2130. for (int retries = 2; --retries >= 0;)
  2131. {
  2132. display = X11Symbols::getInstance()->xOpenDisplay (displayName.toUTF8());
  2133. if (display != nullptr)
  2134. break;
  2135. }
  2136. // This is fatal! Print error and closedown
  2137. if (display == nullptr)
  2138. {
  2139. Logger::outputDebugString ("Failed to connect to the X Server.");
  2140. Process::terminate();
  2141. }
  2142. // Create a context to store user data associated with Windows we create
  2143. windowHandleXContext = (XContext) X11Symbols::getInstance()->xrmUniqueQuark();
  2144. // We're only interested in client messages for this window, which are always sent
  2145. XSetWindowAttributes swa;
  2146. swa.event_mask = NoEventMask;
  2147. // Create our message window (this will never be mapped)
  2148. auto screen = X11Symbols::getInstance()->xDefaultScreen (display);
  2149. juce_messageWindowHandle = X11Symbols::getInstance()->xCreateWindow (display, X11Symbols::getInstance()->xRootWindow (display, screen),
  2150. 0, 0, 1, 1, 0, 0, InputOnly,
  2151. X11Symbols::getInstance()->xDefaultVisual (display, screen),
  2152. CWEventMask, &swa);
  2153. X11Symbols::getInstance()->xSync (display, False);
  2154. atoms = std::make_unique<XWindowSystemUtilities::Atoms> (display);
  2155. // Get defaults for various properties
  2156. auto root = X11Symbols::getInstance()->xRootWindow (display, screen);
  2157. // Try to obtain a 32-bit visual or fallback to 24 or 16
  2158. visual = Visuals::findVisualFormat (display, 32, depth);
  2159. if (visual == nullptr)
  2160. {
  2161. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  2162. Process::terminate();
  2163. }
  2164. // Create and install a colormap suitable for our visual
  2165. colormap = X11Symbols::getInstance()->xCreateColormap (display, root, visual, AllocNone);
  2166. X11Symbols::getInstance()->xInstallColormap (display, colormap);
  2167. initialisePointerMap();
  2168. updateModifierMappings();
  2169. #if JUCE_USE_XSHM
  2170. if (XSHMHelpers::isShmAvailable (display))
  2171. shmCompletionEvent = X11Symbols::getInstance()->xShmGetEventBase (display) + ShmCompletion;
  2172. #endif
  2173. // Setup input event handler
  2174. LinuxEventLoop::registerFdCallback (X11Symbols::getInstance()->xConnectionNumber (display),
  2175. [this](int)
  2176. {
  2177. do
  2178. {
  2179. XEvent evt;
  2180. {
  2181. XWindowSystemUtilities::ScopedXLock xLock;
  2182. if (! X11Symbols::getInstance()->xPending (display))
  2183. return;
  2184. X11Symbols::getInstance()->xNextEvent (display, &evt);
  2185. }
  2186. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle
  2187. && handleSelectionRequest != nullptr)
  2188. {
  2189. handleSelectionRequest (evt.xselectionrequest);
  2190. }
  2191. else if (evt.xany.window != juce_messageWindowHandle
  2192. && dispatchWindowMessage != nullptr)
  2193. {
  2194. dispatchWindowMessage (evt);
  2195. }
  2196. } while (display != nullptr);
  2197. });
  2198. }
  2199. void XWindowSystem::destroyXDisplay()
  2200. {
  2201. if (xIsAvailable)
  2202. {
  2203. jassert (display != nullptr);
  2204. XWindowSystemUtilities::ScopedXLock xLock;
  2205. X11Symbols::getInstance()->xDestroyWindow (display, juce_messageWindowHandle);
  2206. juce_messageWindowHandle = 0;
  2207. X11Symbols::getInstance()->xSync (display, True);
  2208. LinuxEventLoop::unregisterFdCallback (X11Symbols::getInstance()->xConnectionNumber (display));
  2209. visual = nullptr;
  2210. X11Symbols::getInstance()->xCloseDisplay (display);
  2211. display = nullptr;
  2212. }
  2213. }
  2214. //==============================================================================
  2215. ::Window juce_createKeyProxyWindow (ComponentPeer* peer)
  2216. {
  2217. return XWindowSystem::getInstance()->createKeyProxy ((::Window) peer->getNativeHandle());
  2218. }
  2219. void juce_deleteKeyProxyWindow (::Window keyProxy)
  2220. {
  2221. XWindowSystem::getInstance()->deleteKeyProxy (keyProxy);
  2222. }
  2223. //==============================================================================
  2224. template <typename EventType>
  2225. static Point<float> getLogicalMousePos (const EventType& e, double scaleFactor) noexcept
  2226. {
  2227. return Point<float> ((float) e.x, (float) e.y) / scaleFactor;
  2228. }
  2229. static int64 getEventTime (::Time t)
  2230. {
  2231. static int64 eventTimeOffset = 0x12345678;
  2232. auto thisMessageTime = (int64) t;
  2233. if (eventTimeOffset == 0x12345678)
  2234. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  2235. return eventTimeOffset + thisMessageTime;
  2236. }
  2237. template <typename EventType>
  2238. static int64 getEventTime (const EventType& t)
  2239. {
  2240. return getEventTime (t.time);
  2241. }
  2242. void XWindowSystem::handleWindowMessage (LinuxComponentPeer<::Window>* peer, XEvent& event) const
  2243. {
  2244. switch (event.xany.type)
  2245. {
  2246. case KeyPressEventType: handleKeyPressEvent (peer, event.xkey); break;
  2247. case KeyRelease: handleKeyReleaseEvent (peer, event.xkey); break;
  2248. case ButtonPress: handleButtonPressEvent (peer, event.xbutton); break;
  2249. case ButtonRelease: handleButtonReleaseEvent (peer, event.xbutton); break;
  2250. case MotionNotify: handleMotionNotifyEvent (peer, event.xmotion); break;
  2251. case EnterNotify: handleEnterNotifyEvent (peer, event.xcrossing); break;
  2252. case LeaveNotify: handleLeaveNotifyEvent (peer, event.xcrossing); break;
  2253. case FocusIn: handleFocusInEvent (peer); break;
  2254. case FocusOut: handleFocusOutEvent (peer); break;
  2255. case Expose: handleExposeEvent (peer, event.xexpose); break;
  2256. case MappingNotify: handleMappingNotify (event.xmapping); break;
  2257. case ClientMessage: handleClientMessageEvent (peer, event.xclient, event); break;
  2258. case SelectionNotify: dragAndDropStateMap[peer].handleDragAndDropSelection (event); break;
  2259. case ConfigureNotify: handleConfigureNotifyEvent (peer, event.xconfigure); break;
  2260. case ReparentNotify:
  2261. case GravityNotify: handleGravityNotify (peer); break;
  2262. case SelectionClear: dragAndDropStateMap[peer].handleExternalSelectionClear(); break;
  2263. case SelectionRequest: dragAndDropStateMap[peer].handleExternalSelectionRequest (event); break;
  2264. case CirculateNotify:
  2265. case CreateNotify:
  2266. case DestroyNotify:
  2267. case UnmapNotify:
  2268. break;
  2269. case MapNotify:
  2270. peer->handleBroughtToFront();
  2271. break;
  2272. default:
  2273. #if JUCE_USE_XSHM
  2274. if (XSHMHelpers::isShmAvailable (display))
  2275. {
  2276. XWindowSystemUtilities::ScopedXLock xLock;
  2277. if (event.xany.type == shmCompletionEvent)
  2278. --shmPaintsPendingMap[(::Window) peer->getNativeHandle()];
  2279. }
  2280. #endif
  2281. break;
  2282. }
  2283. }
  2284. void XWindowSystem::handleKeyPressEvent (LinuxComponentPeer<::Window>* peer, XKeyEvent& keyEvent) const
  2285. {
  2286. auto oldMods = ModifierKeys::currentModifiers;
  2287. char utf8 [64] = { 0 };
  2288. juce_wchar unicodeChar = 0;
  2289. int keyCode = 0;
  2290. bool keyDownChange = false;
  2291. KeySym sym;
  2292. {
  2293. XWindowSystemUtilities::ScopedXLock xLock;
  2294. updateKeyStates ((int) keyEvent.keycode, true);
  2295. String oldLocale (::setlocale (LC_ALL, nullptr));
  2296. ::setlocale (LC_ALL, "");
  2297. X11Symbols::getInstance()->xLookupString (&keyEvent, utf8, sizeof (utf8), &sym, nullptr);
  2298. if (oldLocale.isNotEmpty())
  2299. ::setlocale (LC_ALL, oldLocale.toRawUTF8());
  2300. unicodeChar = *CharPointer_UTF8 (utf8);
  2301. keyCode = (int) unicodeChar;
  2302. if (keyCode < 0x20)
  2303. keyCode = (int) X11Symbols::getInstance()->xkbKeycodeToKeysym (display, (::KeyCode) keyEvent.keycode, 0,
  2304. ModifierKeys::currentModifiers.isShiftDown() ? 1 : 0);
  2305. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  2306. }
  2307. bool keyPressed = false;
  2308. if ((sym & 0xff00) == 0xff00 || keyCode == XK_ISO_Left_Tab)
  2309. {
  2310. switch (sym) // Translate keypad
  2311. {
  2312. case XK_KP_Add: keyCode = XK_plus; break;
  2313. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  2314. case XK_KP_Divide: keyCode = XK_slash; break;
  2315. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  2316. case XK_KP_Enter: keyCode = XK_Return; break;
  2317. case XK_KP_Insert: keyCode = XK_Insert; break;
  2318. case XK_Delete:
  2319. case XK_KP_Delete: keyCode = XK_Delete; break;
  2320. case XK_KP_Left: keyCode = XK_Left; break;
  2321. case XK_KP_Right: keyCode = XK_Right; break;
  2322. case XK_KP_Up: keyCode = XK_Up; break;
  2323. case XK_KP_Down: keyCode = XK_Down; break;
  2324. case XK_KP_Home: keyCode = XK_Home; break;
  2325. case XK_KP_End: keyCode = XK_End; break;
  2326. case XK_KP_Page_Down: keyCode = XK_Page_Down; break;
  2327. case XK_KP_Page_Up: keyCode = XK_Page_Up; break;
  2328. case XK_KP_0: keyCode = XK_0; break;
  2329. case XK_KP_1: keyCode = XK_1; break;
  2330. case XK_KP_2: keyCode = XK_2; break;
  2331. case XK_KP_3: keyCode = XK_3; break;
  2332. case XK_KP_4: keyCode = XK_4; break;
  2333. case XK_KP_5: keyCode = XK_5; break;
  2334. case XK_KP_6: keyCode = XK_6; break;
  2335. case XK_KP_7: keyCode = XK_7; break;
  2336. case XK_KP_8: keyCode = XK_8; break;
  2337. case XK_KP_9: keyCode = XK_9; break;
  2338. default: break;
  2339. }
  2340. switch (keyCode)
  2341. {
  2342. case XK_Left:
  2343. case XK_Right:
  2344. case XK_Up:
  2345. case XK_Down:
  2346. case XK_Page_Up:
  2347. case XK_Page_Down:
  2348. case XK_End:
  2349. case XK_Home:
  2350. case XK_Delete:
  2351. case XK_Insert:
  2352. keyPressed = true;
  2353. keyCode = (keyCode & 0xff) | Keys::extendedKeyModifier;
  2354. break;
  2355. case XK_Tab:
  2356. case XK_Return:
  2357. case XK_Escape:
  2358. case XK_BackSpace:
  2359. keyPressed = true;
  2360. keyCode &= 0xff;
  2361. break;
  2362. case XK_ISO_Left_Tab:
  2363. keyPressed = true;
  2364. keyCode = XK_Tab & 0xff;
  2365. break;
  2366. default:
  2367. if (sym >= XK_F1 && sym <= XK_F35)
  2368. {
  2369. keyPressed = true;
  2370. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  2371. }
  2372. break;
  2373. }
  2374. }
  2375. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  2376. keyPressed = true;
  2377. if (oldMods != ModifierKeys::currentModifiers)
  2378. peer->handleModifierKeysChange();
  2379. if (keyDownChange)
  2380. peer->handleKeyUpOrDown (true);
  2381. if (keyPressed)
  2382. peer->handleKeyPress (keyCode, unicodeChar);
  2383. }
  2384. void XWindowSystem::handleKeyReleaseEvent (LinuxComponentPeer<::Window>* peer, const XKeyEvent& keyEvent) const
  2385. {
  2386. auto isKeyReleasePartOfAutoRepeat = [&]() -> bool
  2387. {
  2388. if (X11Symbols::getInstance()->xPending (display))
  2389. {
  2390. XEvent e;
  2391. X11Symbols::getInstance()->xPeekEvent (display, &e);
  2392. // Look for a subsequent key-down event with the same timestamp and keycode
  2393. return e.type == KeyPressEventType
  2394. && e.xkey.keycode == keyEvent.keycode
  2395. && e.xkey.time == keyEvent.time;
  2396. }
  2397. return false;
  2398. }();
  2399. if (! isKeyReleasePartOfAutoRepeat)
  2400. {
  2401. updateKeyStates ((int) keyEvent.keycode, false);
  2402. KeySym sym;
  2403. {
  2404. XWindowSystemUtilities::ScopedXLock xLock;
  2405. sym = X11Symbols::getInstance()->xkbKeycodeToKeysym (display, (::KeyCode) keyEvent.keycode, 0, 0);
  2406. }
  2407. auto oldMods = ModifierKeys::currentModifiers;
  2408. auto keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  2409. if (oldMods != ModifierKeys::currentModifiers)
  2410. peer->handleModifierKeysChange();
  2411. if (keyDownChange)
  2412. peer->handleKeyUpOrDown (false);
  2413. }
  2414. }
  2415. void XWindowSystem::handleWheelEvent (LinuxComponentPeer<::Window>* peer, const XButtonPressedEvent& buttonPressEvent, float amount) const
  2416. {
  2417. MouseWheelDetails wheel;
  2418. wheel.deltaX = 0.0f;
  2419. wheel.deltaY = amount;
  2420. wheel.isReversed = false;
  2421. wheel.isSmooth = false;
  2422. wheel.isInertial = false;
  2423. peer->handleMouseWheel (MouseInputSource::InputSourceType::mouse, getLogicalMousePos (buttonPressEvent, peer->getPlatformScaleFactor()),
  2424. getEventTime (buttonPressEvent), wheel);
  2425. }
  2426. void XWindowSystem::handleButtonPressEvent (LinuxComponentPeer<::Window>* peer, const XButtonPressedEvent& buttonPressEvent, int buttonModifierFlag) const
  2427. {
  2428. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (buttonModifierFlag);
  2429. peer->toFront (true);
  2430. peer->handleMouseEvent (MouseInputSource::InputSourceType::mouse, getLogicalMousePos (buttonPressEvent, peer->getPlatformScaleFactor()),
  2431. ModifierKeys::currentModifiers, MouseInputSource::invalidPressure,
  2432. MouseInputSource::invalidOrientation, getEventTime (buttonPressEvent), {});
  2433. }
  2434. void XWindowSystem::handleButtonPressEvent (LinuxComponentPeer<::Window>* peer, const XButtonPressedEvent& buttonPressEvent) const
  2435. {
  2436. updateKeyModifiers ((int) buttonPressEvent.state);
  2437. auto mapIndex = (uint32) (buttonPressEvent.button - Button1);
  2438. if (mapIndex < (uint32) numElementsInArray (pointerMap))
  2439. {
  2440. switch (pointerMap[mapIndex])
  2441. {
  2442. case Keys::WheelUp: handleWheelEvent (peer, buttonPressEvent, 50.0f / 256.0f); break;
  2443. case Keys::WheelDown: handleWheelEvent (peer, buttonPressEvent, -50.0f / 256.0f); break;
  2444. case Keys::LeftButton: handleButtonPressEvent (peer, buttonPressEvent, ModifierKeys::leftButtonModifier); break;
  2445. case Keys::RightButton: handleButtonPressEvent (peer, buttonPressEvent, ModifierKeys::rightButtonModifier); break;
  2446. case Keys::MiddleButton: handleButtonPressEvent (peer, buttonPressEvent, ModifierKeys::middleButtonModifier); break;
  2447. default: break;
  2448. }
  2449. }
  2450. }
  2451. void XWindowSystem::handleButtonReleaseEvent (LinuxComponentPeer<::Window>* peer, const XButtonReleasedEvent& buttonRelEvent) const
  2452. {
  2453. updateKeyModifiers ((int) buttonRelEvent.state);
  2454. if (peer->getParentWindow() != 0)
  2455. peer->updateWindowBounds();
  2456. auto mapIndex = (uint32) (buttonRelEvent.button - Button1);
  2457. if (mapIndex < (uint32) numElementsInArray (pointerMap))
  2458. {
  2459. switch (pointerMap[mapIndex])
  2460. {
  2461. case Keys::LeftButton: ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
  2462. case Keys::RightButton: ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
  2463. case Keys::MiddleButton: ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
  2464. default: break;
  2465. }
  2466. }
  2467. auto& dragState = dragAndDropStateMap[peer];
  2468. if (dragState.isDragging())
  2469. dragState.handleExternalDragButtonReleaseEvent();
  2470. peer->handleMouseEvent (MouseInputSource::InputSourceType::mouse, getLogicalMousePos (buttonRelEvent, peer->getPlatformScaleFactor()),
  2471. ModifierKeys::currentModifiers, MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (buttonRelEvent));
  2472. }
  2473. void XWindowSystem::handleMotionNotifyEvent (LinuxComponentPeer<::Window>* peer, const XPointerMovedEvent& movedEvent) const
  2474. {
  2475. updateKeyModifiers ((int) movedEvent.state);
  2476. auto& dragState = dragAndDropStateMap[peer];
  2477. if (dragState.isDragging())
  2478. dragState.handleExternalDragMotionNotify();
  2479. peer->handleMouseEvent (MouseInputSource::InputSourceType::mouse, getLogicalMousePos (movedEvent, peer->getPlatformScaleFactor()),
  2480. ModifierKeys::currentModifiers, MouseInputSource::invalidPressure,
  2481. MouseInputSource::invalidOrientation, getEventTime (movedEvent));
  2482. }
  2483. void XWindowSystem::handleEnterNotifyEvent (LinuxComponentPeer<::Window>* peer, const XEnterWindowEvent& enterEvent) const
  2484. {
  2485. if (peer->getParentWindow() != 0)
  2486. peer->updateWindowBounds();
  2487. if (! ModifierKeys::currentModifiers.isAnyMouseButtonDown())
  2488. {
  2489. updateKeyModifiers ((int) enterEvent.state);
  2490. peer->handleMouseEvent (MouseInputSource::InputSourceType::mouse, getLogicalMousePos (enterEvent, peer->getPlatformScaleFactor()),
  2491. ModifierKeys::currentModifiers, MouseInputSource::invalidPressure,
  2492. MouseInputSource::invalidOrientation, getEventTime (enterEvent));
  2493. }
  2494. }
  2495. void XWindowSystem::handleLeaveNotifyEvent (LinuxComponentPeer<::Window>* peer, const XLeaveWindowEvent& leaveEvent) const
  2496. {
  2497. // Suppress the normal leave if we've got a pointer grab, or if
  2498. // it's a bogus one caused by clicking a mouse button when running
  2499. // in a Window manager
  2500. if (((! ModifierKeys::currentModifiers.isAnyMouseButtonDown()) && leaveEvent.mode == NotifyNormal)
  2501. || leaveEvent.mode == NotifyUngrab)
  2502. {
  2503. updateKeyModifiers ((int) leaveEvent.state);
  2504. peer->handleMouseEvent (MouseInputSource::InputSourceType::mouse, getLogicalMousePos (leaveEvent, peer->getPlatformScaleFactor()),
  2505. ModifierKeys::currentModifiers, MouseInputSource::invalidPressure,
  2506. MouseInputSource::invalidOrientation, getEventTime (leaveEvent));
  2507. }
  2508. }
  2509. void XWindowSystem::handleFocusInEvent (LinuxComponentPeer<::Window>* peer) const
  2510. {
  2511. peer->isActiveApplication = true;
  2512. if (isFocused ((::Window) peer->getNativeHandle()) && ! peer->focused)
  2513. {
  2514. peer->focused = true;
  2515. peer->handleFocusGain();
  2516. }
  2517. }
  2518. void XWindowSystem::handleFocusOutEvent (LinuxComponentPeer<::Window>* peer) const
  2519. {
  2520. if (! isFocused ((::Window) peer->getNativeHandle()) && peer->focused)
  2521. {
  2522. peer->focused = false;
  2523. peer->isActiveApplication = false;
  2524. peer->handleFocusLoss();
  2525. }
  2526. }
  2527. void XWindowSystem::handleExposeEvent (LinuxComponentPeer<::Window>* peer, XExposeEvent& exposeEvent) const
  2528. {
  2529. // Batch together all pending expose events
  2530. XEvent nextEvent;
  2531. XWindowSystemUtilities::ScopedXLock xLock;
  2532. // if we have opengl contexts then just repaint them all
  2533. // regardless if this is really necessary
  2534. peer->repaintOpenGLContexts();
  2535. auto windowH = (::Window) peer->getNativeHandle();
  2536. if (exposeEvent.window != windowH)
  2537. {
  2538. Window child;
  2539. X11Symbols::getInstance()->xTranslateCoordinates (display, exposeEvent.window, windowH,
  2540. exposeEvent.x, exposeEvent.y, &exposeEvent.x, &exposeEvent.y,
  2541. &child);
  2542. }
  2543. // exposeEvent is in local window local coordinates so do not convert with
  2544. // physicalToScaled, but rather use currentScaleFactor
  2545. auto currentScaleFactor = peer->getPlatformScaleFactor();
  2546. peer->repaint (Rectangle<int> (exposeEvent.x, exposeEvent.y,
  2547. exposeEvent.width, exposeEvent.height) / currentScaleFactor);
  2548. while (X11Symbols::getInstance()->xEventsQueued (display, QueuedAfterFlush) > 0)
  2549. {
  2550. X11Symbols::getInstance()->xPeekEvent (display, &nextEvent);
  2551. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent.window)
  2552. break;
  2553. X11Symbols::getInstance()->xNextEvent (display, &nextEvent);
  2554. auto& nextExposeEvent = (XExposeEvent&) nextEvent.xexpose;
  2555. peer->repaint (Rectangle<int> (nextExposeEvent.x, nextExposeEvent.y,
  2556. nextExposeEvent.width, nextExposeEvent.height) / currentScaleFactor);
  2557. }
  2558. }
  2559. void XWindowSystem::handleConfigureNotifyEvent (LinuxComponentPeer<::Window>* peer, XConfigureEvent& confEvent) const
  2560. {
  2561. peer->updateWindowBounds();
  2562. peer->updateBorderSize();
  2563. peer->handleMovedOrResized();
  2564. // if the native title bar is dragged, need to tell any active menus, etc.
  2565. if ((peer->getStyleFlags() & ComponentPeer::windowHasTitleBar) != 0
  2566. && peer->getComponent().isCurrentlyBlockedByAnotherModalComponent())
  2567. {
  2568. if (auto* currentModalComp = Component::getCurrentlyModalComponent())
  2569. currentModalComp->inputAttemptWhenModal();
  2570. }
  2571. auto windowH = (::Window) peer->getNativeHandle();
  2572. if (confEvent.window == windowH && confEvent.above != 0 && isFrontWindow (windowH))
  2573. peer->handleBroughtToFront();
  2574. }
  2575. void XWindowSystem::handleGravityNotify (LinuxComponentPeer<::Window>* peer) const
  2576. {
  2577. peer->updateWindowBounds();
  2578. peer->updateBorderSize();
  2579. peer->handleMovedOrResized();
  2580. }
  2581. void XWindowSystem::handleMappingNotify (XMappingEvent& mappingEvent) const
  2582. {
  2583. if (mappingEvent.request != MappingPointer)
  2584. {
  2585. // Deal with modifier/keyboard mapping
  2586. XWindowSystemUtilities::ScopedXLock xLock;
  2587. X11Symbols::getInstance()->xRefreshKeyboardMapping (&mappingEvent);
  2588. updateModifierMappings();
  2589. }
  2590. }
  2591. void XWindowSystem::handleClientMessageEvent (LinuxComponentPeer<::Window>* peer, XClientMessageEvent& clientMsg, XEvent& event) const
  2592. {
  2593. if (clientMsg.message_type == atoms->protocols && clientMsg.format == 32)
  2594. {
  2595. auto atom = (Atom) clientMsg.data.l[0];
  2596. if (atom == atoms->protocolList [XWindowSystemUtilities::Atoms::PING])
  2597. {
  2598. auto root = X11Symbols::getInstance()->xRootWindow (display, X11Symbols::getInstance()->xDefaultScreen (display));
  2599. clientMsg.window = root;
  2600. X11Symbols::getInstance()->xSendEvent (display, root, False, NoEventMask, &event);
  2601. X11Symbols::getInstance()->xFlush (display);
  2602. }
  2603. else if (atom == atoms->protocolList [XWindowSystemUtilities::Atoms::TAKE_FOCUS])
  2604. {
  2605. if ((peer->getStyleFlags() & ComponentPeer::windowIgnoresKeyPresses) == 0)
  2606. {
  2607. XWindowAttributes atts;
  2608. XWindowSystemUtilities::ScopedXLock xLock;
  2609. if (clientMsg.window != 0
  2610. && X11Symbols::getInstance()->xGetWindowAttributes (display, clientMsg.window, &atts))
  2611. {
  2612. if (atts.map_state == IsViewable)
  2613. {
  2614. auto windowH = (::Window) peer->getNativeHandle();
  2615. X11Symbols::getInstance()->xSetInputFocus (display, (clientMsg.window == windowH ? getFocusWindow (windowH)
  2616. : clientMsg.window),
  2617. RevertToParent, (::Time) clientMsg.data.l[1]);
  2618. }
  2619. }
  2620. }
  2621. }
  2622. else if (atom == atoms->protocolList [XWindowSystemUtilities::Atoms::DELETE_WINDOW])
  2623. {
  2624. peer->handleUserClosingWindow();
  2625. }
  2626. }
  2627. else if (clientMsg.message_type == atoms->XdndEnter)
  2628. {
  2629. dragAndDropStateMap[peer].handleDragAndDropEnter (clientMsg, peer);
  2630. }
  2631. else if (clientMsg.message_type == atoms->XdndLeave)
  2632. {
  2633. dragAndDropStateMap[peer].handleDragAndDropExit();
  2634. dragAndDropStateMap.erase (peer);
  2635. }
  2636. else if (clientMsg.message_type == atoms->XdndPosition)
  2637. {
  2638. dragAndDropStateMap[peer].handleDragAndDropPosition (clientMsg, peer);
  2639. }
  2640. else if (clientMsg.message_type == atoms->XdndDrop)
  2641. {
  2642. dragAndDropStateMap[peer].handleDragAndDropDrop (clientMsg, peer);
  2643. }
  2644. else if (clientMsg.message_type == atoms->XdndStatus)
  2645. {
  2646. dragAndDropStateMap[peer].handleExternalDragAndDropStatus (clientMsg);
  2647. }
  2648. else if (clientMsg.message_type == atoms->XdndFinished)
  2649. {
  2650. dragAndDropStateMap[peer].externalResetDragAndDrop();
  2651. }
  2652. else if (clientMsg.message_type == atoms->XembedMsgType && clientMsg.format == 32)
  2653. {
  2654. handleXEmbedMessage (peer, clientMsg);
  2655. }
  2656. }
  2657. void XWindowSystem::handleXEmbedMessage (LinuxComponentPeer<::Window>* peer, XClientMessageEvent& clientMsg) const
  2658. {
  2659. switch (clientMsg.data.l[1])
  2660. {
  2661. case 0: // XEMBED_EMBEDDED_NOTIFY
  2662. peer->setParentWindow ((::Window) clientMsg.data.l[3]);
  2663. peer->updateWindowBounds();
  2664. peer->getComponent().setBounds (peer->getBounds());
  2665. break;
  2666. case 4: // XEMBED_FOCUS_IN
  2667. handleFocusInEvent (peer);
  2668. break;
  2669. case 5: // XEMBED_FOCUS_OUT
  2670. handleFocusOutEvent (peer);
  2671. break;
  2672. default:
  2673. break;
  2674. }
  2675. }
  2676. //==============================================================================
  2677. namespace WindowingHelpers
  2678. {
  2679. static void windowMessageReceive (XEvent& event)
  2680. {
  2681. if (event.xany.window != None)
  2682. {
  2683. #if JUCE_X11_SUPPORTS_XEMBED
  2684. if (! juce_handleXEmbedEvent (nullptr, &event))
  2685. #endif
  2686. {
  2687. if (auto* peer = dynamic_cast<LinuxComponentPeer<::Window>*> (getPeerFor (event.xany.window)))
  2688. XWindowSystem::getInstance()->handleWindowMessage (peer, event);
  2689. }
  2690. }
  2691. else if (event.xany.type == KeymapNotify)
  2692. {
  2693. auto& keymapEvent = (const XKeymapEvent&) event.xkeymap;
  2694. memcpy (Keys::keyStates, keymapEvent.key_vector, 32);
  2695. }
  2696. }
  2697. }
  2698. struct WindowingCallbackInitialiser
  2699. {
  2700. WindowingCallbackInitialiser()
  2701. {
  2702. dispatchWindowMessage = WindowingHelpers::windowMessageReceive;
  2703. }
  2704. };
  2705. static WindowingCallbackInitialiser windowingInitialiser;
  2706. JUCE_IMPLEMENT_SINGLETON (XWindowSystem)
  2707. } // namespace juce