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.

4175 lines
148KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  22. #define JUCE_DEBUG_XERRORS 1
  23. #endif
  24. #if JUCE_MODULE_AVAILABLE_juce_gui_extra
  25. #define JUCE_X11_SUPPORTS_XEMBED 1
  26. #else
  27. #define JUCE_X11_SUPPORTS_XEMBED 0
  28. #endif
  29. #if JUCE_X11_SUPPORTS_XEMBED
  30. bool juce_handleXEmbedEvent (ComponentPeer*, void*);
  31. unsigned long juce_getCurrentFocusWindow (ComponentPeer*);
  32. #endif
  33. extern WindowMessageReceiveCallback dispatchWindowMessage;
  34. extern XContext windowHandleXContext;
  35. //=============================== X11 - Keys ===================================
  36. namespace Keys
  37. {
  38. enum MouseButtons
  39. {
  40. NoButton = 0,
  41. LeftButton = 1,
  42. MiddleButton = 2,
  43. RightButton = 3,
  44. WheelUp = 4,
  45. WheelDown = 5
  46. };
  47. static int AltMask = 0;
  48. static int NumLockMask = 0;
  49. static bool numLock = false;
  50. static bool capsLock = false;
  51. static char keyStates [32];
  52. static const int extendedKeyModifier = 0x10000000;
  53. }
  54. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  55. {
  56. ScopedXDisplay xDisplay;
  57. if (auto display = xDisplay.display)
  58. {
  59. int keysym;
  60. if (keyCode & Keys::extendedKeyModifier)
  61. {
  62. keysym = 0xff00 | (keyCode & 0xff);
  63. }
  64. else
  65. {
  66. keysym = keyCode;
  67. if (keysym == (XK_Tab & 0xff)
  68. || keysym == (XK_Return & 0xff)
  69. || keysym == (XK_Escape & 0xff)
  70. || keysym == (XK_BackSpace & 0xff))
  71. {
  72. keysym |= 0xff00;
  73. }
  74. }
  75. ScopedXLock xlock (display);
  76. const int keycode = XKeysymToKeycode (display, (KeySym) keysym);
  77. const int keybyte = keycode >> 3;
  78. const int keybit = (1 << (keycode & 7));
  79. return (Keys::keyStates [keybyte] & keybit) != 0;
  80. }
  81. return false;
  82. }
  83. //==============================================================================
  84. const int KeyPress::spaceKey = XK_space & 0xff;
  85. const int KeyPress::returnKey = XK_Return & 0xff;
  86. const int KeyPress::escapeKey = XK_Escape & 0xff;
  87. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  88. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  89. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  90. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  91. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  92. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  93. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  94. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  95. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  96. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  97. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  98. const int KeyPress::tabKey = XK_Tab & 0xff;
  99. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  100. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  101. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  102. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  103. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  104. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  105. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  106. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  107. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  108. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  109. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  110. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  111. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  112. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  113. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  114. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  115. const int KeyPress::F17Key = (XK_F17 & 0xff) | Keys::extendedKeyModifier;
  116. const int KeyPress::F18Key = (XK_F18 & 0xff) | Keys::extendedKeyModifier;
  117. const int KeyPress::F19Key = (XK_F19 & 0xff) | Keys::extendedKeyModifier;
  118. const int KeyPress::F20Key = (XK_F20 & 0xff) | Keys::extendedKeyModifier;
  119. const int KeyPress::F21Key = (XK_F21 & 0xff) | Keys::extendedKeyModifier;
  120. const int KeyPress::F22Key = (XK_F22 & 0xff) | Keys::extendedKeyModifier;
  121. const int KeyPress::F23Key = (XK_F23 & 0xff) | Keys::extendedKeyModifier;
  122. const int KeyPress::F24Key = (XK_F24 & 0xff) | Keys::extendedKeyModifier;
  123. const int KeyPress::F25Key = (XK_F25 & 0xff) | Keys::extendedKeyModifier;
  124. const int KeyPress::F26Key = (XK_F26 & 0xff) | Keys::extendedKeyModifier;
  125. const int KeyPress::F27Key = (XK_F27 & 0xff) | Keys::extendedKeyModifier;
  126. const int KeyPress::F28Key = (XK_F28 & 0xff) | Keys::extendedKeyModifier;
  127. const int KeyPress::F29Key = (XK_F29 & 0xff) | Keys::extendedKeyModifier;
  128. const int KeyPress::F30Key = (XK_F30 & 0xff) | Keys::extendedKeyModifier;
  129. const int KeyPress::F31Key = (XK_F31 & 0xff) | Keys::extendedKeyModifier;
  130. const int KeyPress::F32Key = (XK_F32 & 0xff) | Keys::extendedKeyModifier;
  131. const int KeyPress::F33Key = (XK_F33 & 0xff) | Keys::extendedKeyModifier;
  132. const int KeyPress::F34Key = (XK_F34 & 0xff) | Keys::extendedKeyModifier;
  133. const int KeyPress::F35Key = (XK_F35 & 0xff) | Keys::extendedKeyModifier;
  134. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  135. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  136. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  137. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  138. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  139. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  140. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  141. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  142. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  143. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  144. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  145. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  146. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  147. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  148. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  149. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  150. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  151. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  152. const int KeyPress::playKey = ((int) 0xffeeff00) | Keys::extendedKeyModifier;
  153. const int KeyPress::stopKey = ((int) 0xffeeff01) | Keys::extendedKeyModifier;
  154. const int KeyPress::fastForwardKey = ((int) 0xffeeff02) | Keys::extendedKeyModifier;
  155. const int KeyPress::rewindKey = ((int) 0xffeeff03) | Keys::extendedKeyModifier;
  156. //================================== X11 - Shm =================================
  157. #if JUCE_USE_XSHM
  158. namespace XSHMHelpers
  159. {
  160. static int trappedErrorCode = 0;
  161. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  162. {
  163. trappedErrorCode = err->error_code;
  164. return 0;
  165. }
  166. static bool isShmAvailable (::Display* display) noexcept
  167. {
  168. static bool isChecked = false;
  169. static bool isAvailable = false;
  170. if (! isChecked)
  171. {
  172. isChecked = true;
  173. if (display != nullptr)
  174. {
  175. int major, minor;
  176. Bool pixmaps;
  177. ScopedXLock xlock (display);
  178. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  179. {
  180. trappedErrorCode = 0;
  181. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  182. XShmSegmentInfo segmentInfo;
  183. zerostruct (segmentInfo);
  184. if (auto* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  185. 24, ZPixmap, nullptr, &segmentInfo, 50, 50))
  186. {
  187. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  188. (size_t) (xImage->bytes_per_line * xImage->height),
  189. IPC_CREAT | 0777)) >= 0)
  190. {
  191. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, nullptr, 0);
  192. if (segmentInfo.shmaddr != (void*) -1)
  193. {
  194. segmentInfo.readOnly = False;
  195. xImage->data = segmentInfo.shmaddr;
  196. XSync (display, False);
  197. if (XShmAttach (display, &segmentInfo) != 0)
  198. {
  199. XSync (display, False);
  200. XShmDetach (display, &segmentInfo);
  201. isAvailable = true;
  202. }
  203. }
  204. XFlush (display);
  205. XDestroyImage (xImage);
  206. shmdt (segmentInfo.shmaddr);
  207. }
  208. shmctl (segmentInfo.shmid, IPC_RMID, nullptr);
  209. XSetErrorHandler (oldHandler);
  210. if (trappedErrorCode != 0)
  211. isAvailable = false;
  212. }
  213. }
  214. }
  215. }
  216. return isAvailable;
  217. }
  218. }
  219. #endif
  220. //=============================== X11 - Render =================================
  221. #if JUCE_USE_XRENDER
  222. namespace XRender
  223. {
  224. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  225. typedef XRenderPictFormat* (*tXRenderFindStandardFormat) (Display*, int);
  226. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  227. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  228. static tXRenderQueryVersion xRenderQueryVersion = nullptr;
  229. static tXRenderFindStandardFormat xRenderFindStandardFormat = nullptr;
  230. static tXRenderFindFormat xRenderFindFormat = nullptr;
  231. static tXRenderFindVisualFormat xRenderFindVisualFormat = nullptr;
  232. static bool isAvailable (::Display* display)
  233. {
  234. static bool hasLoaded = false;
  235. if (! hasLoaded)
  236. {
  237. if (display != nullptr)
  238. {
  239. hasLoaded = true;
  240. ScopedXLock xlock (display);
  241. if (void* h = dlopen ("libXrender.so.1", RTLD_GLOBAL | RTLD_NOW))
  242. {
  243. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  244. xRenderFindStandardFormat = (tXRenderFindStandardFormat) dlsym (h, "XRenderFindStandardFormat");
  245. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  246. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  247. }
  248. if (xRenderQueryVersion != nullptr
  249. && xRenderFindStandardFormat != nullptr
  250. && xRenderFindFormat != nullptr
  251. && xRenderFindVisualFormat != nullptr)
  252. {
  253. int major, minor;
  254. if (xRenderQueryVersion (display, &major, &minor))
  255. return true;
  256. }
  257. }
  258. xRenderQueryVersion = nullptr;
  259. }
  260. return xRenderQueryVersion != nullptr;
  261. }
  262. static bool hasCompositingWindowManager (::Display* display) noexcept
  263. {
  264. return display != nullptr
  265. && XGetSelectionOwner (display, Atoms::getCreating (display, "_NET_WM_CM_S0")) != 0;
  266. }
  267. static XRenderPictFormat* findPictureFormat (::Display* display)
  268. {
  269. ScopedXLock xlock (display);
  270. XRenderPictFormat* pictFormat = nullptr;
  271. if (isAvailable (display))
  272. {
  273. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  274. if (pictFormat == nullptr)
  275. {
  276. XRenderPictFormat desiredFormat;
  277. desiredFormat.type = PictTypeDirect;
  278. desiredFormat.depth = 32;
  279. desiredFormat.direct.alphaMask = 0xff;
  280. desiredFormat.direct.redMask = 0xff;
  281. desiredFormat.direct.greenMask = 0xff;
  282. desiredFormat.direct.blueMask = 0xff;
  283. desiredFormat.direct.alpha = 24;
  284. desiredFormat.direct.red = 16;
  285. desiredFormat.direct.green = 8;
  286. desiredFormat.direct.blue = 0;
  287. pictFormat = xRenderFindFormat (display,
  288. PictFormatType | PictFormatDepth
  289. | PictFormatRedMask | PictFormatRed
  290. | PictFormatGreenMask | PictFormatGreen
  291. | PictFormatBlueMask | PictFormatBlue
  292. | PictFormatAlphaMask | PictFormatAlpha,
  293. &desiredFormat,
  294. 0);
  295. }
  296. }
  297. return pictFormat;
  298. }
  299. }
  300. #endif
  301. //================================ X11 - Visuals ===============================
  302. namespace Visuals
  303. {
  304. static Visual* findVisualWithDepth (::Display* display, int desiredDepth) noexcept
  305. {
  306. ScopedXLock xlock (display);
  307. Visual* visual = nullptr;
  308. int numVisuals = 0;
  309. long desiredMask = VisualNoMask;
  310. XVisualInfo desiredVisual;
  311. desiredVisual.screen = DefaultScreen (display);
  312. desiredVisual.depth = desiredDepth;
  313. desiredMask = VisualScreenMask | VisualDepthMask;
  314. if (desiredDepth == 32)
  315. {
  316. desiredVisual.c_class = TrueColor;
  317. desiredVisual.red_mask = 0x00FF0000;
  318. desiredVisual.green_mask = 0x0000FF00;
  319. desiredVisual.blue_mask = 0x000000FF;
  320. desiredVisual.bits_per_rgb = 8;
  321. desiredMask |= VisualClassMask;
  322. desiredMask |= VisualRedMaskMask;
  323. desiredMask |= VisualGreenMaskMask;
  324. desiredMask |= VisualBlueMaskMask;
  325. desiredMask |= VisualBitsPerRGBMask;
  326. }
  327. if (auto* xvinfos = XGetVisualInfo (display, desiredMask, &desiredVisual, &numVisuals))
  328. {
  329. for (int i = 0; i < numVisuals; i++)
  330. {
  331. if (xvinfos[i].depth == desiredDepth)
  332. {
  333. visual = xvinfos[i].visual;
  334. break;
  335. }
  336. }
  337. XFree (xvinfos);
  338. }
  339. return visual;
  340. }
  341. static Visual* findVisualFormat (::Display* display, int desiredDepth, int& matchedDepth) noexcept
  342. {
  343. Visual* visual = nullptr;
  344. if (desiredDepth == 32)
  345. {
  346. #if JUCE_USE_XSHM
  347. if (XSHMHelpers::isShmAvailable (display))
  348. {
  349. #if JUCE_USE_XRENDER
  350. if (XRender::isAvailable (display))
  351. {
  352. if (auto pictFormat = XRender::findPictureFormat (display))
  353. {
  354. int numVisuals = 0;
  355. XVisualInfo desiredVisual;
  356. desiredVisual.screen = DefaultScreen (display);
  357. desiredVisual.depth = 32;
  358. desiredVisual.bits_per_rgb = 8;
  359. if (auto xvinfos = XGetVisualInfo (display,
  360. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  361. &desiredVisual, &numVisuals))
  362. {
  363. for (int i = 0; i < numVisuals; ++i)
  364. {
  365. auto pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  366. if (pictVisualFormat != nullptr
  367. && pictVisualFormat->type == PictTypeDirect
  368. && pictVisualFormat->direct.alphaMask)
  369. {
  370. visual = xvinfos[i].visual;
  371. matchedDepth = 32;
  372. break;
  373. }
  374. }
  375. XFree (xvinfos);
  376. }
  377. }
  378. }
  379. #endif
  380. if (visual == nullptr)
  381. {
  382. visual = findVisualWithDepth (display, 32);
  383. if (visual != nullptr)
  384. matchedDepth = 32;
  385. }
  386. }
  387. #endif
  388. }
  389. if (visual == nullptr && desiredDepth >= 24)
  390. {
  391. visual = findVisualWithDepth (display, 24);
  392. if (visual != nullptr)
  393. matchedDepth = 24;
  394. }
  395. if (visual == nullptr && desiredDepth >= 16)
  396. {
  397. visual = findVisualWithDepth (display, 16);
  398. if (visual != nullptr)
  399. matchedDepth = 16;
  400. }
  401. return visual;
  402. }
  403. }
  404. //================================= X11 - Bitmap ===============================
  405. class XBitmapImage : public ImagePixelData
  406. {
  407. public:
  408. XBitmapImage (::Display* d, Image::PixelFormat format, int w, int h,
  409. bool clearImage, unsigned int imageDepth_, Visual* visual)
  410. : ImagePixelData (format, w, h),
  411. imageDepth (imageDepth_),
  412. display (d)
  413. {
  414. jassert (format == Image::RGB || format == Image::ARGB);
  415. pixelStride = (format == Image::RGB) ? 3 : 4;
  416. lineStride = ((w * pixelStride + 3) & ~3);
  417. ScopedXLock xlock (display);
  418. #if JUCE_USE_XSHM
  419. usingXShm = false;
  420. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable (display))
  421. {
  422. zerostruct (segmentInfo);
  423. segmentInfo.shmid = -1;
  424. segmentInfo.shmaddr = (char *) -1;
  425. segmentInfo.readOnly = False;
  426. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, nullptr,
  427. &segmentInfo, (unsigned int) w, (unsigned int) h);
  428. if (xImage != nullptr)
  429. {
  430. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  431. (size_t) (xImage->bytes_per_line * xImage->height),
  432. IPC_CREAT | 0777)) >= 0)
  433. {
  434. if (segmentInfo.shmid != -1)
  435. {
  436. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, nullptr, 0);
  437. if (segmentInfo.shmaddr != (void*) -1)
  438. {
  439. segmentInfo.readOnly = False;
  440. xImage->data = segmentInfo.shmaddr;
  441. imageData = (uint8*) segmentInfo.shmaddr;
  442. if (XShmAttach (display, &segmentInfo) != 0)
  443. usingXShm = true;
  444. else
  445. jassertfalse;
  446. }
  447. else
  448. {
  449. shmctl (segmentInfo.shmid, IPC_RMID, nullptr);
  450. }
  451. }
  452. }
  453. }
  454. }
  455. if (! isUsingXShm())
  456. #endif
  457. {
  458. imageDataAllocated.allocate ((size_t) (lineStride * h), format == Image::ARGB && clearImage);
  459. imageData = imageDataAllocated;
  460. xImage = (XImage*) ::calloc (1, sizeof (XImage));
  461. xImage->width = w;
  462. xImage->height = h;
  463. xImage->xoffset = 0;
  464. xImage->format = ZPixmap;
  465. xImage->data = (char*) imageData;
  466. xImage->byte_order = ImageByteOrder (display);
  467. xImage->bitmap_unit = BitmapUnit (display);
  468. xImage->bitmap_bit_order = BitmapBitOrder (display);
  469. xImage->bitmap_pad = 32;
  470. xImage->depth = pixelStride * 8;
  471. xImage->bytes_per_line = lineStride;
  472. xImage->bits_per_pixel = pixelStride * 8;
  473. xImage->red_mask = 0x00FF0000;
  474. xImage->green_mask = 0x0000FF00;
  475. xImage->blue_mask = 0x000000FF;
  476. if (imageDepth == 16)
  477. {
  478. const int pixStride = 2;
  479. const int stride = ((w * pixStride + 3) & ~3);
  480. imageData16Bit.malloc (stride * h);
  481. xImage->data = imageData16Bit;
  482. xImage->bitmap_pad = 16;
  483. xImage->depth = pixStride * 8;
  484. xImage->bytes_per_line = stride;
  485. xImage->bits_per_pixel = pixStride * 8;
  486. xImage->red_mask = visual->red_mask;
  487. xImage->green_mask = visual->green_mask;
  488. xImage->blue_mask = visual->blue_mask;
  489. }
  490. if (! XInitImage (xImage))
  491. jassertfalse;
  492. }
  493. }
  494. ~XBitmapImage() override
  495. {
  496. ScopedXLock xlock (display);
  497. if (gc != None)
  498. XFreeGC (display, gc);
  499. #if JUCE_USE_XSHM
  500. if (isUsingXShm())
  501. {
  502. XShmDetach (display, &segmentInfo);
  503. XFlush (display);
  504. XDestroyImage (xImage);
  505. shmdt (segmentInfo.shmaddr);
  506. shmctl (segmentInfo.shmid, IPC_RMID, nullptr);
  507. }
  508. else
  509. #endif
  510. {
  511. xImage->data = nullptr;
  512. XDestroyImage (xImage);
  513. }
  514. }
  515. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
  516. {
  517. sendDataChangeMessage();
  518. return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (this));
  519. }
  520. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y,
  521. Image::BitmapData::ReadWriteMode mode) override
  522. {
  523. bitmap.data = imageData + x * pixelStride + y * lineStride;
  524. bitmap.pixelFormat = pixelFormat;
  525. bitmap.lineStride = lineStride;
  526. bitmap.pixelStride = pixelStride;
  527. if (mode != Image::BitmapData::readOnly)
  528. sendDataChangeMessage();
  529. }
  530. ImagePixelData::Ptr clone() override
  531. {
  532. jassertfalse;
  533. return nullptr;
  534. }
  535. std::unique_ptr<ImageType> createType() const override { return std::make_unique<NativeImageType>(); }
  536. void blitToWindow (Window window, int dx, int dy,
  537. unsigned int dw, unsigned int dh, int sx, int sy)
  538. {
  539. ScopedXLock xlock (display);
  540. if (gc == None)
  541. {
  542. XGCValues gcvalues;
  543. gcvalues.foreground = None;
  544. gcvalues.background = None;
  545. gcvalues.function = GXcopy;
  546. gcvalues.plane_mask = AllPlanes;
  547. gcvalues.clip_mask = None;
  548. gcvalues.graphics_exposures = False;
  549. gc = XCreateGC (display, window,
  550. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  551. &gcvalues);
  552. }
  553. if (imageDepth == 16)
  554. {
  555. auto rMask = (uint32) xImage->red_mask;
  556. auto gMask = (uint32) xImage->green_mask;
  557. auto bMask = (uint32) xImage->blue_mask;
  558. auto rShiftL = (uint32) jmax (0, getShiftNeeded (rMask));
  559. auto rShiftR = (uint32) jmax (0, -getShiftNeeded (rMask));
  560. auto gShiftL = (uint32) jmax (0, getShiftNeeded (gMask));
  561. auto gShiftR = (uint32) jmax (0, -getShiftNeeded (gMask));
  562. auto bShiftL = (uint32) jmax (0, getShiftNeeded (bMask));
  563. auto bShiftR = (uint32) jmax (0, -getShiftNeeded (bMask));
  564. const Image::BitmapData srcData (Image (this), Image::BitmapData::readOnly);
  565. for (int y = sy; y < sy + (int)dh; ++y)
  566. {
  567. const uint8* p = srcData.getPixelPointer (sx, y);
  568. for (int x = sx; x < sx + (int)dw; ++x)
  569. {
  570. auto* pixel = (const PixelRGB*) p;
  571. p += srcData.pixelStride;
  572. XPutPixel (xImage, x, y,
  573. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  574. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  575. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  576. }
  577. }
  578. }
  579. // blit results to screen.
  580. #if JUCE_USE_XSHM
  581. if (isUsingXShm())
  582. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  583. else
  584. #endif
  585. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  586. }
  587. #if JUCE_USE_XSHM
  588. bool isUsingXShm() const noexcept { return usingXShm; }
  589. #endif
  590. private:
  591. //==============================================================================
  592. XImage* xImage = {};
  593. const unsigned int imageDepth;
  594. HeapBlock<uint8> imageDataAllocated;
  595. HeapBlock<char> imageData16Bit;
  596. int pixelStride, lineStride;
  597. uint8* imageData = {};
  598. GC gc = None;
  599. ::Display* display = {};
  600. #if JUCE_USE_XSHM
  601. XShmSegmentInfo segmentInfo;
  602. bool usingXShm;
  603. #endif
  604. static int getShiftNeeded (const uint32 mask) noexcept
  605. {
  606. for (int i = 32; --i >= 0;)
  607. if (((mask >> i) & 1) != 0)
  608. return i - 7;
  609. jassertfalse;
  610. return 0;
  611. }
  612. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage)
  613. };
  614. //==============================================================================
  615. #if JUCE_USE_XINERAMA
  616. static Array<XineramaScreenInfo> XineramaQueryDisplays (::Display* display)
  617. {
  618. typedef Bool (*tXineramaIsActive) (::Display*);
  619. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (::Display*, int*);
  620. int major_opcode, first_event, first_error;
  621. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  622. {
  623. static void* libXinerama = nullptr;
  624. static tXineramaIsActive isActiveFuncPtr = nullptr;
  625. static tXineramaQueryScreens xineramaQueryScreens = nullptr;
  626. if (libXinerama == nullptr)
  627. {
  628. libXinerama = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  629. if (libXinerama == nullptr)
  630. libXinerama = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  631. if (libXinerama != nullptr)
  632. {
  633. isActiveFuncPtr = (tXineramaIsActive) dlsym (libXinerama, "XineramaIsActive");
  634. xineramaQueryScreens = (tXineramaQueryScreens) dlsym (libXinerama, "XineramaQueryScreens");
  635. }
  636. }
  637. if (isActiveFuncPtr != nullptr && xineramaQueryScreens != nullptr && isActiveFuncPtr (display) != 0)
  638. {
  639. int numScreens;
  640. if (auto* xinfo = xineramaQueryScreens (display, &numScreens))
  641. {
  642. Array<XineramaScreenInfo> infos (xinfo, numScreens);
  643. XFree (xinfo);
  644. return infos;
  645. }
  646. }
  647. }
  648. return {};
  649. }
  650. #endif
  651. //==============================================================================
  652. #if JUCE_USE_XRANDR
  653. class XRandrWrapper
  654. {
  655. private:
  656. XRandrWrapper()
  657. {
  658. if (libXrandr == nullptr)
  659. {
  660. libXrandr = dlopen ("libXrandr.so", RTLD_GLOBAL | RTLD_NOW);
  661. if (libXrandr == nullptr)
  662. libXrandr = dlopen ("libXrandr.so.2", RTLD_GLOBAL | RTLD_NOW);
  663. if (libXrandr != nullptr)
  664. {
  665. getScreenResourcesPtr = (tXRRGetScreenResources) dlsym (libXrandr, "XRRGetScreenResources");
  666. freeScreenResourcesPtr = (tXRRFreeScreenResources) dlsym (libXrandr, "XRRFreeScreenResources");
  667. getOutputInfoPtr = (tXRRGetOutputInfo) dlsym (libXrandr, "XRRGetOutputInfo");
  668. freeOutputInfoPtr = (tXRRFreeOutputInfo) dlsym (libXrandr, "XRRFreeOutputInfo");
  669. getCrtcInfoPtr = (tXRRGetCrtcInfo) dlsym (libXrandr, "XRRGetCrtcInfo");
  670. freeCrtcInfoPtr = (tXRRFreeCrtcInfo) dlsym (libXrandr, "XRRFreeCrtcInfo");
  671. getOutputPrimaryPtr = (tXRRGetOutputPrimary) dlsym (libXrandr, "XRRGetOutputPrimary");
  672. }
  673. }
  674. }
  675. public:
  676. //==============================================================================
  677. static XRandrWrapper& getInstance()
  678. {
  679. static XRandrWrapper xrandr;
  680. return xrandr;
  681. }
  682. //==============================================================================
  683. XRRScreenResources* getScreenResources (::Display* display, ::Window window)
  684. {
  685. if (getScreenResourcesPtr != nullptr)
  686. return getScreenResourcesPtr (display, window);
  687. return nullptr;
  688. }
  689. XRROutputInfo* getOutputInfo (::Display* display, XRRScreenResources* resources, RROutput output)
  690. {
  691. if (getOutputInfoPtr != nullptr)
  692. return getOutputInfoPtr (display, resources, output);
  693. return nullptr;
  694. }
  695. XRRCrtcInfo* getCrtcInfo (::Display* display, XRRScreenResources* resources, RRCrtc crtc)
  696. {
  697. if (getCrtcInfoPtr != nullptr)
  698. return getCrtcInfoPtr (display, resources, crtc);
  699. return nullptr;
  700. }
  701. RROutput getOutputPrimary (::Display* display, ::Window window)
  702. {
  703. if (getOutputPrimaryPtr != nullptr)
  704. return getOutputPrimaryPtr (display, window);
  705. return 0;
  706. }
  707. //==============================================================================
  708. void freeScreenResources (XRRScreenResources* ptr)
  709. {
  710. if (freeScreenResourcesPtr != nullptr)
  711. freeScreenResourcesPtr (ptr);
  712. }
  713. void freeOutputInfo (XRROutputInfo* ptr)
  714. {
  715. if (freeOutputInfoPtr != nullptr)
  716. freeOutputInfoPtr (ptr);
  717. }
  718. void freeCrtcInfo (XRRCrtcInfo* ptr)
  719. {
  720. if (freeCrtcInfoPtr != nullptr)
  721. freeCrtcInfoPtr (ptr);
  722. }
  723. private:
  724. using tXRRGetScreenResources = XRRScreenResources* (*) (::Display*, ::Window);
  725. using tXRRFreeScreenResources = void (*) (XRRScreenResources*);
  726. using tXRRGetOutputInfo = XRROutputInfo* (*) (::Display*, XRRScreenResources*, RROutput);
  727. using tXRRFreeOutputInfo = void (*) (XRROutputInfo*);
  728. using tXRRGetCrtcInfo = XRRCrtcInfo* (*) (::Display*, XRRScreenResources*, RRCrtc);
  729. using tXRRFreeCrtcInfo = void (*) (XRRCrtcInfo*);
  730. using tXRRGetOutputPrimary = RROutput (*) (::Display*, ::Window);
  731. void* libXrandr = nullptr;
  732. tXRRGetScreenResources getScreenResourcesPtr = nullptr;
  733. tXRRFreeScreenResources freeScreenResourcesPtr = nullptr;
  734. tXRRGetOutputInfo getOutputInfoPtr = nullptr;
  735. tXRRFreeOutputInfo freeOutputInfoPtr = nullptr;
  736. tXRRGetCrtcInfo getCrtcInfoPtr = nullptr;
  737. tXRRFreeCrtcInfo freeCrtcInfoPtr = nullptr;
  738. tXRRGetOutputPrimary getOutputPrimaryPtr = nullptr;
  739. };
  740. #endif
  741. static double getDisplayDPI (::Display* display, int index)
  742. {
  743. auto widthMM = DisplayWidthMM (display, index);
  744. auto heightMM = DisplayHeightMM (display, index);
  745. if (widthMM > 0 && heightMM > 0)
  746. return (((DisplayWidth (display, index) * 25.4) / widthMM) + ((DisplayHeight (display, index) * 25.4) / heightMM)) / 2.0;
  747. return 96.0;
  748. }
  749. static double getScaleForDisplay (const String& name, double dpi)
  750. {
  751. if (name.isNotEmpty())
  752. {
  753. // Ubuntu and derived distributions now save a per-display scale factor as a configuration
  754. // variable. This can be changed in the Monitor system settings panel.
  755. ChildProcess dconf;
  756. if (File ("/usr/bin/dconf").existsAsFile()
  757. && dconf.start ("/usr/bin/dconf read /com/ubuntu/user-interface/scale-factor", ChildProcess::wantStdOut))
  758. {
  759. if (dconf.waitForProcessToFinish (200))
  760. {
  761. auto jsonOutput = dconf.readAllProcessOutput().replaceCharacter ('\'', '"');
  762. if (dconf.getExitCode() == 0 && jsonOutput.isNotEmpty())
  763. {
  764. auto jsonVar = JSON::parse (jsonOutput);
  765. if (auto* object = jsonVar.getDynamicObject())
  766. {
  767. auto scaleFactorVar = object->getProperty (name);
  768. if (! scaleFactorVar.isVoid())
  769. {
  770. auto scaleFactor = ((double) scaleFactorVar) / 8.0;
  771. if (scaleFactor > 0.0)
  772. return scaleFactor;
  773. }
  774. }
  775. }
  776. }
  777. }
  778. }
  779. {
  780. // Other gnome based distros now use gsettings for a global scale factor
  781. ChildProcess gsettings;
  782. if (File ("/usr/bin/gsettings").existsAsFile()
  783. && gsettings.start ("/usr/bin/gsettings get org.gnome.desktop.interface scaling-factor", ChildProcess::wantStdOut))
  784. {
  785. if (gsettings.waitForProcessToFinish (200))
  786. {
  787. auto gsettingsOutput = StringArray::fromTokens (gsettings.readAllProcessOutput(), true);
  788. if (gsettingsOutput.size() >= 2 && gsettingsOutput[1].length() > 0)
  789. {
  790. auto scaleFactor = gsettingsOutput[1].getDoubleValue();
  791. if (scaleFactor > 0.0)
  792. return scaleFactor;
  793. return 1.0;
  794. }
  795. }
  796. }
  797. }
  798. // If no scale factor is set by GNOME or Ubuntu then calculate from monitor dpi
  799. // We use the same approach as chromium which simply divides the dpi by 96
  800. // and then rounds the result
  801. return round (dpi / 96.0);
  802. }
  803. //=============================== X11 - Pixmap =================================
  804. namespace PixmapHelpers
  805. {
  806. Pixmap createColourPixmapFromImage (::Display* display, const Image& image)
  807. {
  808. ScopedXLock xlock (display);
  809. auto width = (unsigned int) image.getWidth();
  810. auto height = (unsigned int) image.getHeight();
  811. HeapBlock<uint32> colour (width * height);
  812. int index = 0;
  813. for (int y = 0; y < (int) height; ++y)
  814. for (int x = 0; x < (int) width; ++x)
  815. colour[index++] = image.getPixelAt (x, y).getARGB();
  816. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  817. 0, reinterpret_cast<char*> (colour.getData()),
  818. width, height, 32, 0);
  819. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  820. width, height, 24);
  821. GC gc = XCreateGC (display, pixmap, 0, nullptr);
  822. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  823. XFreeGC (display, gc);
  824. return pixmap;
  825. }
  826. Pixmap createMaskPixmapFromImage (::Display* display, const Image& image)
  827. {
  828. ScopedXLock xlock (display);
  829. auto width = (unsigned int) image.getWidth();
  830. auto height = (unsigned int) image.getHeight();
  831. auto stride = (width + 7) >> 3;
  832. HeapBlock<char> mask;
  833. mask.calloc (stride * height);
  834. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  835. for (unsigned int y = 0; y < height; ++y)
  836. {
  837. for (unsigned int x = 0; x < width; ++x)
  838. {
  839. auto bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  840. const unsigned int offset = y * stride + (x >> 3);
  841. if (image.getPixelAt ((int) x, (int) y).getAlpha() >= 128)
  842. mask[offset] |= bit;
  843. }
  844. }
  845. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  846. mask.getData(), width, height, 1, 0, 1);
  847. }
  848. }
  849. static void* createDraggingHandCursor()
  850. {
  851. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  852. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0, 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  853. 132,117,151,116,132,146,248,60,209,138,98,22,203,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 };
  854. size_t dragHandDataSize = 99;
  855. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), { 8, 7 }).create();
  856. }
  857. //==============================================================================
  858. static int numAlwaysOnTopPeers = 0;
  859. bool juce_areThereAnyAlwaysOnTopWindows()
  860. {
  861. return numAlwaysOnTopPeers > 0;
  862. }
  863. //==============================================================================
  864. class LinuxComponentPeer : public ComponentPeer
  865. {
  866. public:
  867. LinuxComponentPeer (Component& comp, int windowStyleFlags, Window parentToAddTo)
  868. : ComponentPeer (comp, windowStyleFlags),
  869. isAlwaysOnTop (comp.isAlwaysOnTop())
  870. {
  871. // it's dangerous to create a window on a thread other than the message thread..
  872. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  873. display = XWindowSystem::getInstance()->displayRef();
  874. atoms.reset (new Atoms (display));
  875. dragState.reset (new DragState (display));
  876. repainter.reset (new LinuxRepaintManager (*this, display));
  877. if (isAlwaysOnTop)
  878. ++numAlwaysOnTopPeers;
  879. createWindow (parentToAddTo);
  880. setTitle (component.getName());
  881. getNativeRealtimeModifiers = []
  882. {
  883. ScopedXDisplay xDisplay;
  884. if (auto d = xDisplay.display)
  885. {
  886. Window root, child;
  887. int x, y, winx, winy;
  888. unsigned int mask;
  889. int mouseMods = 0;
  890. ScopedXLock xlock (d);
  891. if (XQueryPointer (d, RootWindow (d, DefaultScreen (d)),
  892. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  893. {
  894. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  895. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  896. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  897. }
  898. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  899. }
  900. return ModifierKeys::currentModifiers;
  901. };
  902. }
  903. ~LinuxComponentPeer() override
  904. {
  905. // it's dangerous to delete a window on a thread other than the message thread..
  906. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  907. #if JUCE_X11_SUPPORTS_XEMBED
  908. juce_handleXEmbedEvent (this, nullptr);
  909. #endif
  910. deleteIconPixmaps();
  911. destroyWindow();
  912. windowH = 0;
  913. if (isAlwaysOnTop)
  914. --numAlwaysOnTopPeers;
  915. // delete before display
  916. repainter = nullptr;
  917. display = XWindowSystem::getInstance()->displayUnref();
  918. }
  919. //==============================================================================
  920. void* getNativeHandle() const override
  921. {
  922. return (void*) windowH;
  923. }
  924. static LinuxComponentPeer* getPeerFor (Window windowHandle) noexcept
  925. {
  926. XPointer peer = nullptr;
  927. if (display != nullptr)
  928. {
  929. ScopedXLock xlock (display);
  930. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  931. if (peer != nullptr && ! ComponentPeer::isValidPeer (reinterpret_cast<LinuxComponentPeer*> (peer)))
  932. peer = nullptr;
  933. }
  934. return reinterpret_cast<LinuxComponentPeer*> (peer);
  935. }
  936. void setVisible (bool shouldBeVisible) override
  937. {
  938. ScopedXLock xlock (display);
  939. if (shouldBeVisible)
  940. XMapWindow (display, windowH);
  941. else
  942. XUnmapWindow (display, windowH);
  943. }
  944. void setTitle (const String& title) override
  945. {
  946. XTextProperty nameProperty;
  947. char* strings[] = { const_cast<char*> (title.toRawUTF8()) };
  948. ScopedXLock xlock (display);
  949. if (XStringListToTextProperty (strings, 1, &nameProperty))
  950. {
  951. XSetWMName (display, windowH, &nameProperty);
  952. XSetWMIconName (display, windowH, &nameProperty);
  953. XFree (nameProperty.value);
  954. }
  955. }
  956. void updateScaleFactorFromNewBounds (const Rectangle<int>& newBounds, bool isPhysical)
  957. {
  958. Point<int> translation = (parentWindow != 0 ? getScreenPosition (isPhysical) : Point<int>());
  959. auto newScaleFactor = Desktop::getInstance().getDisplays().findDisplayForRect (newBounds.translated (translation.x, translation.y), isPhysical).scale
  960. / Desktop::getInstance().getGlobalScaleFactor();
  961. if (! approximatelyEqual (newScaleFactor, currentScaleFactor))
  962. {
  963. currentScaleFactor = newScaleFactor;
  964. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (currentScaleFactor); });
  965. }
  966. }
  967. void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
  968. {
  969. if (fullScreen && ! isNowFullScreen)
  970. {
  971. // When transitioning back from fullscreen, we might need to remove
  972. // the FULLSCREEN window property
  973. Atom fs = Atoms::getIfExists (display, "_NET_WM_STATE_FULLSCREEN");
  974. if (fs != None)
  975. {
  976. Window root = RootWindow (display, DefaultScreen (display));
  977. XClientMessageEvent clientMsg;
  978. clientMsg.display = display;
  979. clientMsg.window = windowH;
  980. clientMsg.type = ClientMessage;
  981. clientMsg.format = 32;
  982. clientMsg.message_type = atoms->windowState;
  983. clientMsg.data.l[0] = 0; // Remove
  984. clientMsg.data.l[1] = (long) fs;
  985. clientMsg.data.l[2] = 0;
  986. clientMsg.data.l[3] = 1; // Normal Source
  987. ScopedXLock xlock (display);
  988. XSendEvent (display, root, false,
  989. SubstructureRedirectMask | SubstructureNotifyMask,
  990. (XEvent*) &clientMsg);
  991. }
  992. }
  993. fullScreen = isNowFullScreen;
  994. if (windowH != 0)
  995. {
  996. bounds = newBounds.withSize (jmax (1, newBounds.getWidth()),
  997. jmax (1, newBounds.getHeight()));
  998. updateScaleFactorFromNewBounds (bounds, false);
  999. auto physicalBounds = (parentWindow == 0 ? Desktop::getInstance().getDisplays().logicalToPhysical (bounds)
  1000. : bounds * currentScaleFactor);
  1001. WeakReference<Component> deletionChecker (&component);
  1002. ScopedXLock xlock (display);
  1003. auto* hints = XAllocSizeHints();
  1004. hints->flags = USSize | USPosition;
  1005. hints->x = physicalBounds.getX();
  1006. hints->y = physicalBounds.getY();
  1007. hints->width = physicalBounds.getWidth();
  1008. hints->height = physicalBounds.getHeight();
  1009. if ((getStyleFlags() & windowIsResizable) == 0)
  1010. {
  1011. hints->min_width = hints->max_width = hints->width;
  1012. hints->min_height = hints->max_height = hints->height;
  1013. hints->flags |= PMinSize | PMaxSize;
  1014. }
  1015. XSetWMNormalHints (display, windowH, hints);
  1016. XFree (hints);
  1017. XMoveResizeWindow (display, windowH,
  1018. physicalBounds.getX() - windowBorder.getLeft(),
  1019. physicalBounds.getY() - windowBorder.getTop(),
  1020. (unsigned int) physicalBounds.getWidth(),
  1021. (unsigned int) physicalBounds.getHeight());
  1022. if (deletionChecker != nullptr)
  1023. {
  1024. updateBorderSize();
  1025. handleMovedOrResized();
  1026. }
  1027. }
  1028. }
  1029. Point<int> getScreenPosition (bool physical) const
  1030. {
  1031. auto screenBounds = (parentWindow == 0 ? bounds
  1032. : bounds.translated (parentScreenPosition.x, parentScreenPosition.y));
  1033. if (physical)
  1034. return Desktop::getInstance().getDisplays().logicalToPhysical (screenBounds.getTopLeft());
  1035. return screenBounds.getTopLeft();
  1036. }
  1037. Rectangle<int> getBounds() const override { return bounds; }
  1038. using ComponentPeer::localToGlobal;
  1039. Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getScreenPosition (false).toFloat(); }
  1040. using ComponentPeer::globalToLocal;
  1041. Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getScreenPosition (false).toFloat(); }
  1042. void setAlpha (float /* newAlpha */) override
  1043. {
  1044. //xxx todo!
  1045. }
  1046. StringArray getAvailableRenderingEngines() override
  1047. {
  1048. return StringArray ("Software Renderer");
  1049. }
  1050. void setMinimised (bool shouldBeMinimised) override
  1051. {
  1052. if (shouldBeMinimised)
  1053. {
  1054. Window root = RootWindow (display, DefaultScreen (display));
  1055. XClientMessageEvent clientMsg;
  1056. clientMsg.display = display;
  1057. clientMsg.window = windowH;
  1058. clientMsg.type = ClientMessage;
  1059. clientMsg.format = 32;
  1060. clientMsg.message_type = atoms->changeState;
  1061. clientMsg.data.l[0] = IconicState;
  1062. ScopedXLock xlock (display);
  1063. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  1064. }
  1065. else
  1066. {
  1067. setVisible (true);
  1068. }
  1069. }
  1070. bool isMinimised() const override
  1071. {
  1072. ScopedXLock xlock (display);
  1073. GetXProperty prop (display, windowH, atoms->state, 0, 64, false, atoms->state);
  1074. if (prop.success && prop.actualType == atoms->state
  1075. && prop.actualFormat == 32 && prop.numItems > 0)
  1076. {
  1077. unsigned long state;
  1078. memcpy (&state, prop.data, sizeof (unsigned long));
  1079. return state == IconicState;
  1080. }
  1081. return false;
  1082. }
  1083. void setFullScreen (bool shouldBeFullScreen) override
  1084. {
  1085. auto r = lastNonFullscreenBounds; // (get a copy of this before de-minimising)
  1086. setMinimised (false);
  1087. if (fullScreen != shouldBeFullScreen)
  1088. {
  1089. if (shouldBeFullScreen)
  1090. r = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  1091. if (! r.isEmpty())
  1092. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  1093. component.repaint();
  1094. }
  1095. }
  1096. bool isFullScreen() const override
  1097. {
  1098. return fullScreen;
  1099. }
  1100. bool isChildWindowOf (Window possibleParent) const
  1101. {
  1102. Window* windowList = nullptr;
  1103. uint32 windowListSize = 0;
  1104. Window parent, root;
  1105. ScopedXLock xlock (display);
  1106. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  1107. {
  1108. if (windowList != nullptr)
  1109. XFree (windowList);
  1110. return parent == possibleParent;
  1111. }
  1112. return false;
  1113. }
  1114. bool isParentWindowOf (Window possibleChild) const
  1115. {
  1116. if (windowH != 0 && possibleChild != 0)
  1117. {
  1118. if (possibleChild == windowH)
  1119. return true;
  1120. Window* windowList = nullptr;
  1121. uint32 windowListSize = 0;
  1122. Window parent, root;
  1123. ScopedXLock xlock (display);
  1124. if (XQueryTree (display, possibleChild, &root, &parent, &windowList, &windowListSize) != 0)
  1125. {
  1126. if (windowList != nullptr)
  1127. XFree (windowList);
  1128. if (parent == root)
  1129. return false;
  1130. return isParentWindowOf (parent);
  1131. }
  1132. }
  1133. return false;
  1134. }
  1135. bool isFrontWindow() const
  1136. {
  1137. Window* windowList = nullptr;
  1138. uint32 windowListSize = 0;
  1139. bool result = false;
  1140. ScopedXLock xlock (display);
  1141. Window parent, root = RootWindow (display, DefaultScreen (display));
  1142. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  1143. {
  1144. for (int i = (int) windowListSize; --i >= 0;)
  1145. {
  1146. if (auto* peer = LinuxComponentPeer::getPeerFor (windowList[i]))
  1147. {
  1148. result = (peer == this);
  1149. break;
  1150. }
  1151. }
  1152. }
  1153. if (windowList != nullptr)
  1154. XFree (windowList);
  1155. return result;
  1156. }
  1157. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  1158. {
  1159. if (! bounds.withZeroOrigin().contains (localPos))
  1160. return false;
  1161. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1162. {
  1163. auto* c = Desktop::getInstance().getComponent (i);
  1164. if (c == &component)
  1165. break;
  1166. if (! c->isVisible())
  1167. continue;
  1168. if (auto* peer = c->getPeer())
  1169. if (peer->contains (localPos + bounds.getPosition() - peer->getBounds().getPosition(), true))
  1170. return false;
  1171. }
  1172. if (trueIfInAChildWindow)
  1173. return true;
  1174. ::Window root, child;
  1175. int wx, wy;
  1176. unsigned int ww, wh, bw, bitDepth;
  1177. ScopedXLock xlock (display);
  1178. localPos *= currentScaleFactor;
  1179. return XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth)
  1180. && XTranslateCoordinates (display, windowH, windowH, localPos.getX(), localPos.getY(), &wx, &wy, &child)
  1181. && child == None;
  1182. }
  1183. BorderSize<int> getFrameSize() const override
  1184. {
  1185. return {};
  1186. }
  1187. bool setAlwaysOnTop (bool /* alwaysOnTop */) override
  1188. {
  1189. return false;
  1190. }
  1191. void toFront (bool makeActive) override
  1192. {
  1193. if (makeActive)
  1194. {
  1195. setVisible (true);
  1196. grabFocus();
  1197. }
  1198. {
  1199. ScopedXLock xlock (display);
  1200. XEvent ev;
  1201. ev.xclient.type = ClientMessage;
  1202. ev.xclient.serial = 0;
  1203. ev.xclient.send_event = True;
  1204. ev.xclient.message_type = atoms->activeWin;
  1205. ev.xclient.window = windowH;
  1206. ev.xclient.format = 32;
  1207. ev.xclient.data.l[0] = 2;
  1208. ev.xclient.data.l[1] = getUserTime();
  1209. ev.xclient.data.l[2] = 0;
  1210. ev.xclient.data.l[3] = 0;
  1211. ev.xclient.data.l[4] = 0;
  1212. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  1213. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  1214. XSync (display, False);
  1215. }
  1216. handleBroughtToFront();
  1217. }
  1218. void toBehind (ComponentPeer* other) override
  1219. {
  1220. if (auto* otherPeer = dynamic_cast<LinuxComponentPeer*> (other))
  1221. {
  1222. if (otherPeer->styleFlags & windowIsTemporary)
  1223. return;
  1224. setMinimised (false);
  1225. Window newStack[] = { otherPeer->windowH, windowH };
  1226. ScopedXLock xlock (display);
  1227. XRestackWindows (display, newStack, 2);
  1228. }
  1229. else
  1230. jassertfalse; // wrong type of window?
  1231. }
  1232. bool isFocused() const override
  1233. {
  1234. int revert = 0;
  1235. Window focusedWindow = 0;
  1236. ScopedXLock xlock (display);
  1237. XGetInputFocus (display, &focusedWindow, &revert);
  1238. if (focusedWindow == PointerRoot)
  1239. return false;
  1240. return isParentWindowOf (focusedWindow);
  1241. }
  1242. Window getFocusWindow()
  1243. {
  1244. #if JUCE_X11_SUPPORTS_XEMBED
  1245. if (Window w = (Window) juce_getCurrentFocusWindow (this))
  1246. return w;
  1247. #endif
  1248. return windowH;
  1249. }
  1250. void grabFocus() override
  1251. {
  1252. XWindowAttributes atts;
  1253. ScopedXLock xlock (display);
  1254. if (windowH != 0
  1255. && XGetWindowAttributes (display, windowH, &atts)
  1256. && atts.map_state == IsViewable
  1257. && ! isFocused())
  1258. {
  1259. XSetInputFocus (display, getFocusWindow(), RevertToParent, (::Time) getUserTime());
  1260. isActiveApplication = true;
  1261. }
  1262. }
  1263. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1264. void repaint (const Rectangle<int>& area) override
  1265. {
  1266. repainter->repaint (area.getIntersection (bounds.withZeroOrigin()));
  1267. }
  1268. void performAnyPendingRepaintsNow() override
  1269. {
  1270. repainter->performAnyPendingRepaintsNow();
  1271. }
  1272. void setIcon (const Image& newIcon) override
  1273. {
  1274. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  1275. HeapBlock<unsigned long> data (dataSize);
  1276. int index = 0;
  1277. data[index++] = (unsigned long) newIcon.getWidth();
  1278. data[index++] = (unsigned long) newIcon.getHeight();
  1279. for (int y = 0; y < newIcon.getHeight(); ++y)
  1280. for (int x = 0; x < newIcon.getWidth(); ++x)
  1281. data[index++] = (unsigned long) newIcon.getPixelAt (x, y).getARGB();
  1282. ScopedXLock xlock (display);
  1283. xchangeProperty (windowH, Atoms::getCreating (display, "_NET_WM_ICON"), XA_CARDINAL, 32, data.getData(), dataSize);
  1284. deleteIconPixmaps();
  1285. XWMHints* wmHints = XGetWMHints (display, windowH);
  1286. if (wmHints == nullptr)
  1287. wmHints = XAllocWMHints();
  1288. wmHints->flags |= IconPixmapHint | IconMaskHint;
  1289. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  1290. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  1291. XSetWMHints (display, windowH, wmHints);
  1292. XFree (wmHints);
  1293. XSync (display, False);
  1294. }
  1295. void deleteIconPixmaps()
  1296. {
  1297. ScopedXLock xlock (display);
  1298. if (auto* wmHints = XGetWMHints (display, windowH))
  1299. {
  1300. if ((wmHints->flags & IconPixmapHint) != 0)
  1301. {
  1302. wmHints->flags &= ~IconPixmapHint;
  1303. XFreePixmap (display, wmHints->icon_pixmap);
  1304. }
  1305. if ((wmHints->flags & IconMaskHint) != 0)
  1306. {
  1307. wmHints->flags &= ~IconMaskHint;
  1308. XFreePixmap (display, wmHints->icon_mask);
  1309. }
  1310. XSetWMHints (display, windowH, wmHints);
  1311. XFree (wmHints);
  1312. }
  1313. }
  1314. //==============================================================================
  1315. void handleWindowMessage (XEvent& event)
  1316. {
  1317. switch (event.xany.type)
  1318. {
  1319. case KeyPressEventType: handleKeyPressEvent (event.xkey); break;
  1320. case KeyRelease: handleKeyReleaseEvent (event.xkey); break;
  1321. case ButtonPress: handleButtonPressEvent (event.xbutton); break;
  1322. case ButtonRelease: handleButtonReleaseEvent (event.xbutton); break;
  1323. case MotionNotify: handleMotionNotifyEvent (event.xmotion); break;
  1324. case EnterNotify: handleEnterNotifyEvent (event.xcrossing); break;
  1325. case LeaveNotify: handleLeaveNotifyEvent (event.xcrossing); break;
  1326. case FocusIn: handleFocusInEvent(); break;
  1327. case FocusOut: handleFocusOutEvent(); break;
  1328. case Expose: handleExposeEvent (event.xexpose); break;
  1329. case MappingNotify: handleMappingNotify (event.xmapping); break;
  1330. case ClientMessage: handleClientMessageEvent (event.xclient, event); break;
  1331. case SelectionNotify: handleDragAndDropSelection (event); break;
  1332. case ConfigureNotify: handleConfigureNotifyEvent (event.xconfigure); break;
  1333. case ReparentNotify:
  1334. case GravityNotify: handleGravityNotify(); break;
  1335. case SelectionClear: handleExternalSelectionClear(); break;
  1336. case SelectionRequest: handleExternalSelectionRequest (event); break;
  1337. case CirculateNotify:
  1338. case CreateNotify:
  1339. case DestroyNotify:
  1340. // Think we can ignore these
  1341. break;
  1342. case MapNotify:
  1343. mapped = true;
  1344. handleBroughtToFront();
  1345. break;
  1346. case UnmapNotify:
  1347. mapped = false;
  1348. break;
  1349. default:
  1350. #if JUCE_USE_XSHM
  1351. if (XSHMHelpers::isShmAvailable (display))
  1352. {
  1353. ScopedXLock xlock (display);
  1354. if (event.xany.type == shmCompletionEvent)
  1355. repainter->notifyPaintCompleted();
  1356. }
  1357. #endif
  1358. break;
  1359. }
  1360. }
  1361. void handleKeyPressEvent (XKeyEvent& keyEvent)
  1362. {
  1363. auto oldMods = ModifierKeys::currentModifiers;
  1364. char utf8 [64] = { 0 };
  1365. juce_wchar unicodeChar = 0;
  1366. int keyCode = 0;
  1367. bool keyDownChange = false;
  1368. KeySym sym;
  1369. {
  1370. ScopedXLock xlock (display);
  1371. updateKeyStates ((int) keyEvent.keycode, true);
  1372. String oldLocale (::setlocale (LC_ALL, nullptr));
  1373. ::setlocale (LC_ALL, "");
  1374. XLookupString (&keyEvent, utf8, sizeof (utf8), &sym, nullptr);
  1375. if (oldLocale.isNotEmpty())
  1376. ::setlocale (LC_ALL, oldLocale.toRawUTF8());
  1377. unicodeChar = *CharPointer_UTF8 (utf8);
  1378. keyCode = (int) unicodeChar;
  1379. if (keyCode < 0x20)
  1380. keyCode = (int) XkbKeycodeToKeysym (display, (::KeyCode) keyEvent.keycode, 0, ModifierKeys::currentModifiers.isShiftDown() ? 1 : 0);
  1381. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  1382. }
  1383. bool keyPressed = false;
  1384. if ((sym & 0xff00) == 0xff00 || keyCode == XK_ISO_Left_Tab)
  1385. {
  1386. switch (sym) // Translate keypad
  1387. {
  1388. case XK_KP_Add: keyCode = XK_plus; break;
  1389. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  1390. case XK_KP_Divide: keyCode = XK_slash; break;
  1391. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  1392. case XK_KP_Enter: keyCode = XK_Return; break;
  1393. case XK_KP_Insert: keyCode = XK_Insert; break;
  1394. case XK_Delete:
  1395. case XK_KP_Delete: keyCode = XK_Delete; break;
  1396. case XK_KP_Left: keyCode = XK_Left; break;
  1397. case XK_KP_Right: keyCode = XK_Right; break;
  1398. case XK_KP_Up: keyCode = XK_Up; break;
  1399. case XK_KP_Down: keyCode = XK_Down; break;
  1400. case XK_KP_Home: keyCode = XK_Home; break;
  1401. case XK_KP_End: keyCode = XK_End; break;
  1402. case XK_KP_Page_Down: keyCode = XK_Page_Down; break;
  1403. case XK_KP_Page_Up: keyCode = XK_Page_Up; break;
  1404. case XK_KP_0: keyCode = XK_0; break;
  1405. case XK_KP_1: keyCode = XK_1; break;
  1406. case XK_KP_2: keyCode = XK_2; break;
  1407. case XK_KP_3: keyCode = XK_3; break;
  1408. case XK_KP_4: keyCode = XK_4; break;
  1409. case XK_KP_5: keyCode = XK_5; break;
  1410. case XK_KP_6: keyCode = XK_6; break;
  1411. case XK_KP_7: keyCode = XK_7; break;
  1412. case XK_KP_8: keyCode = XK_8; break;
  1413. case XK_KP_9: keyCode = XK_9; break;
  1414. default: break;
  1415. }
  1416. switch (keyCode)
  1417. {
  1418. case XK_Left:
  1419. case XK_Right:
  1420. case XK_Up:
  1421. case XK_Down:
  1422. case XK_Page_Up:
  1423. case XK_Page_Down:
  1424. case XK_End:
  1425. case XK_Home:
  1426. case XK_Delete:
  1427. case XK_Insert:
  1428. keyPressed = true;
  1429. keyCode = (keyCode & 0xff) | Keys::extendedKeyModifier;
  1430. break;
  1431. case XK_Tab:
  1432. case XK_Return:
  1433. case XK_Escape:
  1434. case XK_BackSpace:
  1435. keyPressed = true;
  1436. keyCode &= 0xff;
  1437. break;
  1438. case XK_ISO_Left_Tab:
  1439. keyPressed = true;
  1440. keyCode = XK_Tab & 0xff;
  1441. break;
  1442. default:
  1443. if (sym >= XK_F1 && sym <= XK_F35)
  1444. {
  1445. keyPressed = true;
  1446. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  1447. }
  1448. break;
  1449. }
  1450. }
  1451. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  1452. keyPressed = true;
  1453. if (oldMods != ModifierKeys::currentModifiers)
  1454. handleModifierKeysChange();
  1455. if (keyDownChange)
  1456. handleKeyUpOrDown (true);
  1457. if (keyPressed)
  1458. handleKeyPress (keyCode, unicodeChar);
  1459. }
  1460. static bool isKeyReleasePartOfAutoRepeat (const XKeyEvent& keyReleaseEvent)
  1461. {
  1462. if (XPending (display))
  1463. {
  1464. XEvent e;
  1465. XPeekEvent (display, &e);
  1466. // Look for a subsequent key-down event with the same timestamp and keycode
  1467. return e.type == KeyPressEventType
  1468. && e.xkey.keycode == keyReleaseEvent.keycode
  1469. && e.xkey.time == keyReleaseEvent.time;
  1470. }
  1471. return false;
  1472. }
  1473. void handleKeyReleaseEvent (const XKeyEvent& keyEvent)
  1474. {
  1475. if (! isKeyReleasePartOfAutoRepeat (keyEvent))
  1476. {
  1477. updateKeyStates ((int) keyEvent.keycode, false);
  1478. KeySym sym;
  1479. {
  1480. ScopedXLock xlock (display);
  1481. sym = XkbKeycodeToKeysym (display, (::KeyCode) keyEvent.keycode, 0, 0);
  1482. }
  1483. auto oldMods = ModifierKeys::currentModifiers;
  1484. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  1485. if (oldMods != ModifierKeys::currentModifiers)
  1486. handleModifierKeysChange();
  1487. if (keyDownChange)
  1488. handleKeyUpOrDown (false);
  1489. }
  1490. }
  1491. template <typename EventType>
  1492. Point<float> getMousePos (const EventType& e) noexcept
  1493. {
  1494. return Point<float> ((float) e.x, (float) e.y) / currentScaleFactor;
  1495. }
  1496. void handleWheelEvent (const XButtonPressedEvent& buttonPressEvent, float amount)
  1497. {
  1498. MouseWheelDetails wheel;
  1499. wheel.deltaX = 0.0f;
  1500. wheel.deltaY = amount;
  1501. wheel.isReversed = false;
  1502. wheel.isSmooth = false;
  1503. wheel.isInertial = false;
  1504. handleMouseWheel (MouseInputSource::InputSourceType::mouse, getMousePos (buttonPressEvent),
  1505. getEventTime (buttonPressEvent), wheel);
  1506. }
  1507. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent, int buttonModifierFlag)
  1508. {
  1509. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (buttonModifierFlag);
  1510. toFront (true);
  1511. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (buttonPressEvent), ModifierKeys::currentModifiers,
  1512. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (buttonPressEvent), {});
  1513. }
  1514. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent)
  1515. {
  1516. updateKeyModifiers ((int) buttonPressEvent.state);
  1517. auto mapIndex = (uint32) (buttonPressEvent.button - Button1);
  1518. if (mapIndex < (uint32) numElementsInArray (pointerMap))
  1519. {
  1520. switch (pointerMap[mapIndex])
  1521. {
  1522. case Keys::WheelUp: handleWheelEvent (buttonPressEvent, 50.0f / 256.0f); break;
  1523. case Keys::WheelDown: handleWheelEvent (buttonPressEvent, -50.0f / 256.0f); break;
  1524. case Keys::LeftButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::leftButtonModifier); break;
  1525. case Keys::RightButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::rightButtonModifier); break;
  1526. case Keys::MiddleButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::middleButtonModifier); break;
  1527. default: break;
  1528. }
  1529. }
  1530. clearLastMousePos();
  1531. }
  1532. void handleButtonReleaseEvent (const XButtonReleasedEvent& buttonRelEvent)
  1533. {
  1534. updateKeyModifiers ((int) buttonRelEvent.state);
  1535. if (parentWindow != 0)
  1536. updateWindowBounds();
  1537. auto mapIndex = (uint32) (buttonRelEvent.button - Button1);
  1538. if (mapIndex < (uint32) numElementsInArray (pointerMap))
  1539. {
  1540. switch (pointerMap[mapIndex])
  1541. {
  1542. case Keys::LeftButton: ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
  1543. case Keys::RightButton: ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
  1544. case Keys::MiddleButton: ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
  1545. default: break;
  1546. }
  1547. }
  1548. if (dragState->dragging)
  1549. handleExternalDragButtonReleaseEvent();
  1550. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (buttonRelEvent), ModifierKeys::currentModifiers,
  1551. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (buttonRelEvent));
  1552. clearLastMousePos();
  1553. }
  1554. void handleMotionNotifyEvent (const XPointerMovedEvent& movedEvent)
  1555. {
  1556. updateKeyModifiers ((int) movedEvent.state);
  1557. lastMousePos = Point<int> (movedEvent.x_root, movedEvent.y_root);
  1558. if (dragState->dragging)
  1559. handleExternalDragMotionNotify();
  1560. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (movedEvent), ModifierKeys::currentModifiers,
  1561. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (movedEvent));
  1562. }
  1563. void handleEnterNotifyEvent (const XEnterWindowEvent& enterEvent)
  1564. {
  1565. if (parentWindow != 0)
  1566. updateWindowBounds();
  1567. clearLastMousePos();
  1568. if (! ModifierKeys::currentModifiers.isAnyMouseButtonDown())
  1569. {
  1570. updateKeyModifiers ((int) enterEvent.state);
  1571. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (enterEvent), ModifierKeys::currentModifiers,
  1572. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (enterEvent));
  1573. }
  1574. }
  1575. void handleLeaveNotifyEvent (const XLeaveWindowEvent& leaveEvent)
  1576. {
  1577. // Suppress the normal leave if we've got a pointer grab, or if
  1578. // it's a bogus one caused by clicking a mouse button when running
  1579. // in a Window manager
  1580. if (((! ModifierKeys::currentModifiers.isAnyMouseButtonDown()) && leaveEvent.mode == NotifyNormal)
  1581. || leaveEvent.mode == NotifyUngrab)
  1582. {
  1583. updateKeyModifiers ((int) leaveEvent.state);
  1584. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (leaveEvent), ModifierKeys::currentModifiers,
  1585. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (leaveEvent));
  1586. }
  1587. }
  1588. void handleFocusInEvent()
  1589. {
  1590. isActiveApplication = true;
  1591. if (isFocused() && ! focused)
  1592. {
  1593. focused = true;
  1594. handleFocusGain();
  1595. }
  1596. }
  1597. void handleFocusOutEvent()
  1598. {
  1599. if (! isFocused() && focused)
  1600. {
  1601. focused = false;
  1602. isActiveApplication = false;
  1603. handleFocusLoss();
  1604. }
  1605. }
  1606. void handleExposeEvent (XExposeEvent& exposeEvent)
  1607. {
  1608. // Batch together all pending expose events
  1609. XEvent nextEvent;
  1610. ScopedXLock xlock (display);
  1611. // if we have opengl contexts then just repaint them all
  1612. // regardless if this is really necessary
  1613. repaintOpenGLContexts();
  1614. if (exposeEvent.window != windowH)
  1615. {
  1616. Window child;
  1617. XTranslateCoordinates (display, exposeEvent.window, windowH,
  1618. exposeEvent.x, exposeEvent.y, &exposeEvent.x, &exposeEvent.y,
  1619. &child);
  1620. }
  1621. // exposeEvent is in local window local coordinates so do not convert with
  1622. // physicalToScaled, but rather use currentScaleFactor
  1623. repaint (Rectangle<int> (exposeEvent.x, exposeEvent.y,
  1624. exposeEvent.width, exposeEvent.height) / currentScaleFactor);
  1625. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  1626. {
  1627. XPeekEvent (display, &nextEvent);
  1628. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent.window)
  1629. break;
  1630. XNextEvent (display, &nextEvent);
  1631. auto& nextExposeEvent = (const XExposeEvent&) nextEvent.xexpose;
  1632. repaint (Rectangle<int> (nextExposeEvent.x, nextExposeEvent.y,
  1633. nextExposeEvent.width, nextExposeEvent.height) / currentScaleFactor);
  1634. }
  1635. }
  1636. void handleConfigureNotifyEvent (XConfigureEvent& confEvent)
  1637. {
  1638. updateWindowBounds();
  1639. updateBorderSize();
  1640. handleMovedOrResized();
  1641. // if the native title bar is dragged, need to tell any active menus, etc.
  1642. if ((styleFlags & windowHasTitleBar) != 0
  1643. && component.isCurrentlyBlockedByAnotherModalComponent())
  1644. {
  1645. if (auto* currentModalComp = Component::getCurrentlyModalComponent())
  1646. currentModalComp->inputAttemptWhenModal();
  1647. }
  1648. if (confEvent.window == windowH && confEvent.above != 0 && isFrontWindow())
  1649. handleBroughtToFront();
  1650. }
  1651. void handleGravityNotify()
  1652. {
  1653. updateWindowBounds();
  1654. updateBorderSize();
  1655. handleMovedOrResized();
  1656. }
  1657. void handleMappingNotify (XMappingEvent& mappingEvent)
  1658. {
  1659. if (mappingEvent.request != MappingPointer)
  1660. {
  1661. // Deal with modifier/keyboard mapping
  1662. ScopedXLock xlock (display);
  1663. XRefreshKeyboardMapping (&mappingEvent);
  1664. updateModifierMappings();
  1665. }
  1666. }
  1667. void handleClientMessageEvent (XClientMessageEvent& clientMsg, XEvent& event)
  1668. {
  1669. if (clientMsg.message_type == atoms->protocols && clientMsg.format == 32)
  1670. {
  1671. auto atom = (Atom) clientMsg.data.l[0];
  1672. if (atom == atoms->protocolList [Atoms::PING])
  1673. {
  1674. Window root = RootWindow (display, DefaultScreen (display));
  1675. clientMsg.window = root;
  1676. XSendEvent (display, root, False, NoEventMask, &event);
  1677. XFlush (display);
  1678. }
  1679. else if (atom == atoms->protocolList [Atoms::TAKE_FOCUS])
  1680. {
  1681. if ((getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0)
  1682. {
  1683. XWindowAttributes atts;
  1684. ScopedXLock xlock (display);
  1685. if (clientMsg.window != 0
  1686. && XGetWindowAttributes (display, clientMsg.window, &atts))
  1687. {
  1688. if (atts.map_state == IsViewable)
  1689. XSetInputFocus (display,
  1690. (clientMsg.window == windowH ? getFocusWindow()
  1691. : clientMsg.window),
  1692. RevertToParent,
  1693. (::Time) clientMsg.data.l[1]);
  1694. }
  1695. }
  1696. }
  1697. else if (atom == atoms->protocolList [Atoms::DELETE_WINDOW])
  1698. {
  1699. handleUserClosingWindow();
  1700. }
  1701. }
  1702. else if (clientMsg.message_type == atoms->XdndEnter)
  1703. {
  1704. handleDragAndDropEnter (clientMsg);
  1705. }
  1706. else if (clientMsg.message_type == atoms->XdndLeave)
  1707. {
  1708. handleDragExit (dragInfo);
  1709. resetDragAndDrop();
  1710. }
  1711. else if (clientMsg.message_type == atoms->XdndPosition)
  1712. {
  1713. handleDragAndDropPosition (clientMsg);
  1714. }
  1715. else if (clientMsg.message_type == atoms->XdndDrop)
  1716. {
  1717. handleDragAndDropDrop (clientMsg);
  1718. }
  1719. else if (clientMsg.message_type == atoms->XdndStatus)
  1720. {
  1721. handleExternalDragAndDropStatus (clientMsg);
  1722. }
  1723. else if (clientMsg.message_type == atoms->XdndFinished)
  1724. {
  1725. externalResetDragAndDrop();
  1726. }
  1727. else if (clientMsg.message_type == atoms->XembedMsgType && clientMsg.format == 32)
  1728. {
  1729. handleXEmbedMessage (clientMsg);
  1730. }
  1731. }
  1732. bool externalDragTextInit (const String& text, std::function<void()> cb)
  1733. {
  1734. if (dragState->dragging)
  1735. return false;
  1736. return externalDragInit (true, text, cb);
  1737. }
  1738. bool externalDragFileInit (const StringArray& files, bool /*canMoveFiles*/, std::function<void()> cb)
  1739. {
  1740. if (dragState->dragging)
  1741. return false;
  1742. StringArray uriList;
  1743. for (auto& f : files)
  1744. {
  1745. if (f.matchesWildcard ("?*://*", false))
  1746. uriList.add (f);
  1747. else
  1748. uriList.add ("file://" + f);
  1749. }
  1750. return externalDragInit (false, uriList.joinIntoString ("\r\n"), cb);
  1751. }
  1752. void handleXEmbedMessage (XClientMessageEvent& clientMsg)
  1753. {
  1754. switch (clientMsg.data.l[1])
  1755. {
  1756. case XEMBED_EMBEDDED_NOTIFY:
  1757. parentWindow = (::Window) clientMsg.data.l[3];
  1758. updateWindowBounds();
  1759. component.setBounds (bounds);
  1760. break;
  1761. case XEMBED_FOCUS_IN:
  1762. handleFocusInEvent();
  1763. break;
  1764. case XEMBED_FOCUS_OUT:
  1765. handleFocusOutEvent();
  1766. break;
  1767. default:
  1768. break;
  1769. }
  1770. }
  1771. //==============================================================================
  1772. void showMouseCursor (Cursor cursor) noexcept
  1773. {
  1774. ScopedXLock xlock (display);
  1775. XDefineCursor (display, windowH, cursor);
  1776. }
  1777. //==============================================================================
  1778. double getPlatformScaleFactor() const noexcept override
  1779. {
  1780. return currentScaleFactor;
  1781. }
  1782. //==============================================================================
  1783. void addOpenGLRepaintListener (Component* dummy)
  1784. {
  1785. if (dummy != nullptr)
  1786. glRepaintListeners.addIfNotAlreadyThere (dummy);
  1787. }
  1788. void removeOpenGLRepaintListener (Component* dummy)
  1789. {
  1790. if (dummy != nullptr)
  1791. glRepaintListeners.removeAllInstancesOf (dummy);
  1792. }
  1793. void repaintOpenGLContexts()
  1794. {
  1795. for (int i = 0; i < glRepaintListeners.size(); ++i)
  1796. if (auto* c = glRepaintListeners [i])
  1797. c->handleCommandMessage (0);
  1798. }
  1799. //==============================================================================
  1800. unsigned long createKeyProxy()
  1801. {
  1802. jassert (keyProxy == 0 && windowH != 0);
  1803. if (keyProxy == 0 && windowH != 0)
  1804. {
  1805. XSetWindowAttributes swa;
  1806. swa.event_mask = KeyPressMask | KeyReleaseMask | FocusChangeMask;
  1807. keyProxy = XCreateWindow (display, windowH,
  1808. -1, -1, 1, 1, 0, 0,
  1809. InputOnly, CopyFromParent,
  1810. CWEventMask,
  1811. &swa);
  1812. XMapWindow (display, keyProxy);
  1813. XSaveContext (display, (XID) keyProxy, windowHandleXContext, (XPointer) this);
  1814. }
  1815. return keyProxy;
  1816. }
  1817. void deleteKeyProxy()
  1818. {
  1819. jassert (keyProxy != 0);
  1820. if (keyProxy != 0)
  1821. {
  1822. XPointer handlePointer;
  1823. if (! XFindContext (display, (XID) keyProxy, windowHandleXContext, &handlePointer))
  1824. XDeleteContext (display, (XID) keyProxy, windowHandleXContext);
  1825. XDestroyWindow (display, keyProxy);
  1826. XSync (display, false);
  1827. XEvent event;
  1828. while (XCheckWindowEvent (display, keyProxy, getAllEventsMask(), &event) == True)
  1829. {}
  1830. keyProxy = 0;
  1831. }
  1832. }
  1833. //==============================================================================
  1834. bool dontRepaint;
  1835. static bool isActiveApplication;
  1836. private:
  1837. //==============================================================================
  1838. class LinuxRepaintManager : public Timer
  1839. {
  1840. public:
  1841. LinuxRepaintManager (LinuxComponentPeer& p, ::Display* d)
  1842. : peer (p), display (d)
  1843. {
  1844. #if JUCE_USE_XSHM
  1845. useARGBImagesForRendering = XSHMHelpers::isShmAvailable (display);
  1846. if (useARGBImagesForRendering)
  1847. {
  1848. ScopedXLock xlock (display);
  1849. XShmSegmentInfo segmentinfo;
  1850. auto testImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  1851. 24, ZPixmap, nullptr, &segmentinfo, 64, 64);
  1852. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  1853. XDestroyImage (testImage);
  1854. }
  1855. #endif
  1856. }
  1857. void timerCallback() override
  1858. {
  1859. #if JUCE_USE_XSHM
  1860. if (shmPaintsPending != 0)
  1861. {
  1862. ScopedXLock xlock (display);
  1863. XEvent evt;
  1864. while (XCheckTypedWindowEvent (display, peer.windowH, peer.shmCompletionEvent, &evt))
  1865. --shmPaintsPending;
  1866. }
  1867. if (shmPaintsPending != 0)
  1868. return;
  1869. #endif
  1870. if (! regionsNeedingRepaint.isEmpty())
  1871. {
  1872. stopTimer();
  1873. performAnyPendingRepaintsNow();
  1874. }
  1875. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  1876. {
  1877. stopTimer();
  1878. image = Image();
  1879. }
  1880. }
  1881. void repaint (Rectangle<int> area)
  1882. {
  1883. if (! isTimerRunning())
  1884. startTimer (repaintTimerPeriod);
  1885. regionsNeedingRepaint.add (area * peer.currentScaleFactor);
  1886. }
  1887. void performAnyPendingRepaintsNow()
  1888. {
  1889. #if JUCE_USE_XSHM
  1890. if (shmPaintsPending != 0)
  1891. {
  1892. startTimer (repaintTimerPeriod);
  1893. return;
  1894. }
  1895. #endif
  1896. auto originalRepaintRegion = regionsNeedingRepaint;
  1897. regionsNeedingRepaint.clear();
  1898. auto totalArea = originalRepaintRegion.getBounds();
  1899. if (! totalArea.isEmpty())
  1900. {
  1901. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  1902. || image.getHeight() < totalArea.getHeight())
  1903. {
  1904. #if JUCE_USE_XSHM
  1905. image = Image (new XBitmapImage (display, useARGBImagesForRendering ? Image::ARGB
  1906. : Image::RGB,
  1907. #else
  1908. image = Image (new XBitmapImage (display, Image::RGB,
  1909. #endif
  1910. (totalArea.getWidth() + 31) & ~31,
  1911. (totalArea.getHeight() + 31) & ~31,
  1912. false, (unsigned int) peer.depth, peer.visual));
  1913. }
  1914. startTimer (repaintTimerPeriod);
  1915. RectangleList<int> adjustedList (originalRepaintRegion);
  1916. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  1917. if (peer.depth == 32)
  1918. for (auto& i : originalRepaintRegion)
  1919. image.clear (i - totalArea.getPosition());
  1920. {
  1921. auto context = peer.getComponent().getLookAndFeel()
  1922. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList);
  1923. context->addTransform (AffineTransform::scale ((float) peer.currentScaleFactor));
  1924. peer.handlePaint (*context);
  1925. }
  1926. for (auto& i : originalRepaintRegion)
  1927. {
  1928. auto* xbitmap = static_cast<XBitmapImage*> (image.getPixelData());
  1929. #if JUCE_USE_XSHM
  1930. if (xbitmap->isUsingXShm())
  1931. ++shmPaintsPending;
  1932. #endif
  1933. xbitmap->blitToWindow (peer.windowH,
  1934. i.getX(), i.getY(),
  1935. (unsigned int) i.getWidth(),
  1936. (unsigned int) i.getHeight(),
  1937. i.getX() - totalArea.getX(), i.getY() - totalArea.getY());
  1938. }
  1939. }
  1940. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  1941. startTimer (repaintTimerPeriod);
  1942. }
  1943. #if JUCE_USE_XSHM
  1944. void notifyPaintCompleted() noexcept { --shmPaintsPending; }
  1945. #endif
  1946. private:
  1947. enum { repaintTimerPeriod = 1000 / 100 };
  1948. LinuxComponentPeer& peer;
  1949. Image image;
  1950. uint32 lastTimeImageUsed = 0;
  1951. RectangleList<int> regionsNeedingRepaint;
  1952. ::Display* display;
  1953. #if JUCE_USE_XSHM
  1954. bool useARGBImagesForRendering;
  1955. int shmPaintsPending = 0;
  1956. #endif
  1957. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  1958. };
  1959. std::unique_ptr<Atoms> atoms;
  1960. std::unique_ptr<LinuxRepaintManager> repainter;
  1961. friend class LinuxRepaintManager;
  1962. Window windowH = {}, parentWindow = {}, keyProxy = {};
  1963. Rectangle<int> bounds;
  1964. Point<int> parentScreenPosition;
  1965. Image taskbarImage;
  1966. bool fullScreen = false, mapped = false, focused = false;
  1967. Visual* visual = {};
  1968. int depth = 0;
  1969. BorderSize<int> windowBorder;
  1970. bool isAlwaysOnTop;
  1971. double currentScaleFactor = 1.0;
  1972. Array<Component*> glRepaintListeners;
  1973. enum { KeyPressEventType = 2 };
  1974. static ::Display* display;
  1975. #if JUCE_USE_XSHM
  1976. int shmCompletionEvent = 0;
  1977. #endif
  1978. struct MotifWmHints
  1979. {
  1980. unsigned long flags;
  1981. unsigned long functions;
  1982. unsigned long decorations;
  1983. long input_mode;
  1984. unsigned long status;
  1985. };
  1986. static void updateKeyStates (int keycode, bool press) noexcept
  1987. {
  1988. const int keybyte = keycode >> 3;
  1989. const int keybit = (1 << (keycode & 7));
  1990. if (press)
  1991. Keys::keyStates [keybyte] |= keybit;
  1992. else
  1993. Keys::keyStates [keybyte] &= ~keybit;
  1994. }
  1995. static void updateKeyModifiers (int status) noexcept
  1996. {
  1997. int keyMods = 0;
  1998. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  1999. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  2000. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  2001. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  2002. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  2003. Keys::capsLock = ((status & LockMask) != 0);
  2004. }
  2005. static bool updateKeyModifiersFromSym (KeySym sym, bool press) noexcept
  2006. {
  2007. int modifier = 0;
  2008. bool isModifier = true;
  2009. switch (sym)
  2010. {
  2011. case XK_Shift_L:
  2012. case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
  2013. case XK_Control_L:
  2014. case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
  2015. case XK_Alt_L:
  2016. case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
  2017. case XK_Num_Lock:
  2018. if (press)
  2019. Keys::numLock = ! Keys::numLock;
  2020. break;
  2021. case XK_Caps_Lock:
  2022. if (press)
  2023. Keys::capsLock = ! Keys::capsLock;
  2024. break;
  2025. case XK_Scroll_Lock:
  2026. break;
  2027. default:
  2028. isModifier = false;
  2029. break;
  2030. }
  2031. ModifierKeys::currentModifiers = press ? ModifierKeys::currentModifiers.withFlags (modifier)
  2032. : ModifierKeys::currentModifiers.withoutFlags (modifier);
  2033. return isModifier;
  2034. }
  2035. // Alt and Num lock are not defined by standard X
  2036. // modifier constants: check what they're mapped to
  2037. static void updateModifierMappings() noexcept
  2038. {
  2039. ScopedXLock xlock (display);
  2040. int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  2041. int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  2042. Keys::AltMask = 0;
  2043. Keys::NumLockMask = 0;
  2044. if (auto* mapping = XGetModifierMapping (display))
  2045. {
  2046. for (int modifierIdx = 0; modifierIdx < 8; ++modifierIdx)
  2047. {
  2048. for (int keyIndex = 0; keyIndex < mapping->max_keypermod; ++keyIndex)
  2049. {
  2050. auto key = mapping->modifiermap[(modifierIdx * mapping->max_keypermod) + keyIndex];
  2051. if (key == altLeftCode)
  2052. Keys::AltMask = 1 << modifierIdx;
  2053. else if (key == numLockCode)
  2054. Keys::NumLockMask = 1 << modifierIdx;
  2055. }
  2056. }
  2057. XFreeModifiermap (mapping);
  2058. }
  2059. }
  2060. //==============================================================================
  2061. static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
  2062. {
  2063. XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  2064. }
  2065. void removeWindowDecorations (Window wndH)
  2066. {
  2067. Atom hints = Atoms::getIfExists (display, "_MOTIF_WM_HINTS");
  2068. if (hints != None)
  2069. {
  2070. MotifWmHints motifHints;
  2071. zerostruct (motifHints);
  2072. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  2073. motifHints.decorations = 0;
  2074. ScopedXLock xlock (display);
  2075. xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
  2076. }
  2077. hints = Atoms::getIfExists (display, "_WIN_HINTS");
  2078. if (hints != None)
  2079. {
  2080. long gnomeHints = 0;
  2081. ScopedXLock xlock (display);
  2082. xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
  2083. }
  2084. hints = Atoms::getIfExists (display, "KWM_WIN_DECORATION");
  2085. if (hints != None)
  2086. {
  2087. long kwmHints = 2; /*KDE_tinyDecoration*/
  2088. ScopedXLock xlock (display);
  2089. xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
  2090. }
  2091. hints = Atoms::getIfExists (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  2092. if (hints != None)
  2093. {
  2094. ScopedXLock xlock (display);
  2095. xchangeProperty (wndH, atoms->windowType, XA_ATOM, 32, &hints, 1);
  2096. }
  2097. }
  2098. void addWindowButtons (Window wndH)
  2099. {
  2100. ScopedXLock xlock (display);
  2101. Atom hints = Atoms::getIfExists (display, "_MOTIF_WM_HINTS");
  2102. if (hints != None)
  2103. {
  2104. MotifWmHints motifHints;
  2105. zerostruct (motifHints);
  2106. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  2107. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  2108. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  2109. if ((styleFlags & windowHasCloseButton) != 0)
  2110. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  2111. if ((styleFlags & windowHasMinimiseButton) != 0)
  2112. {
  2113. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  2114. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  2115. }
  2116. if ((styleFlags & windowHasMaximiseButton) != 0)
  2117. {
  2118. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  2119. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  2120. }
  2121. if ((styleFlags & windowIsResizable) != 0)
  2122. {
  2123. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  2124. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  2125. }
  2126. xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
  2127. }
  2128. hints = Atoms::getIfExists (display, "_NET_WM_ALLOWED_ACTIONS");
  2129. if (hints != None)
  2130. {
  2131. Atom netHints [6];
  2132. int num = 0;
  2133. if ((styleFlags & windowIsResizable) != 0)
  2134. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_RESIZE");
  2135. if ((styleFlags & windowHasMaximiseButton) != 0)
  2136. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_FULLSCREEN");
  2137. if ((styleFlags & windowHasMinimiseButton) != 0)
  2138. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_MINIMIZE");
  2139. if ((styleFlags & windowHasCloseButton) != 0)
  2140. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_CLOSE");
  2141. xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
  2142. }
  2143. }
  2144. void setWindowType()
  2145. {
  2146. Atom netHints [2];
  2147. if ((styleFlags & windowIsTemporary) != 0
  2148. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  2149. netHints [0] = Atoms::getIfExists (display, "_NET_WM_WINDOW_TYPE_COMBO");
  2150. else
  2151. netHints [0] = Atoms::getIfExists (display, "_NET_WM_WINDOW_TYPE_NORMAL");
  2152. xchangeProperty (windowH, atoms->windowType, XA_ATOM, 32, &netHints, 1);
  2153. int numHints = 0;
  2154. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  2155. netHints [numHints++] = Atoms::getIfExists (display, "_NET_WM_STATE_SKIP_TASKBAR");
  2156. if (component.isAlwaysOnTop())
  2157. netHints [numHints++] = Atoms::getIfExists (display, "_NET_WM_STATE_ABOVE");
  2158. if (numHints > 0)
  2159. xchangeProperty (windowH, atoms->windowState, XA_ATOM, 32, &netHints, numHints);
  2160. }
  2161. void createWindow (Window parentToAddTo)
  2162. {
  2163. ScopedXLock xlock (display);
  2164. resetDragAndDrop();
  2165. // Get defaults for various properties
  2166. const int screen = DefaultScreen (display);
  2167. Window root = RootWindow (display, screen);
  2168. parentWindow = parentToAddTo;
  2169. // Try to obtain a 32-bit visual or fallback to 24 or 16
  2170. visual = Visuals::findVisualFormat (display, (styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  2171. if (visual == nullptr)
  2172. {
  2173. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  2174. Process::terminate();
  2175. }
  2176. // Create and install a colormap suitable fr our visual
  2177. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  2178. XInstallColormap (display, colormap);
  2179. // Set up the window attributes
  2180. XSetWindowAttributes swa;
  2181. swa.border_pixel = 0;
  2182. swa.background_pixmap = None;
  2183. swa.colormap = colormap;
  2184. swa.override_redirect = ((styleFlags & windowIsTemporary) != 0) ? True : False;
  2185. swa.event_mask = getAllEventsMask();
  2186. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  2187. 0, 0, 1, 1,
  2188. 0, depth, InputOutput, visual,
  2189. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  2190. &swa);
  2191. // Set the window context to identify the window handle object
  2192. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  2193. {
  2194. // Failed
  2195. jassertfalse;
  2196. Logger::outputDebugString ("Failed to create context information for window.\n");
  2197. XDestroyWindow (display, windowH);
  2198. windowH = 0;
  2199. return;
  2200. }
  2201. // Set window manager hints
  2202. XWMHints* wmHints = XAllocWMHints();
  2203. wmHints->flags = InputHint | StateHint;
  2204. wmHints->input = True; // Locally active input model
  2205. wmHints->initial_state = NormalState;
  2206. XSetWMHints (display, windowH, wmHints);
  2207. XFree (wmHints);
  2208. // Set the window type
  2209. setWindowType();
  2210. // Define decoration
  2211. if ((styleFlags & windowHasTitleBar) == 0)
  2212. removeWindowDecorations (windowH);
  2213. else
  2214. addWindowButtons (windowH);
  2215. setTitle (component.getName());
  2216. // Associate the PID, allowing to be shut down when something goes wrong
  2217. unsigned long pid = (unsigned long) getpid();
  2218. xchangeProperty (windowH, atoms->pid, XA_CARDINAL, 32, &pid, 1);
  2219. // Set window manager protocols
  2220. xchangeProperty (windowH, atoms->protocols, XA_ATOM, 32, atoms->protocolList, 2);
  2221. // Set drag and drop flags
  2222. xchangeProperty (windowH, atoms->XdndTypeList, XA_ATOM, 32, atoms->allowedMimeTypes, numElementsInArray (atoms->allowedMimeTypes));
  2223. xchangeProperty (windowH, atoms->XdndActionList, XA_ATOM, 32, atoms->allowedActions, numElementsInArray (atoms->allowedActions));
  2224. xchangeProperty (windowH, atoms->XdndActionDescription, XA_STRING, 8, "", 0);
  2225. xchangeProperty (windowH, atoms->XdndAware, XA_ATOM, 32, &atoms->DndVersion, 1);
  2226. unsigned long info[2] = { 0, 1 };
  2227. xchangeProperty (windowH, atoms->XembedInfo, atoms->XembedInfo, 32, (unsigned char*) info, 2);
  2228. initialisePointerMap();
  2229. updateModifierMappings();
  2230. #if JUCE_USE_XSHM
  2231. if (XSHMHelpers::isShmAvailable (display))
  2232. shmCompletionEvent = XShmGetEventBase (display) + ShmCompletion;
  2233. #endif
  2234. }
  2235. void destroyWindow()
  2236. {
  2237. ScopedXLock xlock (display);
  2238. XPointer handlePointer;
  2239. if (keyProxy != 0)
  2240. deleteKeyProxy();
  2241. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  2242. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  2243. XDestroyWindow (display, windowH);
  2244. // Wait for it to complete and then remove any events for this
  2245. // window from the event queue.
  2246. XSync (display, false);
  2247. XEvent event;
  2248. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  2249. {}
  2250. }
  2251. int getAllEventsMask() const noexcept
  2252. {
  2253. return NoEventMask | KeyPressMask | KeyReleaseMask
  2254. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  2255. | ExposureMask | StructureNotifyMask | FocusChangeMask
  2256. | ((styleFlags & windowIgnoresMouseClicks) != 0 ? 0 : (ButtonPressMask | ButtonReleaseMask));
  2257. }
  2258. template <typename EventType>
  2259. static int64 getEventTime (const EventType& t)
  2260. {
  2261. return getEventTime (t.time);
  2262. }
  2263. static int64 getEventTime (::Time t)
  2264. {
  2265. static int64 eventTimeOffset = 0x12345678;
  2266. auto thisMessageTime = (int64) t;
  2267. if (eventTimeOffset == 0x12345678)
  2268. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  2269. return eventTimeOffset + thisMessageTime;
  2270. }
  2271. long getUserTime() const
  2272. {
  2273. GetXProperty prop (display, windowH, atoms->userTime, 0, 65536, false, XA_CARDINAL);
  2274. if (! prop.success)
  2275. return 0;
  2276. long result;
  2277. memcpy (&result, prop.data, sizeof (long));
  2278. return result;
  2279. }
  2280. void updateBorderSize()
  2281. {
  2282. if ((styleFlags & windowHasTitleBar) == 0)
  2283. {
  2284. windowBorder = BorderSize<int> (0);
  2285. }
  2286. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  2287. {
  2288. ScopedXLock xlock (display);
  2289. Atom hints = Atoms::getIfExists (display, "_NET_FRAME_EXTENTS");
  2290. if (hints != None)
  2291. {
  2292. GetXProperty prop (display, windowH, hints, 0, 4, false, XA_CARDINAL);
  2293. if (prop.success && prop.actualFormat == 32)
  2294. {
  2295. auto data = prop.data;
  2296. std::array<unsigned long, 4> sizes;
  2297. for (auto& size : sizes)
  2298. {
  2299. memcpy (&size, data, sizeof (unsigned long));
  2300. data += sizeof (unsigned long);
  2301. }
  2302. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  2303. (int) sizes[3], (int) sizes[1]);
  2304. }
  2305. }
  2306. }
  2307. }
  2308. void updateWindowBounds()
  2309. {
  2310. jassert (windowH != 0);
  2311. if (windowH != 0)
  2312. {
  2313. Window root, child;
  2314. int wx = 0, wy = 0;
  2315. unsigned int ww = 0, wh = 0, bw, bitDepth;
  2316. ScopedXLock xlock (display);
  2317. if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth))
  2318. {
  2319. int rootX = 0, rootY = 0;
  2320. if (! XTranslateCoordinates (display, windowH, root, 0, 0, &rootX, &rootY, &child))
  2321. rootX = rootY = 0;
  2322. if (parentWindow == 0)
  2323. {
  2324. wx = rootX;
  2325. wy = rootY;
  2326. }
  2327. else
  2328. {
  2329. parentScreenPosition = Desktop::getInstance().getDisplays().physicalToLogical (Point<int> (rootX, rootY));
  2330. }
  2331. }
  2332. Rectangle<int> physicalBounds (wx, wy, (int) ww, (int) wh);
  2333. updateScaleFactorFromNewBounds (physicalBounds, true);
  2334. bounds = (parentWindow == 0 ? Desktop::getInstance().getDisplays().physicalToLogical (physicalBounds)
  2335. : physicalBounds / currentScaleFactor);
  2336. }
  2337. }
  2338. //==============================================================================
  2339. struct DragState
  2340. {
  2341. DragState (::Display* d)
  2342. {
  2343. if (isText)
  2344. allowedTypes.add (Atoms::getCreating (d, "text/plain"));
  2345. else
  2346. allowedTypes.add (Atoms::getCreating (d, "text/uri-list"));
  2347. }
  2348. bool isText = false;
  2349. bool dragging = false; // currently performing outgoing external dnd as Xdnd source, have grabbed mouse
  2350. bool expectingStatus = false; // XdndPosition sent, waiting for XdndStatus
  2351. bool canDrop = false; // target window signals it will accept the drop
  2352. Window targetWindow = None; // potential drop target
  2353. int xdndVersion = -1; // negotiated version with target
  2354. Rectangle<int> silentRect;
  2355. String textOrFiles;
  2356. Array<Atom> allowedTypes;
  2357. std::function<void()> completionCallback;
  2358. };
  2359. //==============================================================================
  2360. void resetDragAndDrop()
  2361. {
  2362. dragInfo.clear();
  2363. dragInfo.position = Point<int> (-1, -1);
  2364. dragAndDropCurrentMimeType = 0;
  2365. dragAndDropSourceWindow = 0;
  2366. srcMimeTypeAtomList.clear();
  2367. finishAfterDropDataReceived = false;
  2368. }
  2369. void resetExternalDragState()
  2370. {
  2371. dragState.reset (new DragState (display));
  2372. }
  2373. void sendDragAndDropMessage (XClientMessageEvent& msg)
  2374. {
  2375. msg.type = ClientMessage;
  2376. msg.display = display;
  2377. msg.window = dragAndDropSourceWindow;
  2378. msg.format = 32;
  2379. msg.data.l[0] = (long) windowH;
  2380. ScopedXLock xlock (display);
  2381. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  2382. }
  2383. bool sendExternalDragAndDropMessage (XClientMessageEvent& msg, Window targetWindow)
  2384. {
  2385. msg.type = ClientMessage;
  2386. msg.display = display;
  2387. msg.window = targetWindow;
  2388. msg.format = 32;
  2389. msg.data.l[0] = (long) windowH;
  2390. ScopedXLock xlock (display);
  2391. return XSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
  2392. }
  2393. void sendExternalDragAndDropDrop (Window targetWindow)
  2394. {
  2395. XClientMessageEvent msg;
  2396. zerostruct (msg);
  2397. msg.message_type = atoms->XdndDrop;
  2398. msg.data.l[2] = CurrentTime;
  2399. sendExternalDragAndDropMessage (msg, targetWindow);
  2400. }
  2401. void sendExternalDragAndDropEnter (Window targetWindow)
  2402. {
  2403. XClientMessageEvent msg;
  2404. zerostruct (msg);
  2405. msg.message_type = atoms->XdndEnter;
  2406. msg.data.l[1] = (dragState->xdndVersion << 24);
  2407. for (int i = 0; i < 3; ++i)
  2408. msg.data.l[i + 2] = (long) dragState->allowedTypes[i];
  2409. sendExternalDragAndDropMessage (msg, targetWindow);
  2410. }
  2411. void sendExternalDragAndDropPosition (Window targetWindow)
  2412. {
  2413. XClientMessageEvent msg;
  2414. zerostruct (msg);
  2415. msg.message_type = atoms->XdndPosition;
  2416. Point<int> mousePos (Desktop::getInstance().getMousePosition());
  2417. if (dragState->silentRect.contains (mousePos)) // we've been asked to keep silent
  2418. return;
  2419. auto& displays = Desktop::getInstance().getDisplays();
  2420. mousePos = displays.logicalToPhysical (mousePos);
  2421. msg.data.l[1] = 0;
  2422. msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
  2423. msg.data.l[3] = CurrentTime;
  2424. msg.data.l[4] = (long) atoms->XdndActionCopy; // this is all JUCE currently supports
  2425. dragState->expectingStatus = sendExternalDragAndDropMessage (msg, targetWindow);
  2426. }
  2427. void sendDragAndDropStatus (bool acceptDrop, Atom dropAction)
  2428. {
  2429. XClientMessageEvent msg;
  2430. zerostruct (msg);
  2431. msg.message_type = atoms->XdndStatus;
  2432. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  2433. msg.data.l[4] = (long) dropAction;
  2434. sendDragAndDropMessage (msg);
  2435. }
  2436. void sendExternalDragAndDropLeave (Window targetWindow)
  2437. {
  2438. XClientMessageEvent msg;
  2439. zerostruct (msg);
  2440. msg.message_type = atoms->XdndLeave;
  2441. sendExternalDragAndDropMessage (msg, targetWindow);
  2442. }
  2443. void sendDragAndDropFinish()
  2444. {
  2445. XClientMessageEvent msg;
  2446. zerostruct (msg);
  2447. msg.message_type = atoms->XdndFinished;
  2448. sendDragAndDropMessage (msg);
  2449. }
  2450. void handleExternalSelectionClear()
  2451. {
  2452. if (dragState->dragging)
  2453. externalResetDragAndDrop();
  2454. }
  2455. void handleExternalSelectionRequest (const XEvent& evt)
  2456. {
  2457. Atom targetType = evt.xselectionrequest.target;
  2458. XEvent s;
  2459. s.xselection.type = SelectionNotify;
  2460. s.xselection.requestor = evt.xselectionrequest.requestor;
  2461. s.xselection.selection = evt.xselectionrequest.selection;
  2462. s.xselection.target = targetType;
  2463. s.xselection.property = None;
  2464. s.xselection.time = evt.xselectionrequest.time;
  2465. if (dragState->allowedTypes.contains (targetType))
  2466. {
  2467. s.xselection.property = evt.xselectionrequest.property;
  2468. xchangeProperty (evt.xselectionrequest.requestor,
  2469. evt.xselectionrequest.property,
  2470. targetType, 8,
  2471. dragState->textOrFiles.toRawUTF8(),
  2472. (int) dragState->textOrFiles.getNumBytesAsUTF8());
  2473. }
  2474. XSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
  2475. }
  2476. void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
  2477. {
  2478. if (dragState->expectingStatus)
  2479. {
  2480. dragState->expectingStatus = false;
  2481. dragState->canDrop = false;
  2482. dragState->silentRect = Rectangle<int>();
  2483. if ((clientMsg.data.l[1] & 1) != 0
  2484. && ((Atom) clientMsg.data.l[4] == atoms->XdndActionCopy
  2485. || (Atom) clientMsg.data.l[4] == atoms->XdndActionPrivate))
  2486. {
  2487. if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
  2488. dragState->silentRect.setBounds ((int) clientMsg.data.l[2] >> 16,
  2489. (int) clientMsg.data.l[2] & 0xffff,
  2490. (int) clientMsg.data.l[3] >> 16,
  2491. (int) clientMsg.data.l[3] & 0xffff);
  2492. dragState->canDrop = true;
  2493. }
  2494. }
  2495. }
  2496. void handleExternalDragButtonReleaseEvent()
  2497. {
  2498. if (dragState->dragging)
  2499. XUngrabPointer (display, CurrentTime);
  2500. if (dragState->canDrop)
  2501. {
  2502. sendExternalDragAndDropDrop (dragState->targetWindow);
  2503. }
  2504. else
  2505. {
  2506. sendExternalDragAndDropLeave (dragState->targetWindow);
  2507. externalResetDragAndDrop();
  2508. }
  2509. }
  2510. void handleExternalDragMotionNotify()
  2511. {
  2512. Window targetWindow = externalFindDragTargetWindow (RootWindow (display, DefaultScreen (display)));
  2513. if (dragState->targetWindow != targetWindow)
  2514. {
  2515. if (dragState->targetWindow != None)
  2516. sendExternalDragAndDropLeave (dragState->targetWindow);
  2517. dragState->canDrop = false;
  2518. dragState->silentRect = Rectangle<int>();
  2519. if (targetWindow == None)
  2520. return;
  2521. dragState->xdndVersion = getDnDVersionForWindow (targetWindow);
  2522. if (dragState->xdndVersion == -1)
  2523. return;
  2524. sendExternalDragAndDropEnter (targetWindow);
  2525. dragState->targetWindow = targetWindow;
  2526. }
  2527. if (! dragState->expectingStatus)
  2528. sendExternalDragAndDropPosition (targetWindow);
  2529. }
  2530. void handleDragAndDropPosition (const XClientMessageEvent& clientMsg)
  2531. {
  2532. if (dragAndDropSourceWindow == 0)
  2533. return;
  2534. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2535. Point<int> dropPos ((int) clientMsg.data.l[2] >> 16,
  2536. (int) clientMsg.data.l[2] & 0xffff);
  2537. dropPos = Desktop::getInstance().getDisplays().physicalToLogical (dropPos);
  2538. dropPos -= bounds.getPosition();
  2539. Atom targetAction = atoms->XdndActionCopy;
  2540. for (int i = numElementsInArray (atoms->allowedActions); --i >= 0;)
  2541. {
  2542. if ((Atom) clientMsg.data.l[4] == atoms->allowedActions[i])
  2543. {
  2544. targetAction = atoms->allowedActions[i];
  2545. break;
  2546. }
  2547. }
  2548. sendDragAndDropStatus (true, targetAction);
  2549. if (dragInfo.position != dropPos)
  2550. {
  2551. dragInfo.position = dropPos;
  2552. if (dragInfo.isEmpty())
  2553. updateDraggedFileList (clientMsg);
  2554. if (! dragInfo.isEmpty())
  2555. handleDragMove (dragInfo);
  2556. }
  2557. }
  2558. void handleDragAndDropDrop (const XClientMessageEvent& clientMsg)
  2559. {
  2560. if (dragInfo.isEmpty())
  2561. {
  2562. // no data, transaction finished in handleDragAndDropSelection()
  2563. finishAfterDropDataReceived = true;
  2564. updateDraggedFileList (clientMsg);
  2565. }
  2566. else
  2567. {
  2568. handleDragAndDropDataReceived(); // data was already received
  2569. }
  2570. }
  2571. void handleDragAndDropDataReceived()
  2572. {
  2573. DragInfo dragInfoCopy (dragInfo);
  2574. sendDragAndDropFinish();
  2575. resetDragAndDrop();
  2576. if (! dragInfoCopy.isEmpty())
  2577. handleDragDrop (dragInfoCopy);
  2578. }
  2579. void handleDragAndDropEnter (const XClientMessageEvent& clientMsg)
  2580. {
  2581. dragInfo.clear();
  2582. srcMimeTypeAtomList.clear();
  2583. dragAndDropCurrentMimeType = 0;
  2584. auto dndCurrentVersion = static_cast<unsigned long> (clientMsg.data.l[1] & 0xff000000) >> 24;
  2585. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  2586. {
  2587. dragAndDropSourceWindow = 0;
  2588. return;
  2589. }
  2590. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2591. if ((clientMsg.data.l[1] & 1) != 0)
  2592. {
  2593. ScopedXLock xlock (display);
  2594. GetXProperty prop (display, dragAndDropSourceWindow, atoms->XdndTypeList, 0, 0x8000000L, false, XA_ATOM);
  2595. if (prop.success
  2596. && prop.actualType == XA_ATOM
  2597. && prop.actualFormat == 32
  2598. && prop.numItems != 0)
  2599. {
  2600. auto* types = prop.data;
  2601. for (unsigned long i = 0; i < prop.numItems; ++i)
  2602. {
  2603. unsigned long type;
  2604. memcpy (&type, types, sizeof (unsigned long));
  2605. if (type != None)
  2606. srcMimeTypeAtomList.add (type);
  2607. types += sizeof (unsigned long);
  2608. }
  2609. }
  2610. }
  2611. if (srcMimeTypeAtomList.isEmpty())
  2612. {
  2613. for (int i = 2; i < 5; ++i)
  2614. if (clientMsg.data.l[i] != None)
  2615. srcMimeTypeAtomList.add ((unsigned long) clientMsg.data.l[i]);
  2616. if (srcMimeTypeAtomList.isEmpty())
  2617. {
  2618. dragAndDropSourceWindow = 0;
  2619. return;
  2620. }
  2621. }
  2622. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  2623. for (int j = 0; j < numElementsInArray (atoms->allowedMimeTypes); ++j)
  2624. if (srcMimeTypeAtomList[i] == atoms->allowedMimeTypes[j])
  2625. dragAndDropCurrentMimeType = atoms->allowedMimeTypes[j];
  2626. handleDragAndDropPosition (clientMsg);
  2627. }
  2628. void handleDragAndDropSelection (const XEvent& evt)
  2629. {
  2630. dragInfo.clear();
  2631. if (evt.xselection.property != None)
  2632. {
  2633. StringArray lines;
  2634. {
  2635. MemoryBlock dropData;
  2636. for (;;)
  2637. {
  2638. GetXProperty prop (display, evt.xany.window, evt.xselection.property,
  2639. (long) (dropData.getSize() / 4), 65536, false, AnyPropertyType);
  2640. if (! prop.success)
  2641. break;
  2642. dropData.append (prop.data, (size_t) (prop.actualFormat / 8) * prop.numItems);
  2643. if (prop.bytesLeft <= 0)
  2644. break;
  2645. }
  2646. lines.addLines (dropData.toString());
  2647. }
  2648. if (Atoms::isMimeTypeFile (display, dragAndDropCurrentMimeType))
  2649. {
  2650. for (int i = 0; i < lines.size(); ++i)
  2651. dragInfo.files.add (URL::removeEscapeChars (lines[i].replace ("file://", String(), true)));
  2652. dragInfo.files.trim();
  2653. dragInfo.files.removeEmptyStrings();
  2654. }
  2655. else
  2656. {
  2657. dragInfo.text = lines.joinIntoString ("\n");
  2658. }
  2659. if (finishAfterDropDataReceived)
  2660. handleDragAndDropDataReceived();
  2661. }
  2662. }
  2663. void updateDraggedFileList (const XClientMessageEvent& clientMsg)
  2664. {
  2665. jassert (dragInfo.isEmpty());
  2666. if (dragAndDropSourceWindow != None
  2667. && dragAndDropCurrentMimeType != None)
  2668. {
  2669. ScopedXLock xlock (display);
  2670. XConvertSelection (display,
  2671. atoms->XdndSelection,
  2672. dragAndDropCurrentMimeType,
  2673. Atoms::getCreating (display, "JXSelectionWindowProperty"),
  2674. windowH,
  2675. (::Time) clientMsg.data.l[2]);
  2676. }
  2677. }
  2678. bool isWindowDnDAware (Window w) const
  2679. {
  2680. int numProperties = 0;
  2681. auto* properties = XListProperties (display, w, &numProperties);
  2682. bool dndAwarePropFound = false;
  2683. for (int i = 0; i < numProperties; ++i)
  2684. if (properties[i] == atoms->XdndAware)
  2685. dndAwarePropFound = true;
  2686. if (properties != nullptr)
  2687. XFree (properties);
  2688. return dndAwarePropFound;
  2689. }
  2690. int getDnDVersionForWindow (Window targetWindow)
  2691. {
  2692. GetXProperty prop (display, targetWindow, atoms->XdndAware,
  2693. 0, 2, false, AnyPropertyType);
  2694. if (prop.success && prop.data != None && prop.actualFormat == 32 && prop.numItems == 1)
  2695. return jmin ((int) prop.data[0], (int) atoms->DndVersion);
  2696. return -1;
  2697. }
  2698. Window externalFindDragTargetWindow (Window targetWindow)
  2699. {
  2700. if (targetWindow == None)
  2701. return None;
  2702. if (isWindowDnDAware (targetWindow))
  2703. return targetWindow;
  2704. Window child, phonyWin;
  2705. int phony;
  2706. unsigned int uphony;
  2707. XQueryPointer (display, targetWindow, &phonyWin, &child,
  2708. &phony, &phony, &phony, &phony, &uphony);
  2709. return externalFindDragTargetWindow (child);
  2710. }
  2711. bool externalDragInit (bool isText, const String& textOrFiles, std::function<void()> cb)
  2712. {
  2713. ScopedXLock xlock (display);
  2714. resetExternalDragState();
  2715. dragState->isText = isText;
  2716. dragState->textOrFiles = textOrFiles;
  2717. dragState->targetWindow = windowH;
  2718. dragState->completionCallback = cb;
  2719. const int pointerGrabMask = Button1MotionMask | ButtonReleaseMask;
  2720. if (XGrabPointer (display, windowH, True, pointerGrabMask,
  2721. GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
  2722. {
  2723. // No other method of changing the pointer seems to work, this call is needed from this very context
  2724. XChangeActivePointerGrab (display, pointerGrabMask, (Cursor) createDraggingHandCursor(), CurrentTime);
  2725. XSetSelectionOwner (display, atoms->XdndSelection, windowH, CurrentTime);
  2726. // save the available types to XdndTypeList
  2727. xchangeProperty (windowH, atoms->XdndTypeList, XA_ATOM, 32,
  2728. dragState->allowedTypes.getRawDataPointer(),
  2729. dragState->allowedTypes.size());
  2730. dragState->dragging = true;
  2731. dragState->xdndVersion = getDnDVersionForWindow (dragState->targetWindow);
  2732. sendExternalDragAndDropEnter (dragState->targetWindow);
  2733. handleExternalDragMotionNotify();
  2734. return true;
  2735. }
  2736. return false;
  2737. }
  2738. void externalResetDragAndDrop()
  2739. {
  2740. if (dragState->dragging)
  2741. {
  2742. ScopedXLock xlock (display);
  2743. XUngrabPointer (display, CurrentTime);
  2744. }
  2745. if (dragState->completionCallback != nullptr)
  2746. dragState->completionCallback();
  2747. resetExternalDragState();
  2748. }
  2749. std::unique_ptr<DragState> dragState;
  2750. DragInfo dragInfo;
  2751. Atom dragAndDropCurrentMimeType;
  2752. Window dragAndDropSourceWindow;
  2753. bool finishAfterDropDataReceived;
  2754. Array<Atom> srcMimeTypeAtomList;
  2755. int pointerMap[5] = {};
  2756. void initialisePointerMap()
  2757. {
  2758. const int numButtons = XGetPointerMapping (display, nullptr, 0);
  2759. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2760. if (numButtons == 2)
  2761. {
  2762. pointerMap[0] = Keys::LeftButton;
  2763. pointerMap[1] = Keys::RightButton;
  2764. }
  2765. else if (numButtons >= 3)
  2766. {
  2767. pointerMap[0] = Keys::LeftButton;
  2768. pointerMap[1] = Keys::MiddleButton;
  2769. pointerMap[2] = Keys::RightButton;
  2770. if (numButtons >= 5)
  2771. {
  2772. pointerMap[3] = Keys::WheelUp;
  2773. pointerMap[4] = Keys::WheelDown;
  2774. }
  2775. }
  2776. }
  2777. static Point<int> lastMousePos;
  2778. static void clearLastMousePos() noexcept
  2779. {
  2780. lastMousePos = Point<int> (0x100000, 0x100000);
  2781. }
  2782. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  2783. };
  2784. bool LinuxComponentPeer::isActiveApplication = false;
  2785. Point<int> LinuxComponentPeer::lastMousePos;
  2786. ::Display* LinuxComponentPeer::display = nullptr;
  2787. //==============================================================================
  2788. namespace WindowingHelpers
  2789. {
  2790. static void windowMessageReceive (XEvent& event)
  2791. {
  2792. if (event.xany.window != None)
  2793. {
  2794. #if JUCE_X11_SUPPORTS_XEMBED
  2795. if (! juce_handleXEmbedEvent (nullptr, &event))
  2796. #endif
  2797. {
  2798. if (auto* peer = LinuxComponentPeer::getPeerFor (event.xany.window))
  2799. peer->handleWindowMessage (event);
  2800. }
  2801. }
  2802. else if (event.xany.type == KeymapNotify)
  2803. {
  2804. auto& keymapEvent = (const XKeymapEvent&) event.xkeymap;
  2805. memcpy (Keys::keyStates, keymapEvent.key_vector, 32);
  2806. }
  2807. }
  2808. }
  2809. struct WindowingCallbackInitialiser
  2810. {
  2811. WindowingCallbackInitialiser()
  2812. {
  2813. dispatchWindowMessage = WindowingHelpers::windowMessageReceive;
  2814. }
  2815. };
  2816. static WindowingCallbackInitialiser windowingInitialiser;
  2817. //==============================================================================
  2818. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess()
  2819. {
  2820. return LinuxComponentPeer::isActiveApplication;
  2821. }
  2822. // N/A on Linux as far as I know.
  2823. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2824. JUCE_API void JUCE_CALLTYPE Process::hide() {}
  2825. //==============================================================================
  2826. void Desktop::setKioskComponent (Component* comp, bool enableOrDisable, bool /* allowMenusAndBars */)
  2827. {
  2828. if (enableOrDisable)
  2829. comp->setBounds (getDisplays().getMainDisplay().totalArea);
  2830. }
  2831. void Desktop::allowedOrientationsChanged() {}
  2832. //==============================================================================
  2833. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  2834. {
  2835. return new LinuxComponentPeer (*this, styleFlags, (Window) nativeWindowToAttachTo);
  2836. }
  2837. //==============================================================================
  2838. void Displays::findDisplays (float masterScale)
  2839. {
  2840. ScopedXDisplay xDisplay;
  2841. if (auto display = xDisplay.display)
  2842. {
  2843. Atom hints = Atoms::getIfExists (display, "_NET_WORKAREA");
  2844. auto getWorkAreaPropertyData = [&] (int screenNum) -> unsigned char*
  2845. {
  2846. if (hints != None)
  2847. {
  2848. GetXProperty prop (display, RootWindow (display, screenNum), hints, 0, 4, false, XA_CARDINAL);
  2849. if (prop.success && prop.actualType == XA_CARDINAL && prop.actualFormat == 32 && prop.numItems == 4)
  2850. return prop.data;
  2851. }
  2852. return nullptr;
  2853. };
  2854. #if JUCE_USE_XRANDR
  2855. {
  2856. int major_opcode, first_event, first_error;
  2857. if (XQueryExtension (display, "RANDR", &major_opcode, &first_event, &first_error))
  2858. {
  2859. auto& xrandr = XRandrWrapper::getInstance();
  2860. auto numMonitors = ScreenCount (display);
  2861. auto mainDisplay = xrandr.getOutputPrimary (display, RootWindow (display, 0));
  2862. for (int i = 0; i < numMonitors; ++i)
  2863. {
  2864. if (getWorkAreaPropertyData (i) == nullptr)
  2865. continue;
  2866. if (auto* screens = xrandr.getScreenResources (display, RootWindow (display, i)))
  2867. {
  2868. for (int j = 0; j < screens->noutput; ++j)
  2869. {
  2870. if (screens->outputs[j])
  2871. {
  2872. // Xrandr on the raspberry pi fails to determine the main display (mainDisplay == 0)!
  2873. // Detect this edge case and make the first found display the main display
  2874. if (! mainDisplay)
  2875. mainDisplay = screens->outputs[j];
  2876. if (auto* output = xrandr.getOutputInfo (display, screens, screens->outputs[j]))
  2877. {
  2878. if (output->crtc)
  2879. {
  2880. if (auto* crtc = xrandr.getCrtcInfo (display, screens, output->crtc))
  2881. {
  2882. Display d;
  2883. d.totalArea = Rectangle<int> (crtc->x, crtc->y,
  2884. (int) crtc->width, (int) crtc->height);
  2885. d.isMain = (mainDisplay == screens->outputs[j]) && (i == 0);
  2886. d.dpi = getDisplayDPI (display, 0);
  2887. // The raspberry pi returns a zero sized display, so we need to guard for divide-by-zero
  2888. if (output->mm_width > 0 && output->mm_height > 0)
  2889. d.dpi = ((static_cast<double> (crtc->width) * 25.4 * 0.5) / static_cast<double> (output->mm_width))
  2890. + ((static_cast<double> (crtc->height) * 25.4 * 0.5) / static_cast<double> (output->mm_height));
  2891. double scale = getScaleForDisplay (output->name, d.dpi);
  2892. scale = (scale <= 0.1 ? 1.0 : scale);
  2893. d.scale = masterScale * scale;
  2894. if (d.isMain)
  2895. displays.insert (0, d);
  2896. else
  2897. displays.add (d);
  2898. xrandr.freeCrtcInfo (crtc);
  2899. }
  2900. }
  2901. xrandr.freeOutputInfo (output);
  2902. }
  2903. }
  2904. }
  2905. xrandr.freeScreenResources (screens);
  2906. }
  2907. }
  2908. if (! displays.isEmpty() && ! displays.getReference (0).isMain)
  2909. displays.getReference (0).isMain = true;
  2910. }
  2911. }
  2912. if (displays.isEmpty())
  2913. #endif
  2914. #if JUCE_USE_XINERAMA
  2915. {
  2916. auto screens = XineramaQueryDisplays (display);
  2917. int numMonitors = screens.size();
  2918. for (int index = 0; index < numMonitors; ++index)
  2919. {
  2920. for (int j = numMonitors; --j >= 0;)
  2921. {
  2922. if (screens[j].screen_number == index)
  2923. {
  2924. Display d;
  2925. d.totalArea = Rectangle<int> (screens[j].x_org,
  2926. screens[j].y_org,
  2927. screens[j].width,
  2928. screens[j].height);
  2929. d.isMain = (index == 0);
  2930. d.scale = masterScale;
  2931. d.dpi = getDisplayDPI (display, 0); // (all screens share the same DPI)
  2932. displays.add (d);
  2933. }
  2934. }
  2935. }
  2936. }
  2937. if (displays.isEmpty())
  2938. #endif
  2939. {
  2940. if (hints != None)
  2941. {
  2942. auto numMonitors = ScreenCount (display);
  2943. for (int i = 0; i < numMonitors; ++i)
  2944. {
  2945. if (auto* positionData = getWorkAreaPropertyData (i))
  2946. {
  2947. std::array<long, 4> position;
  2948. for (auto& p : position)
  2949. {
  2950. memcpy (&p, positionData, sizeof (long));
  2951. positionData += sizeof (long);
  2952. }
  2953. Display d;
  2954. d.totalArea = Rectangle<int> ((int) position[0], (int) position[1],
  2955. (int) position[2], (int) position[3]);
  2956. d.isMain = displays.isEmpty();
  2957. d.scale = masterScale;
  2958. d.dpi = getDisplayDPI (display, i);
  2959. displays.add (d);
  2960. }
  2961. }
  2962. }
  2963. if (displays.isEmpty())
  2964. {
  2965. Display d;
  2966. d.totalArea = Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  2967. DisplayHeight (display, DefaultScreen (display)));
  2968. d.isMain = true;
  2969. d.scale = masterScale;
  2970. d.dpi = getDisplayDPI (display, 0);
  2971. displays.add (d);
  2972. }
  2973. }
  2974. for (auto& d : displays)
  2975. d.userArea = d.totalArea; // JUCE currently does not support requesting the user area on Linux
  2976. updateToLogical();
  2977. }
  2978. }
  2979. //==============================================================================
  2980. bool MouseInputSource::SourceList::addSource()
  2981. {
  2982. if (sources.isEmpty())
  2983. {
  2984. addSource (0, MouseInputSource::InputSourceType::mouse);
  2985. return true;
  2986. }
  2987. return false;
  2988. }
  2989. bool MouseInputSource::SourceList::canUseTouch()
  2990. {
  2991. return false;
  2992. }
  2993. bool Desktop::canUseSemiTransparentWindows() noexcept
  2994. {
  2995. #if JUCE_USE_XRENDER
  2996. auto display = XWindowSystem::getInstance()->displayRef();
  2997. if (XRender::hasCompositingWindowManager (display))
  2998. {
  2999. int matchedDepth = 0, desiredDepth = 32;
  3000. return Visuals::findVisualFormat (display, desiredDepth, matchedDepth) != 0
  3001. && matchedDepth == desiredDepth;
  3002. }
  3003. #endif
  3004. return false;
  3005. }
  3006. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3007. {
  3008. ScopedXDisplay xDisplay;
  3009. auto display = xDisplay.display;
  3010. if (display == nullptr)
  3011. return {};
  3012. Window root, child;
  3013. int x, y, winx, winy;
  3014. unsigned int mask;
  3015. ScopedXLock xlock (display);
  3016. if (XQueryPointer (display,
  3017. RootWindow (display, DefaultScreen (display)),
  3018. &root, &child,
  3019. &x, &y, &winx, &winy, &mask) == False)
  3020. {
  3021. // Pointer not on the default screen
  3022. x = y = -1;
  3023. }
  3024. return Desktop::getInstance().getDisplays().physicalToLogical (Point<float> ((float) x, (float) y));
  3025. }
  3026. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3027. {
  3028. ScopedXDisplay xDisplay;
  3029. if (auto display = xDisplay.display)
  3030. {
  3031. ScopedXLock xlock (display);
  3032. Window root = RootWindow (display, DefaultScreen (display));
  3033. newPosition = Desktop::getInstance().getDisplays().logicalToPhysical (newPosition);
  3034. XWarpPointer (display, None, root, 0, 0, 0, 0, roundToInt (newPosition.getX()), roundToInt (newPosition.getY()));
  3035. }
  3036. }
  3037. double Desktop::getDefaultMasterScale()
  3038. {
  3039. return 1.0;
  3040. }
  3041. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  3042. {
  3043. return upright;
  3044. }
  3045. //==============================================================================
  3046. static bool screenSaverAllowed = true;
  3047. void Desktop::setScreenSaverEnabled (bool isEnabled)
  3048. {
  3049. if (screenSaverAllowed != isEnabled)
  3050. {
  3051. screenSaverAllowed = isEnabled;
  3052. ScopedXDisplay xDisplay;
  3053. if (auto display = xDisplay.display)
  3054. {
  3055. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  3056. static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
  3057. if (xScreenSaverSuspend == nullptr)
  3058. if (void* h = dlopen ("libXss.so.1", RTLD_GLOBAL | RTLD_NOW))
  3059. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  3060. ScopedXLock xlock (display);
  3061. if (xScreenSaverSuspend != nullptr)
  3062. xScreenSaverSuspend (display, ! isEnabled);
  3063. }
  3064. }
  3065. }
  3066. bool Desktop::isScreenSaverEnabled()
  3067. {
  3068. return screenSaverAllowed;
  3069. }
  3070. //==============================================================================
  3071. Image juce_createIconForFile (const File& /* file */)
  3072. {
  3073. return {};
  3074. }
  3075. //==============================================================================
  3076. void LookAndFeel::playAlertSound()
  3077. {
  3078. std::cout << "\a" << std::flush;
  3079. }
  3080. //==============================================================================
  3081. Rectangle<int> juce_LinuxScaledToPhysicalBounds (ComponentPeer* peer, Rectangle<int> bounds)
  3082. {
  3083. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3084. bounds *= linuxPeer->getPlatformScaleFactor();
  3085. return bounds;
  3086. }
  3087. void juce_LinuxAddRepaintListener (ComponentPeer* peer, Component* dummy)
  3088. {
  3089. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3090. linuxPeer->addOpenGLRepaintListener (dummy);
  3091. }
  3092. void juce_LinuxRemoveRepaintListener (ComponentPeer* peer, Component* dummy)
  3093. {
  3094. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3095. linuxPeer->removeOpenGLRepaintListener (dummy);
  3096. }
  3097. unsigned long juce_createKeyProxyWindow (ComponentPeer* peer)
  3098. {
  3099. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3100. return linuxPeer->createKeyProxy();
  3101. return 0;
  3102. }
  3103. void juce_deleteKeyProxyWindow (ComponentPeer* peer)
  3104. {
  3105. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3106. linuxPeer->deleteKeyProxy();
  3107. }
  3108. //==============================================================================
  3109. #if JUCE_MODAL_LOOPS_PERMITTED
  3110. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3111. const String& title, const String& message,
  3112. Component* /* associatedComponent */)
  3113. {
  3114. AlertWindow::showMessageBox (iconType, title, message);
  3115. }
  3116. #endif
  3117. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3118. const String& title, const String& message,
  3119. Component* associatedComponent,
  3120. ModalComponentManager::Callback* callback)
  3121. {
  3122. AlertWindow::showMessageBoxAsync (iconType, title, message, String(), associatedComponent, callback);
  3123. }
  3124. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3125. const String& title, const String& message,
  3126. Component* associatedComponent,
  3127. ModalComponentManager::Callback* callback)
  3128. {
  3129. return AlertWindow::showOkCancelBox (iconType, title, message, String(), String(),
  3130. associatedComponent, callback);
  3131. }
  3132. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3133. const String& title, const String& message,
  3134. Component* associatedComponent,
  3135. ModalComponentManager::Callback* callback)
  3136. {
  3137. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  3138. String(), String(), String(),
  3139. associatedComponent, callback);
  3140. }
  3141. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  3142. const String& title, const String& message,
  3143. Component* associatedComponent,
  3144. ModalComponentManager::Callback* callback)
  3145. {
  3146. return AlertWindow::showOkCancelBox (iconType, title, message, TRANS ("Yes"), TRANS ("No"),
  3147. associatedComponent, callback);
  3148. }
  3149. //============================== X11 - MouseCursor =============================
  3150. std::map<Cursor, Display*> cursorMap;
  3151. void* CustomMouseCursorInfo::create() const
  3152. {
  3153. ScopedXDisplay xDisplay;
  3154. auto display = xDisplay.display;
  3155. if (display == nullptr)
  3156. return nullptr;
  3157. ScopedXLock xlock (display);
  3158. auto imageW = (unsigned int) image.getWidth();
  3159. auto imageH = (unsigned int) image.getHeight();
  3160. int hotspotX = hotspot.x;
  3161. int hotspotY = hotspot.y;
  3162. #if JUCE_USE_XCURSOR
  3163. {
  3164. using tXcursorSupportsARGB = XcursorBool (*) (Display*);
  3165. using tXcursorImageCreate = XcursorImage* (*) (int, int);
  3166. using tXcursorImageDestroy = void (*) (XcursorImage*);
  3167. using tXcursorImageLoadCursor = Cursor (*) (Display*, const XcursorImage*);
  3168. static tXcursorSupportsARGB xcursorSupportsARGB = nullptr;
  3169. static tXcursorImageCreate xcursorImageCreate = nullptr;
  3170. static tXcursorImageDestroy xcursorImageDestroy = nullptr;
  3171. static tXcursorImageLoadCursor xcursorImageLoadCursor = nullptr;
  3172. static bool hasBeenLoaded = false;
  3173. if (! hasBeenLoaded)
  3174. {
  3175. hasBeenLoaded = true;
  3176. if (void* h = dlopen ("libXcursor.so.1", RTLD_GLOBAL | RTLD_NOW))
  3177. {
  3178. xcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  3179. xcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  3180. xcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  3181. xcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  3182. if (xcursorSupportsARGB == nullptr || xcursorImageCreate == nullptr
  3183. || xcursorImageLoadCursor == nullptr || xcursorImageDestroy == nullptr
  3184. || ! xcursorSupportsARGB (display))
  3185. xcursorSupportsARGB = nullptr;
  3186. }
  3187. }
  3188. if (xcursorSupportsARGB != nullptr)
  3189. {
  3190. if (XcursorImage* xcImage = xcursorImageCreate ((int) imageW, (int) imageH))
  3191. {
  3192. xcImage->xhot = (XcursorDim) hotspotX;
  3193. xcImage->yhot = (XcursorDim) hotspotY;
  3194. XcursorPixel* dest = xcImage->pixels;
  3195. for (int y = 0; y < (int) imageH; ++y)
  3196. for (int x = 0; x < (int) imageW; ++x)
  3197. *dest++ = image.getPixelAt (x, y).getARGB();
  3198. void* result = (void*) xcursorImageLoadCursor (display, xcImage);
  3199. xcursorImageDestroy (xcImage);
  3200. if (result != nullptr)
  3201. {
  3202. cursorMap[(Cursor) result] = display;
  3203. return result;
  3204. }
  3205. }
  3206. }
  3207. }
  3208. #endif
  3209. Window root = RootWindow (display, DefaultScreen (display));
  3210. unsigned int cursorW, cursorH;
  3211. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  3212. return nullptr;
  3213. Image im (Image::ARGB, (int) cursorW, (int) cursorH, true);
  3214. {
  3215. Graphics g (im);
  3216. if (imageW > cursorW || imageH > cursorH)
  3217. {
  3218. hotspotX = (hotspotX * (int) cursorW) / (int) imageW;
  3219. hotspotY = (hotspotY * (int) cursorH) / (int) imageH;
  3220. g.drawImage (image, Rectangle<float> ((float) imageW, (float) imageH),
  3221. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize);
  3222. }
  3223. else
  3224. {
  3225. g.drawImageAt (image, 0, 0);
  3226. }
  3227. }
  3228. const unsigned int stride = (cursorW + 7) >> 3;
  3229. HeapBlock<char> maskPlane, sourcePlane;
  3230. maskPlane.calloc (stride * cursorH);
  3231. sourcePlane.calloc (stride * cursorH);
  3232. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  3233. for (int y = (int) cursorH; --y >= 0;)
  3234. {
  3235. for (int x = (int) cursorW; --x >= 0;)
  3236. {
  3237. auto mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  3238. auto offset = (unsigned int) y * stride + ((unsigned int) x >> 3);
  3239. auto c = im.getPixelAt (x, y);
  3240. if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
  3241. if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
  3242. }
  3243. }
  3244. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3245. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3246. XColor white, black;
  3247. black.red = black.green = black.blue = 0;
  3248. white.red = white.green = white.blue = 0xffff;
  3249. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black,
  3250. (unsigned int) hotspotX, (unsigned int) hotspotY);
  3251. XFreePixmap (display, sourcePixmap);
  3252. XFreePixmap (display, maskPixmap);
  3253. cursorMap[(Cursor) result] = display;
  3254. return result;
  3255. }
  3256. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool)
  3257. {
  3258. if (cursorHandle != nullptr)
  3259. {
  3260. ScopedXDisplay xDisplay;
  3261. if (auto display = xDisplay.display)
  3262. {
  3263. ScopedXLock xlock (display);
  3264. XFreeCursor (display, (Cursor) cursorHandle);
  3265. }
  3266. }
  3267. }
  3268. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  3269. {
  3270. ScopedXDisplay xDisplay;
  3271. auto display = xDisplay.display;
  3272. if (display == nullptr)
  3273. return None;
  3274. unsigned int shape;
  3275. switch (type)
  3276. {
  3277. case NormalCursor:
  3278. case ParentCursor: return None; // Use parent cursor
  3279. case NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), {}).create();
  3280. case WaitCursor: shape = XC_watch; break;
  3281. case IBeamCursor: shape = XC_xterm; break;
  3282. case PointingHandCursor: shape = XC_hand2; break;
  3283. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  3284. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  3285. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  3286. case TopEdgeResizeCursor: shape = XC_top_side; break;
  3287. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  3288. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  3289. case RightEdgeResizeCursor: shape = XC_right_side; break;
  3290. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  3291. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  3292. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  3293. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  3294. case CrosshairCursor: shape = XC_crosshair; break;
  3295. case DraggingHandCursor: return createDraggingHandCursor();
  3296. case CopyingCursor:
  3297. {
  3298. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3299. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0, 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  3300. 78,133,218,215,137,31,82,154,100,200,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,
  3301. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3302. const int copyCursorSize = 119;
  3303. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), { 1, 3 }).create();
  3304. }
  3305. default:
  3306. jassertfalse;
  3307. return None;
  3308. }
  3309. ScopedXLock xlock (display);
  3310. auto* result = (void*) XCreateFontCursor (display, shape);
  3311. cursorMap[(Cursor) result] = display;
  3312. return result;
  3313. }
  3314. void MouseCursor::showInWindow (ComponentPeer* peer) const
  3315. {
  3316. if (auto* lp = dynamic_cast<LinuxComponentPeer*> (peer))
  3317. {
  3318. ScopedXDisplay xDisplay;
  3319. if (cursorHandle != nullptr && xDisplay.display != cursorMap[(Cursor) getHandle()])
  3320. {
  3321. auto oldHandle = (Cursor) getHandle();
  3322. if (auto* customInfo = cursorHandle->getCustomInfo())
  3323. cursorHandle->setHandle (customInfo->create());
  3324. else
  3325. cursorHandle->setHandle (createStandardMouseCursor (cursorHandle->getType()));
  3326. cursorMap.erase (oldHandle);
  3327. }
  3328. lp->showMouseCursor ((Cursor) getHandle());
  3329. }
  3330. }
  3331. //=================================== X11 - DND ================================
  3332. static LinuxComponentPeer* getPeerForDragEvent (Component* sourceComp)
  3333. {
  3334. if (sourceComp == nullptr)
  3335. if (auto* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  3336. sourceComp = draggingSource->getComponentUnderMouse();
  3337. if (sourceComp != nullptr)
  3338. if (auto* lp = dynamic_cast<LinuxComponentPeer*> (sourceComp->getPeer()))
  3339. return lp;
  3340. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  3341. return nullptr;
  3342. }
  3343. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles,
  3344. Component* sourceComp, std::function<void()> callback)
  3345. {
  3346. if (files.isEmpty())
  3347. return false;
  3348. if (auto* lp = getPeerForDragEvent (sourceComp))
  3349. return lp->externalDragFileInit (files, canMoveFiles, callback);
  3350. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3351. jassertfalse;
  3352. return false;
  3353. }
  3354. bool DragAndDropContainer::performExternalDragDropOfText (const String& text, Component* sourceComp,
  3355. std::function<void()> callback)
  3356. {
  3357. if (text.isEmpty())
  3358. return false;
  3359. if (auto* lp = getPeerForDragEvent (sourceComp))
  3360. return lp->externalDragTextInit (text, callback);
  3361. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3362. jassertfalse;
  3363. return false;
  3364. }
  3365. } // namespace juce