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.

3879 lines
149KB

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