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.

3490 lines
134KB

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