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.

3908 lines
150KB

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