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.

3405 lines
132KB

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