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.

4152 lines
147KB

  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. }
  794. }
  795. }
  796. }
  797. // If no scale factor is set by GNOME or Ubuntu then calculate from monitor dpi
  798. // We use the same approach as chromium which simply divides the dpi by 96
  799. // and then rounds the result
  800. return round (dpi / 96.0);
  801. }
  802. //=============================== X11 - Pixmap =================================
  803. namespace PixmapHelpers
  804. {
  805. Pixmap createColourPixmapFromImage (::Display* display, const Image& image)
  806. {
  807. ScopedXLock xlock (display);
  808. auto width = (unsigned int) image.getWidth();
  809. auto height = (unsigned int) image.getHeight();
  810. HeapBlock<uint32> colour (width * height);
  811. int index = 0;
  812. for (int y = 0; y < (int) height; ++y)
  813. for (int x = 0; x < (int) width; ++x)
  814. colour[index++] = image.getPixelAt (x, y).getARGB();
  815. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  816. 0, reinterpret_cast<char*> (colour.getData()),
  817. width, height, 32, 0);
  818. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  819. width, height, 24);
  820. GC gc = XCreateGC (display, pixmap, 0, nullptr);
  821. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  822. XFreeGC (display, gc);
  823. return pixmap;
  824. }
  825. Pixmap createMaskPixmapFromImage (::Display* display, const Image& image)
  826. {
  827. ScopedXLock xlock (display);
  828. auto width = (unsigned int) image.getWidth();
  829. auto height = (unsigned int) image.getHeight();
  830. auto stride = (width + 7) >> 3;
  831. HeapBlock<char> mask;
  832. mask.calloc (stride * height);
  833. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  834. for (unsigned int y = 0; y < height; ++y)
  835. {
  836. for (unsigned int x = 0; x < width; ++x)
  837. {
  838. auto bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  839. const unsigned int offset = y * stride + (x >> 3);
  840. if (image.getPixelAt ((int) x, (int) y).getAlpha() >= 128)
  841. mask[offset] |= bit;
  842. }
  843. }
  844. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  845. mask.getData(), width, height, 1, 0, 1);
  846. }
  847. }
  848. static void* createDraggingHandCursor()
  849. {
  850. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  851. 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,
  852. 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 };
  853. size_t dragHandDataSize = 99;
  854. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), { 8, 7 }).create();
  855. }
  856. //==============================================================================
  857. static int numAlwaysOnTopPeers = 0;
  858. bool juce_areThereAnyAlwaysOnTopWindows()
  859. {
  860. return numAlwaysOnTopPeers > 0;
  861. }
  862. //==============================================================================
  863. class LinuxComponentPeer : public ComponentPeer
  864. {
  865. public:
  866. LinuxComponentPeer (Component& comp, int windowStyleFlags, Window parentToAddTo)
  867. : ComponentPeer (comp, windowStyleFlags),
  868. isAlwaysOnTop (comp.isAlwaysOnTop())
  869. {
  870. // it's dangerous to create a window on a thread other than the message thread..
  871. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  872. display = XWindowSystem::getInstance()->displayRef();
  873. atoms.reset (new Atoms (display));
  874. dragState.reset (new DragState (display));
  875. repainter.reset (new LinuxRepaintManager (*this, display));
  876. if (isAlwaysOnTop)
  877. ++numAlwaysOnTopPeers;
  878. createWindow (parentToAddTo);
  879. setTitle (component.getName());
  880. getNativeRealtimeModifiers = []
  881. {
  882. ScopedXDisplay xDisplay;
  883. if (auto d = xDisplay.display)
  884. {
  885. Window root, child;
  886. int x, y, winx, winy;
  887. unsigned int mask;
  888. int mouseMods = 0;
  889. ScopedXLock xlock (d);
  890. if (XQueryPointer (d, RootWindow (d, DefaultScreen (d)),
  891. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  892. {
  893. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  894. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  895. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  896. }
  897. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  898. }
  899. return ModifierKeys::currentModifiers;
  900. };
  901. }
  902. ~LinuxComponentPeer() override
  903. {
  904. // it's dangerous to delete a window on a thread other than the message thread..
  905. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  906. #if JUCE_X11_SUPPORTS_XEMBED
  907. juce_handleXEmbedEvent (this, nullptr);
  908. #endif
  909. deleteIconPixmaps();
  910. destroyWindow();
  911. windowH = 0;
  912. if (isAlwaysOnTop)
  913. --numAlwaysOnTopPeers;
  914. // delete before display
  915. repainter = nullptr;
  916. display = XWindowSystem::getInstance()->displayUnref();
  917. }
  918. //==============================================================================
  919. void* getNativeHandle() const override
  920. {
  921. return (void*) windowH;
  922. }
  923. static LinuxComponentPeer* getPeerFor (Window windowHandle) noexcept
  924. {
  925. XPointer peer = nullptr;
  926. if (display != nullptr)
  927. {
  928. ScopedXLock xlock (display);
  929. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  930. if (peer != nullptr && ! ComponentPeer::isValidPeer (reinterpret_cast<LinuxComponentPeer*> (peer)))
  931. peer = nullptr;
  932. }
  933. return reinterpret_cast<LinuxComponentPeer*> (peer);
  934. }
  935. void setVisible (bool shouldBeVisible) override
  936. {
  937. ScopedXLock xlock (display);
  938. if (shouldBeVisible)
  939. XMapWindow (display, windowH);
  940. else
  941. XUnmapWindow (display, windowH);
  942. }
  943. void setTitle (const String& title) override
  944. {
  945. XTextProperty nameProperty;
  946. char* strings[] = { const_cast<char*> (title.toRawUTF8()) };
  947. ScopedXLock xlock (display);
  948. if (XStringListToTextProperty (strings, 1, &nameProperty))
  949. {
  950. XSetWMName (display, windowH, &nameProperty);
  951. XSetWMIconName (display, windowH, &nameProperty);
  952. XFree (nameProperty.value);
  953. }
  954. }
  955. void updateScaleFactorFromNewBounds (const Rectangle<int>& newBounds, bool isPhysical)
  956. {
  957. Point<int> translation = (parentWindow != 0 ? getScreenPosition (isPhysical) : Point<int>());
  958. auto newScaleFactor = Desktop::getInstance().getDisplays().findDisplayForRect (newBounds.translated (translation.x, translation.y), isPhysical).scale
  959. / Desktop::getInstance().getGlobalScaleFactor();
  960. if (! approximatelyEqual (newScaleFactor, currentScaleFactor))
  961. {
  962. currentScaleFactor = newScaleFactor;
  963. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (currentScaleFactor); });
  964. }
  965. }
  966. void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
  967. {
  968. if (fullScreen && ! isNowFullScreen)
  969. {
  970. // When transitioning back from fullscreen, we might need to remove
  971. // the FULLSCREEN window property
  972. Atom fs = Atoms::getIfExists (display, "_NET_WM_STATE_FULLSCREEN");
  973. if (fs != None)
  974. {
  975. Window root = RootWindow (display, DefaultScreen (display));
  976. XClientMessageEvent clientMsg;
  977. clientMsg.display = display;
  978. clientMsg.window = windowH;
  979. clientMsg.type = ClientMessage;
  980. clientMsg.format = 32;
  981. clientMsg.message_type = atoms->windowState;
  982. clientMsg.data.l[0] = 0; // Remove
  983. clientMsg.data.l[1] = (long) fs;
  984. clientMsg.data.l[2] = 0;
  985. clientMsg.data.l[3] = 1; // Normal Source
  986. ScopedXLock xlock (display);
  987. XSendEvent (display, root, false,
  988. SubstructureRedirectMask | SubstructureNotifyMask,
  989. (XEvent*) &clientMsg);
  990. }
  991. }
  992. fullScreen = isNowFullScreen;
  993. if (windowH != 0)
  994. {
  995. bounds = newBounds.withSize (jmax (1, newBounds.getWidth()),
  996. jmax (1, newBounds.getHeight()));
  997. updateScaleFactorFromNewBounds (bounds, false);
  998. auto physicalBounds = (parentWindow == 0 ? Desktop::getInstance().getDisplays().logicalToPhysical (bounds)
  999. : bounds * currentScaleFactor);
  1000. WeakReference<Component> deletionChecker (&component);
  1001. ScopedXLock xlock (display);
  1002. auto* hints = XAllocSizeHints();
  1003. hints->flags = USSize | USPosition;
  1004. hints->x = physicalBounds.getX();
  1005. hints->y = physicalBounds.getY();
  1006. hints->width = physicalBounds.getWidth();
  1007. hints->height = physicalBounds.getHeight();
  1008. if ((getStyleFlags() & windowIsResizable) == 0)
  1009. {
  1010. hints->min_width = hints->max_width = hints->width;
  1011. hints->min_height = hints->max_height = hints->height;
  1012. hints->flags |= PMinSize | PMaxSize;
  1013. }
  1014. XSetWMNormalHints (display, windowH, hints);
  1015. XFree (hints);
  1016. XMoveResizeWindow (display, windowH,
  1017. physicalBounds.getX() - windowBorder.getLeft(),
  1018. physicalBounds.getY() - windowBorder.getTop(),
  1019. (unsigned int) physicalBounds.getWidth(),
  1020. (unsigned int) physicalBounds.getHeight());
  1021. if (deletionChecker != nullptr)
  1022. {
  1023. updateBorderSize();
  1024. handleMovedOrResized();
  1025. }
  1026. }
  1027. }
  1028. Point<int> getScreenPosition (bool physical) const
  1029. {
  1030. if (physical)
  1031. return Desktop::getInstance().getDisplays().logicalToPhysical (bounds.getTopLeft());
  1032. return bounds.getTopLeft();
  1033. }
  1034. Rectangle<int> getBounds() const override { return bounds; }
  1035. using ComponentPeer::localToGlobal;
  1036. Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getScreenPosition (false).toFloat(); }
  1037. using ComponentPeer::globalToLocal;
  1038. Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getScreenPosition (false).toFloat(); }
  1039. void setAlpha (float /* newAlpha */) override
  1040. {
  1041. //xxx todo!
  1042. }
  1043. StringArray getAvailableRenderingEngines() override
  1044. {
  1045. return StringArray ("Software Renderer");
  1046. }
  1047. void setMinimised (bool shouldBeMinimised) override
  1048. {
  1049. if (shouldBeMinimised)
  1050. {
  1051. Window root = RootWindow (display, DefaultScreen (display));
  1052. XClientMessageEvent clientMsg;
  1053. clientMsg.display = display;
  1054. clientMsg.window = windowH;
  1055. clientMsg.type = ClientMessage;
  1056. clientMsg.format = 32;
  1057. clientMsg.message_type = atoms->changeState;
  1058. clientMsg.data.l[0] = IconicState;
  1059. ScopedXLock xlock (display);
  1060. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  1061. }
  1062. else
  1063. {
  1064. setVisible (true);
  1065. }
  1066. }
  1067. bool isMinimised() const override
  1068. {
  1069. ScopedXLock xlock (display);
  1070. GetXProperty prop (display, windowH, atoms->state, 0, 64, false, atoms->state);
  1071. if (prop.success && prop.actualType == atoms->state
  1072. && prop.actualFormat == 32 && prop.numItems > 0)
  1073. {
  1074. unsigned long state;
  1075. memcpy (&state, prop.data, sizeof (unsigned long));
  1076. return state == IconicState;
  1077. }
  1078. return false;
  1079. }
  1080. void setFullScreen (bool shouldBeFullScreen) override
  1081. {
  1082. auto r = lastNonFullscreenBounds; // (get a copy of this before de-minimising)
  1083. setMinimised (false);
  1084. if (fullScreen != shouldBeFullScreen)
  1085. {
  1086. if (shouldBeFullScreen)
  1087. r = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  1088. if (! r.isEmpty())
  1089. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  1090. component.repaint();
  1091. }
  1092. }
  1093. bool isFullScreen() const override
  1094. {
  1095. return fullScreen;
  1096. }
  1097. bool isChildWindowOf (Window possibleParent) const
  1098. {
  1099. Window* windowList = nullptr;
  1100. uint32 windowListSize = 0;
  1101. Window parent, root;
  1102. ScopedXLock xlock (display);
  1103. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  1104. {
  1105. if (windowList != nullptr)
  1106. XFree (windowList);
  1107. return parent == possibleParent;
  1108. }
  1109. return false;
  1110. }
  1111. bool isParentWindowOf (Window possibleChild) const
  1112. {
  1113. if (windowH != 0 && possibleChild != 0)
  1114. {
  1115. if (possibleChild == windowH)
  1116. return true;
  1117. Window* windowList = nullptr;
  1118. uint32 windowListSize = 0;
  1119. Window parent, root;
  1120. ScopedXLock xlock (display);
  1121. if (XQueryTree (display, possibleChild, &root, &parent, &windowList, &windowListSize) != 0)
  1122. {
  1123. if (windowList != nullptr)
  1124. XFree (windowList);
  1125. if (parent == root)
  1126. return false;
  1127. return isParentWindowOf (parent);
  1128. }
  1129. }
  1130. return false;
  1131. }
  1132. bool isFrontWindow() const
  1133. {
  1134. Window* windowList = nullptr;
  1135. uint32 windowListSize = 0;
  1136. bool result = false;
  1137. ScopedXLock xlock (display);
  1138. Window parent, root = RootWindow (display, DefaultScreen (display));
  1139. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  1140. {
  1141. for (int i = (int) windowListSize; --i >= 0;)
  1142. {
  1143. if (auto* peer = LinuxComponentPeer::getPeerFor (windowList[i]))
  1144. {
  1145. result = (peer == this);
  1146. break;
  1147. }
  1148. }
  1149. }
  1150. if (windowList != nullptr)
  1151. XFree (windowList);
  1152. return result;
  1153. }
  1154. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  1155. {
  1156. if (! bounds.withZeroOrigin().contains (localPos))
  1157. return false;
  1158. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1159. {
  1160. auto* c = Desktop::getInstance().getComponent (i);
  1161. if (c == &component)
  1162. break;
  1163. if (! c->isVisible())
  1164. continue;
  1165. if (auto* peer = c->getPeer())
  1166. if (peer->contains (localPos + bounds.getPosition() - peer->getBounds().getPosition(), true))
  1167. return false;
  1168. }
  1169. if (trueIfInAChildWindow)
  1170. return true;
  1171. ::Window root, child;
  1172. int wx, wy;
  1173. unsigned int ww, wh, bw, bitDepth;
  1174. ScopedXLock xlock (display);
  1175. localPos *= currentScaleFactor;
  1176. return XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth)
  1177. && XTranslateCoordinates (display, windowH, windowH, localPos.getX(), localPos.getY(), &wx, &wy, &child)
  1178. && child == None;
  1179. }
  1180. BorderSize<int> getFrameSize() const override
  1181. {
  1182. return {};
  1183. }
  1184. bool setAlwaysOnTop (bool /* alwaysOnTop */) override
  1185. {
  1186. return false;
  1187. }
  1188. void toFront (bool makeActive) override
  1189. {
  1190. if (makeActive)
  1191. {
  1192. setVisible (true);
  1193. grabFocus();
  1194. }
  1195. {
  1196. ScopedXLock xlock (display);
  1197. XEvent ev;
  1198. ev.xclient.type = ClientMessage;
  1199. ev.xclient.serial = 0;
  1200. ev.xclient.send_event = True;
  1201. ev.xclient.message_type = atoms->activeWin;
  1202. ev.xclient.window = windowH;
  1203. ev.xclient.format = 32;
  1204. ev.xclient.data.l[0] = 2;
  1205. ev.xclient.data.l[1] = getUserTime();
  1206. ev.xclient.data.l[2] = 0;
  1207. ev.xclient.data.l[3] = 0;
  1208. ev.xclient.data.l[4] = 0;
  1209. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  1210. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  1211. XSync (display, False);
  1212. }
  1213. handleBroughtToFront();
  1214. }
  1215. void toBehind (ComponentPeer* other) override
  1216. {
  1217. if (auto* otherPeer = dynamic_cast<LinuxComponentPeer*> (other))
  1218. {
  1219. if (otherPeer->styleFlags & windowIsTemporary)
  1220. return;
  1221. setMinimised (false);
  1222. Window newStack[] = { otherPeer->windowH, windowH };
  1223. ScopedXLock xlock (display);
  1224. XRestackWindows (display, newStack, 2);
  1225. }
  1226. else
  1227. jassertfalse; // wrong type of window?
  1228. }
  1229. bool isFocused() const override
  1230. {
  1231. int revert = 0;
  1232. Window focusedWindow = 0;
  1233. ScopedXLock xlock (display);
  1234. XGetInputFocus (display, &focusedWindow, &revert);
  1235. return isParentWindowOf (focusedWindow);
  1236. }
  1237. Window getFocusWindow()
  1238. {
  1239. #if JUCE_X11_SUPPORTS_XEMBED
  1240. if (Window w = (Window) juce_getCurrentFocusWindow (this))
  1241. return w;
  1242. #endif
  1243. return windowH;
  1244. }
  1245. void grabFocus() override
  1246. {
  1247. XWindowAttributes atts;
  1248. ScopedXLock xlock (display);
  1249. if (windowH != 0
  1250. && XGetWindowAttributes (display, windowH, &atts)
  1251. && atts.map_state == IsViewable
  1252. && ! isFocused())
  1253. {
  1254. XSetInputFocus (display, getFocusWindow(), RevertToParent, (::Time) getUserTime());
  1255. isActiveApplication = true;
  1256. }
  1257. }
  1258. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1259. void repaint (const Rectangle<int>& area) override
  1260. {
  1261. repainter->repaint (area.getIntersection (bounds.withZeroOrigin()));
  1262. }
  1263. void performAnyPendingRepaintsNow() override
  1264. {
  1265. repainter->performAnyPendingRepaintsNow();
  1266. }
  1267. void setIcon (const Image& newIcon) override
  1268. {
  1269. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  1270. HeapBlock<unsigned long> data (dataSize);
  1271. int index = 0;
  1272. data[index++] = (unsigned long) newIcon.getWidth();
  1273. data[index++] = (unsigned long) newIcon.getHeight();
  1274. for (int y = 0; y < newIcon.getHeight(); ++y)
  1275. for (int x = 0; x < newIcon.getWidth(); ++x)
  1276. data[index++] = (unsigned long) newIcon.getPixelAt (x, y).getARGB();
  1277. ScopedXLock xlock (display);
  1278. xchangeProperty (windowH, Atoms::getCreating (display, "_NET_WM_ICON"), XA_CARDINAL, 32, data.getData(), dataSize);
  1279. deleteIconPixmaps();
  1280. XWMHints* wmHints = XGetWMHints (display, windowH);
  1281. if (wmHints == nullptr)
  1282. wmHints = XAllocWMHints();
  1283. wmHints->flags |= IconPixmapHint | IconMaskHint;
  1284. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  1285. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  1286. XSetWMHints (display, windowH, wmHints);
  1287. XFree (wmHints);
  1288. XSync (display, False);
  1289. }
  1290. void deleteIconPixmaps()
  1291. {
  1292. ScopedXLock xlock (display);
  1293. if (auto* wmHints = XGetWMHints (display, windowH))
  1294. {
  1295. if ((wmHints->flags & IconPixmapHint) != 0)
  1296. {
  1297. wmHints->flags &= ~IconPixmapHint;
  1298. XFreePixmap (display, wmHints->icon_pixmap);
  1299. }
  1300. if ((wmHints->flags & IconMaskHint) != 0)
  1301. {
  1302. wmHints->flags &= ~IconMaskHint;
  1303. XFreePixmap (display, wmHints->icon_mask);
  1304. }
  1305. XSetWMHints (display, windowH, wmHints);
  1306. XFree (wmHints);
  1307. }
  1308. }
  1309. //==============================================================================
  1310. void handleWindowMessage (XEvent& event)
  1311. {
  1312. switch (event.xany.type)
  1313. {
  1314. case KeyPressEventType: handleKeyPressEvent (event.xkey); break;
  1315. case KeyRelease: handleKeyReleaseEvent (event.xkey); break;
  1316. case ButtonPress: handleButtonPressEvent (event.xbutton); break;
  1317. case ButtonRelease: handleButtonReleaseEvent (event.xbutton); break;
  1318. case MotionNotify: handleMotionNotifyEvent (event.xmotion); break;
  1319. case EnterNotify: handleEnterNotifyEvent (event.xcrossing); break;
  1320. case LeaveNotify: handleLeaveNotifyEvent (event.xcrossing); break;
  1321. case FocusIn: handleFocusInEvent(); break;
  1322. case FocusOut: handleFocusOutEvent(); break;
  1323. case Expose: handleExposeEvent (event.xexpose); break;
  1324. case MappingNotify: handleMappingNotify (event.xmapping); break;
  1325. case ClientMessage: handleClientMessageEvent (event.xclient, event); break;
  1326. case SelectionNotify: handleDragAndDropSelection (event); break;
  1327. case ConfigureNotify: handleConfigureNotifyEvent (event.xconfigure); break;
  1328. case ReparentNotify:
  1329. case GravityNotify: handleGravityNotify(); break;
  1330. case SelectionClear: handleExternalSelectionClear(); break;
  1331. case SelectionRequest: handleExternalSelectionRequest (event); break;
  1332. case CirculateNotify:
  1333. case CreateNotify:
  1334. case DestroyNotify:
  1335. // Think we can ignore these
  1336. break;
  1337. case MapNotify:
  1338. mapped = true;
  1339. handleBroughtToFront();
  1340. break;
  1341. case UnmapNotify:
  1342. mapped = false;
  1343. break;
  1344. default:
  1345. #if JUCE_USE_XSHM
  1346. if (XSHMHelpers::isShmAvailable (display))
  1347. {
  1348. ScopedXLock xlock (display);
  1349. if (event.xany.type == shmCompletionEvent)
  1350. repainter->notifyPaintCompleted();
  1351. }
  1352. #endif
  1353. break;
  1354. }
  1355. }
  1356. void handleKeyPressEvent (XKeyEvent& keyEvent)
  1357. {
  1358. auto oldMods = ModifierKeys::currentModifiers;
  1359. char utf8 [64] = { 0 };
  1360. juce_wchar unicodeChar = 0;
  1361. int keyCode = 0;
  1362. bool keyDownChange = false;
  1363. KeySym sym;
  1364. {
  1365. ScopedXLock xlock (display);
  1366. updateKeyStates ((int) keyEvent.keycode, true);
  1367. String oldLocale (::setlocale (LC_ALL, nullptr));
  1368. ::setlocale (LC_ALL, "");
  1369. XLookupString (&keyEvent, utf8, sizeof (utf8), &sym, nullptr);
  1370. if (oldLocale.isNotEmpty())
  1371. ::setlocale (LC_ALL, oldLocale.toRawUTF8());
  1372. unicodeChar = *CharPointer_UTF8 (utf8);
  1373. keyCode = (int) unicodeChar;
  1374. if (keyCode < 0x20)
  1375. keyCode = (int) XkbKeycodeToKeysym (display, (::KeyCode) keyEvent.keycode, 0, ModifierKeys::currentModifiers.isShiftDown() ? 1 : 0);
  1376. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  1377. }
  1378. bool keyPressed = false;
  1379. if ((sym & 0xff00) == 0xff00 || keyCode == XK_ISO_Left_Tab)
  1380. {
  1381. switch (sym) // Translate keypad
  1382. {
  1383. case XK_KP_Add: keyCode = XK_plus; break;
  1384. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  1385. case XK_KP_Divide: keyCode = XK_slash; break;
  1386. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  1387. case XK_KP_Enter: keyCode = XK_Return; break;
  1388. case XK_KP_Insert: keyCode = XK_Insert; break;
  1389. case XK_Delete:
  1390. case XK_KP_Delete: keyCode = XK_Delete; break;
  1391. case XK_KP_Left: keyCode = XK_Left; break;
  1392. case XK_KP_Right: keyCode = XK_Right; break;
  1393. case XK_KP_Up: keyCode = XK_Up; break;
  1394. case XK_KP_Down: keyCode = XK_Down; break;
  1395. case XK_KP_Home: keyCode = XK_Home; break;
  1396. case XK_KP_End: keyCode = XK_End; break;
  1397. case XK_KP_Page_Down: keyCode = XK_Page_Down; break;
  1398. case XK_KP_Page_Up: keyCode = XK_Page_Up; break;
  1399. case XK_KP_0: keyCode = XK_0; break;
  1400. case XK_KP_1: keyCode = XK_1; break;
  1401. case XK_KP_2: keyCode = XK_2; break;
  1402. case XK_KP_3: keyCode = XK_3; break;
  1403. case XK_KP_4: keyCode = XK_4; break;
  1404. case XK_KP_5: keyCode = XK_5; break;
  1405. case XK_KP_6: keyCode = XK_6; break;
  1406. case XK_KP_7: keyCode = XK_7; break;
  1407. case XK_KP_8: keyCode = XK_8; break;
  1408. case XK_KP_9: keyCode = XK_9; break;
  1409. default: break;
  1410. }
  1411. switch (keyCode)
  1412. {
  1413. case XK_Left:
  1414. case XK_Right:
  1415. case XK_Up:
  1416. case XK_Down:
  1417. case XK_Page_Up:
  1418. case XK_Page_Down:
  1419. case XK_End:
  1420. case XK_Home:
  1421. case XK_Delete:
  1422. case XK_Insert:
  1423. keyPressed = true;
  1424. keyCode = (keyCode & 0xff) | Keys::extendedKeyModifier;
  1425. break;
  1426. case XK_Tab:
  1427. case XK_Return:
  1428. case XK_Escape:
  1429. case XK_BackSpace:
  1430. keyPressed = true;
  1431. keyCode &= 0xff;
  1432. break;
  1433. case XK_ISO_Left_Tab:
  1434. keyPressed = true;
  1435. keyCode = XK_Tab & 0xff;
  1436. break;
  1437. default:
  1438. if (sym >= XK_F1 && sym <= XK_F35)
  1439. {
  1440. keyPressed = true;
  1441. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  1442. }
  1443. break;
  1444. }
  1445. }
  1446. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  1447. keyPressed = true;
  1448. if (oldMods != ModifierKeys::currentModifiers)
  1449. handleModifierKeysChange();
  1450. if (keyDownChange)
  1451. handleKeyUpOrDown (true);
  1452. if (keyPressed)
  1453. handleKeyPress (keyCode, unicodeChar);
  1454. }
  1455. static bool isKeyReleasePartOfAutoRepeat (const XKeyEvent& keyReleaseEvent)
  1456. {
  1457. if (XPending (display))
  1458. {
  1459. XEvent e;
  1460. XPeekEvent (display, &e);
  1461. // Look for a subsequent key-down event with the same timestamp and keycode
  1462. return e.type == KeyPressEventType
  1463. && e.xkey.keycode == keyReleaseEvent.keycode
  1464. && e.xkey.time == keyReleaseEvent.time;
  1465. }
  1466. return false;
  1467. }
  1468. void handleKeyReleaseEvent (const XKeyEvent& keyEvent)
  1469. {
  1470. if (! isKeyReleasePartOfAutoRepeat (keyEvent))
  1471. {
  1472. updateKeyStates ((int) keyEvent.keycode, false);
  1473. KeySym sym;
  1474. {
  1475. ScopedXLock xlock (display);
  1476. sym = XkbKeycodeToKeysym (display, (::KeyCode) keyEvent.keycode, 0, 0);
  1477. }
  1478. auto oldMods = ModifierKeys::currentModifiers;
  1479. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  1480. if (oldMods != ModifierKeys::currentModifiers)
  1481. handleModifierKeysChange();
  1482. if (keyDownChange)
  1483. handleKeyUpOrDown (false);
  1484. }
  1485. }
  1486. template <typename EventType>
  1487. Point<float> getMousePos (const EventType& e) noexcept
  1488. {
  1489. return Point<float> ((float) e.x, (float) e.y) / currentScaleFactor;
  1490. }
  1491. void handleWheelEvent (const XButtonPressedEvent& buttonPressEvent, float amount)
  1492. {
  1493. MouseWheelDetails wheel;
  1494. wheel.deltaX = 0.0f;
  1495. wheel.deltaY = amount;
  1496. wheel.isReversed = false;
  1497. wheel.isSmooth = false;
  1498. wheel.isInertial = false;
  1499. handleMouseWheel (MouseInputSource::InputSourceType::mouse, getMousePos (buttonPressEvent),
  1500. getEventTime (buttonPressEvent), wheel);
  1501. }
  1502. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent, int buttonModifierFlag)
  1503. {
  1504. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (buttonModifierFlag);
  1505. toFront (true);
  1506. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (buttonPressEvent), ModifierKeys::currentModifiers,
  1507. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (buttonPressEvent), {});
  1508. }
  1509. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent)
  1510. {
  1511. updateKeyModifiers ((int) buttonPressEvent.state);
  1512. auto mapIndex = (uint32) (buttonPressEvent.button - Button1);
  1513. if (mapIndex < (uint32) numElementsInArray (pointerMap))
  1514. {
  1515. switch (pointerMap[mapIndex])
  1516. {
  1517. case Keys::WheelUp: handleWheelEvent (buttonPressEvent, 50.0f / 256.0f); break;
  1518. case Keys::WheelDown: handleWheelEvent (buttonPressEvent, -50.0f / 256.0f); break;
  1519. case Keys::LeftButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::leftButtonModifier); break;
  1520. case Keys::RightButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::rightButtonModifier); break;
  1521. case Keys::MiddleButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::middleButtonModifier); break;
  1522. default: break;
  1523. }
  1524. }
  1525. clearLastMousePos();
  1526. }
  1527. void handleButtonReleaseEvent (const XButtonReleasedEvent& buttonRelEvent)
  1528. {
  1529. updateKeyModifiers ((int) buttonRelEvent.state);
  1530. if (parentWindow != 0)
  1531. updateWindowBounds();
  1532. auto mapIndex = (uint32) (buttonRelEvent.button - Button1);
  1533. if (mapIndex < (uint32) numElementsInArray (pointerMap))
  1534. {
  1535. switch (pointerMap[mapIndex])
  1536. {
  1537. case Keys::LeftButton: ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
  1538. case Keys::RightButton: ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
  1539. case Keys::MiddleButton: ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
  1540. default: break;
  1541. }
  1542. }
  1543. if (dragState->dragging)
  1544. handleExternalDragButtonReleaseEvent();
  1545. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (buttonRelEvent), ModifierKeys::currentModifiers,
  1546. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (buttonRelEvent));
  1547. clearLastMousePos();
  1548. }
  1549. void handleMotionNotifyEvent (const XPointerMovedEvent& movedEvent)
  1550. {
  1551. updateKeyModifiers ((int) movedEvent.state);
  1552. lastMousePos = Point<int> (movedEvent.x_root, movedEvent.y_root);
  1553. if (dragState->dragging)
  1554. handleExternalDragMotionNotify();
  1555. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (movedEvent), ModifierKeys::currentModifiers,
  1556. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (movedEvent));
  1557. }
  1558. void handleEnterNotifyEvent (const XEnterWindowEvent& enterEvent)
  1559. {
  1560. if (parentWindow != 0)
  1561. updateWindowBounds();
  1562. clearLastMousePos();
  1563. if (! ModifierKeys::currentModifiers.isAnyMouseButtonDown())
  1564. {
  1565. updateKeyModifiers ((int) enterEvent.state);
  1566. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (enterEvent), ModifierKeys::currentModifiers,
  1567. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (enterEvent));
  1568. }
  1569. }
  1570. void handleLeaveNotifyEvent (const XLeaveWindowEvent& leaveEvent)
  1571. {
  1572. // Suppress the normal leave if we've got a pointer grab, or if
  1573. // it's a bogus one caused by clicking a mouse button when running
  1574. // in a Window manager
  1575. if (((! ModifierKeys::currentModifiers.isAnyMouseButtonDown()) && leaveEvent.mode == NotifyNormal)
  1576. || leaveEvent.mode == NotifyUngrab)
  1577. {
  1578. updateKeyModifiers ((int) leaveEvent.state);
  1579. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (leaveEvent), ModifierKeys::currentModifiers,
  1580. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, getEventTime (leaveEvent));
  1581. }
  1582. }
  1583. void handleFocusInEvent()
  1584. {
  1585. isActiveApplication = true;
  1586. if (isFocused() && ! focused)
  1587. {
  1588. focused = true;
  1589. handleFocusGain();
  1590. }
  1591. }
  1592. void handleFocusOutEvent()
  1593. {
  1594. if (! isFocused() && focused)
  1595. {
  1596. focused = false;
  1597. isActiveApplication = false;
  1598. handleFocusLoss();
  1599. }
  1600. }
  1601. void handleExposeEvent (XExposeEvent& exposeEvent)
  1602. {
  1603. // Batch together all pending expose events
  1604. XEvent nextEvent;
  1605. ScopedXLock xlock (display);
  1606. // if we have opengl contexts then just repaint them all
  1607. // regardless if this is really necessary
  1608. repaintOpenGLContexts();
  1609. if (exposeEvent.window != windowH)
  1610. {
  1611. Window child;
  1612. XTranslateCoordinates (display, exposeEvent.window, windowH,
  1613. exposeEvent.x, exposeEvent.y, &exposeEvent.x, &exposeEvent.y,
  1614. &child);
  1615. }
  1616. // exposeEvent is in local window local coordinates so do not convert with
  1617. // physicalToScaled, but rather use currentScaleFactor
  1618. repaint (Rectangle<int> (exposeEvent.x, exposeEvent.y,
  1619. exposeEvent.width, exposeEvent.height) / currentScaleFactor);
  1620. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  1621. {
  1622. XPeekEvent (display, &nextEvent);
  1623. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent.window)
  1624. break;
  1625. XNextEvent (display, &nextEvent);
  1626. auto& nextExposeEvent = (const XExposeEvent&) nextEvent.xexpose;
  1627. repaint (Rectangle<int> (nextExposeEvent.x, nextExposeEvent.y,
  1628. nextExposeEvent.width, nextExposeEvent.height) / currentScaleFactor);
  1629. }
  1630. }
  1631. void handleConfigureNotifyEvent (XConfigureEvent& confEvent)
  1632. {
  1633. updateWindowBounds();
  1634. updateBorderSize();
  1635. handleMovedOrResized();
  1636. // if the native title bar is dragged, need to tell any active menus, etc.
  1637. if ((styleFlags & windowHasTitleBar) != 0
  1638. && component.isCurrentlyBlockedByAnotherModalComponent())
  1639. {
  1640. if (auto* currentModalComp = Component::getCurrentlyModalComponent())
  1641. currentModalComp->inputAttemptWhenModal();
  1642. }
  1643. if (confEvent.window == windowH && confEvent.above != 0 && isFrontWindow())
  1644. handleBroughtToFront();
  1645. }
  1646. void handleGravityNotify()
  1647. {
  1648. updateWindowBounds();
  1649. updateBorderSize();
  1650. handleMovedOrResized();
  1651. }
  1652. void handleMappingNotify (XMappingEvent& mappingEvent)
  1653. {
  1654. if (mappingEvent.request != MappingPointer)
  1655. {
  1656. // Deal with modifier/keyboard mapping
  1657. ScopedXLock xlock (display);
  1658. XRefreshKeyboardMapping (&mappingEvent);
  1659. updateModifierMappings();
  1660. }
  1661. }
  1662. void handleClientMessageEvent (XClientMessageEvent& clientMsg, XEvent& event)
  1663. {
  1664. if (clientMsg.message_type == atoms->protocols && clientMsg.format == 32)
  1665. {
  1666. auto atom = (Atom) clientMsg.data.l[0];
  1667. if (atom == atoms->protocolList [Atoms::PING])
  1668. {
  1669. Window root = RootWindow (display, DefaultScreen (display));
  1670. clientMsg.window = root;
  1671. XSendEvent (display, root, False, NoEventMask, &event);
  1672. XFlush (display);
  1673. }
  1674. else if (atom == atoms->protocolList [Atoms::TAKE_FOCUS])
  1675. {
  1676. if ((getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0)
  1677. {
  1678. XWindowAttributes atts;
  1679. ScopedXLock xlock (display);
  1680. if (clientMsg.window != 0
  1681. && XGetWindowAttributes (display, clientMsg.window, &atts))
  1682. {
  1683. if (atts.map_state == IsViewable)
  1684. XSetInputFocus (display,
  1685. (clientMsg.window == windowH ? getFocusWindow()
  1686. : clientMsg.window),
  1687. RevertToParent,
  1688. (::Time) clientMsg.data.l[1]);
  1689. }
  1690. }
  1691. }
  1692. else if (atom == atoms->protocolList [Atoms::DELETE_WINDOW])
  1693. {
  1694. handleUserClosingWindow();
  1695. }
  1696. }
  1697. else if (clientMsg.message_type == atoms->XdndEnter)
  1698. {
  1699. handleDragAndDropEnter (clientMsg);
  1700. }
  1701. else if (clientMsg.message_type == atoms->XdndLeave)
  1702. {
  1703. handleDragExit (dragInfo);
  1704. resetDragAndDrop();
  1705. }
  1706. else if (clientMsg.message_type == atoms->XdndPosition)
  1707. {
  1708. handleDragAndDropPosition (clientMsg);
  1709. }
  1710. else if (clientMsg.message_type == atoms->XdndDrop)
  1711. {
  1712. handleDragAndDropDrop (clientMsg);
  1713. }
  1714. else if (clientMsg.message_type == atoms->XdndStatus)
  1715. {
  1716. handleExternalDragAndDropStatus (clientMsg);
  1717. }
  1718. else if (clientMsg.message_type == atoms->XdndFinished)
  1719. {
  1720. externalResetDragAndDrop();
  1721. }
  1722. else if (clientMsg.message_type == atoms->XembedMsgType && clientMsg.format == 32)
  1723. {
  1724. handleXEmbedMessage (clientMsg);
  1725. }
  1726. }
  1727. bool externalDragTextInit (const String& text, std::function<void()> cb)
  1728. {
  1729. if (dragState->dragging)
  1730. return false;
  1731. return externalDragInit (true, text, cb);
  1732. }
  1733. bool externalDragFileInit (const StringArray& files, bool /*canMoveFiles*/, std::function<void()> cb)
  1734. {
  1735. if (dragState->dragging)
  1736. return false;
  1737. StringArray uriList;
  1738. for (auto& f : files)
  1739. {
  1740. if (f.matchesWildcard ("?*://*", false))
  1741. uriList.add (f);
  1742. else
  1743. uriList.add ("file://" + f);
  1744. }
  1745. return externalDragInit (false, uriList.joinIntoString ("\r\n"), cb);
  1746. }
  1747. void handleXEmbedMessage (XClientMessageEvent& clientMsg)
  1748. {
  1749. switch (clientMsg.data.l[1])
  1750. {
  1751. case XEMBED_EMBEDDED_NOTIFY:
  1752. parentWindow = (::Window) clientMsg.data.l[3];
  1753. updateWindowBounds();
  1754. component.setBounds (bounds);
  1755. break;
  1756. case XEMBED_FOCUS_IN:
  1757. handleFocusInEvent();
  1758. break;
  1759. case XEMBED_FOCUS_OUT:
  1760. handleFocusOutEvent();
  1761. break;
  1762. default:
  1763. break;
  1764. }
  1765. }
  1766. //==============================================================================
  1767. void showMouseCursor (Cursor cursor) noexcept
  1768. {
  1769. ScopedXLock xlock (display);
  1770. XDefineCursor (display, windowH, cursor);
  1771. }
  1772. //==============================================================================
  1773. double getPlatformScaleFactor() const noexcept override
  1774. {
  1775. return currentScaleFactor;
  1776. }
  1777. //==============================================================================
  1778. void addOpenGLRepaintListener (Component* dummy)
  1779. {
  1780. if (dummy != nullptr)
  1781. glRepaintListeners.addIfNotAlreadyThere (dummy);
  1782. }
  1783. void removeOpenGLRepaintListener (Component* dummy)
  1784. {
  1785. if (dummy != nullptr)
  1786. glRepaintListeners.removeAllInstancesOf (dummy);
  1787. }
  1788. void repaintOpenGLContexts()
  1789. {
  1790. for (int i = 0; i < glRepaintListeners.size(); ++i)
  1791. if (auto* c = glRepaintListeners [i])
  1792. c->handleCommandMessage (0);
  1793. }
  1794. //==============================================================================
  1795. unsigned long createKeyProxy()
  1796. {
  1797. jassert (keyProxy == 0 && windowH != 0);
  1798. if (keyProxy == 0 && windowH != 0)
  1799. {
  1800. XSetWindowAttributes swa;
  1801. swa.event_mask = KeyPressMask | KeyReleaseMask | FocusChangeMask;
  1802. keyProxy = XCreateWindow (display, windowH,
  1803. -1, -1, 1, 1, 0, 0,
  1804. InputOnly, CopyFromParent,
  1805. CWEventMask,
  1806. &swa);
  1807. XMapWindow (display, keyProxy);
  1808. XSaveContext (display, (XID) keyProxy, windowHandleXContext, (XPointer) this);
  1809. }
  1810. return keyProxy;
  1811. }
  1812. void deleteKeyProxy()
  1813. {
  1814. jassert (keyProxy != 0);
  1815. if (keyProxy != 0)
  1816. {
  1817. XPointer handlePointer;
  1818. if (! XFindContext (display, (XID) keyProxy, windowHandleXContext, &handlePointer))
  1819. XDeleteContext (display, (XID) keyProxy, windowHandleXContext);
  1820. XDestroyWindow (display, keyProxy);
  1821. XSync (display, false);
  1822. XEvent event;
  1823. while (XCheckWindowEvent (display, keyProxy, getAllEventsMask(), &event) == True)
  1824. {}
  1825. keyProxy = 0;
  1826. }
  1827. }
  1828. //==============================================================================
  1829. bool dontRepaint;
  1830. static bool isActiveApplication;
  1831. private:
  1832. //==============================================================================
  1833. class LinuxRepaintManager : public Timer
  1834. {
  1835. public:
  1836. LinuxRepaintManager (LinuxComponentPeer& p, ::Display* d)
  1837. : peer (p), display (d)
  1838. {
  1839. #if JUCE_USE_XSHM
  1840. useARGBImagesForRendering = XSHMHelpers::isShmAvailable (display);
  1841. if (useARGBImagesForRendering)
  1842. {
  1843. ScopedXLock xlock (display);
  1844. XShmSegmentInfo segmentinfo;
  1845. auto testImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  1846. 24, ZPixmap, nullptr, &segmentinfo, 64, 64);
  1847. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  1848. XDestroyImage (testImage);
  1849. }
  1850. #endif
  1851. }
  1852. void timerCallback() override
  1853. {
  1854. #if JUCE_USE_XSHM
  1855. if (shmPaintsPending != 0)
  1856. {
  1857. ScopedXLock xlock (display);
  1858. XEvent evt;
  1859. while (XCheckTypedWindowEvent (display, peer.windowH, peer.shmCompletionEvent, &evt))
  1860. --shmPaintsPending;
  1861. }
  1862. if (shmPaintsPending != 0)
  1863. return;
  1864. #endif
  1865. if (! regionsNeedingRepaint.isEmpty())
  1866. {
  1867. stopTimer();
  1868. performAnyPendingRepaintsNow();
  1869. }
  1870. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  1871. {
  1872. stopTimer();
  1873. image = Image();
  1874. }
  1875. }
  1876. void repaint (Rectangle<int> area)
  1877. {
  1878. if (! isTimerRunning())
  1879. startTimer (repaintTimerPeriod);
  1880. regionsNeedingRepaint.add (area * peer.currentScaleFactor);
  1881. }
  1882. void performAnyPendingRepaintsNow()
  1883. {
  1884. #if JUCE_USE_XSHM
  1885. if (shmPaintsPending != 0)
  1886. {
  1887. startTimer (repaintTimerPeriod);
  1888. return;
  1889. }
  1890. #endif
  1891. auto originalRepaintRegion = regionsNeedingRepaint;
  1892. regionsNeedingRepaint.clear();
  1893. auto totalArea = originalRepaintRegion.getBounds();
  1894. if (! totalArea.isEmpty())
  1895. {
  1896. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  1897. || image.getHeight() < totalArea.getHeight())
  1898. {
  1899. #if JUCE_USE_XSHM
  1900. image = Image (new XBitmapImage (display, useARGBImagesForRendering ? Image::ARGB
  1901. : Image::RGB,
  1902. #else
  1903. image = Image (new XBitmapImage (display, Image::RGB,
  1904. #endif
  1905. (totalArea.getWidth() + 31) & ~31,
  1906. (totalArea.getHeight() + 31) & ~31,
  1907. false, (unsigned int) peer.depth, peer.visual));
  1908. }
  1909. startTimer (repaintTimerPeriod);
  1910. RectangleList<int> adjustedList (originalRepaintRegion);
  1911. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  1912. if (peer.depth == 32)
  1913. for (auto& i : originalRepaintRegion)
  1914. image.clear (i - totalArea.getPosition());
  1915. {
  1916. auto context = peer.getComponent().getLookAndFeel()
  1917. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList);
  1918. context->addTransform (AffineTransform::scale ((float) peer.currentScaleFactor));
  1919. peer.handlePaint (*context);
  1920. }
  1921. for (auto& i : originalRepaintRegion)
  1922. {
  1923. auto* xbitmap = static_cast<XBitmapImage*> (image.getPixelData());
  1924. #if JUCE_USE_XSHM
  1925. if (xbitmap->isUsingXShm())
  1926. ++shmPaintsPending;
  1927. #endif
  1928. xbitmap->blitToWindow (peer.windowH,
  1929. i.getX(), i.getY(),
  1930. (unsigned int) i.getWidth(),
  1931. (unsigned int) i.getHeight(),
  1932. i.getX() - totalArea.getX(), i.getY() - totalArea.getY());
  1933. }
  1934. }
  1935. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  1936. startTimer (repaintTimerPeriod);
  1937. }
  1938. #if JUCE_USE_XSHM
  1939. void notifyPaintCompleted() noexcept { --shmPaintsPending; }
  1940. #endif
  1941. private:
  1942. enum { repaintTimerPeriod = 1000 / 100 };
  1943. LinuxComponentPeer& peer;
  1944. Image image;
  1945. uint32 lastTimeImageUsed = 0;
  1946. RectangleList<int> regionsNeedingRepaint;
  1947. ::Display* display;
  1948. #if JUCE_USE_XSHM
  1949. bool useARGBImagesForRendering;
  1950. int shmPaintsPending = 0;
  1951. #endif
  1952. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  1953. };
  1954. std::unique_ptr<Atoms> atoms;
  1955. std::unique_ptr<LinuxRepaintManager> repainter;
  1956. friend class LinuxRepaintManager;
  1957. Window windowH = {}, parentWindow = {}, keyProxy = {};
  1958. Rectangle<int> bounds;
  1959. Image taskbarImage;
  1960. bool fullScreen = false, mapped = false, focused = false;
  1961. Visual* visual = {};
  1962. int depth = 0;
  1963. BorderSize<int> windowBorder;
  1964. bool isAlwaysOnTop;
  1965. double currentScaleFactor = 1.0;
  1966. Array<Component*> glRepaintListeners;
  1967. enum { KeyPressEventType = 2 };
  1968. static ::Display* display;
  1969. #if JUCE_USE_XSHM
  1970. int shmCompletionEvent = 0;
  1971. #endif
  1972. struct MotifWmHints
  1973. {
  1974. unsigned long flags;
  1975. unsigned long functions;
  1976. unsigned long decorations;
  1977. long input_mode;
  1978. unsigned long status;
  1979. };
  1980. static void updateKeyStates (int keycode, bool press) noexcept
  1981. {
  1982. const int keybyte = keycode >> 3;
  1983. const int keybit = (1 << (keycode & 7));
  1984. if (press)
  1985. Keys::keyStates [keybyte] |= keybit;
  1986. else
  1987. Keys::keyStates [keybyte] &= ~keybit;
  1988. }
  1989. static void updateKeyModifiers (int status) noexcept
  1990. {
  1991. int keyMods = 0;
  1992. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  1993. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  1994. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  1995. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1996. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  1997. Keys::capsLock = ((status & LockMask) != 0);
  1998. }
  1999. static bool updateKeyModifiersFromSym (KeySym sym, bool press) noexcept
  2000. {
  2001. int modifier = 0;
  2002. bool isModifier = true;
  2003. switch (sym)
  2004. {
  2005. case XK_Shift_L:
  2006. case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
  2007. case XK_Control_L:
  2008. case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
  2009. case XK_Alt_L:
  2010. case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
  2011. case XK_Num_Lock:
  2012. if (press)
  2013. Keys::numLock = ! Keys::numLock;
  2014. break;
  2015. case XK_Caps_Lock:
  2016. if (press)
  2017. Keys::capsLock = ! Keys::capsLock;
  2018. break;
  2019. case XK_Scroll_Lock:
  2020. break;
  2021. default:
  2022. isModifier = false;
  2023. break;
  2024. }
  2025. ModifierKeys::currentModifiers = press ? ModifierKeys::currentModifiers.withFlags (modifier)
  2026. : ModifierKeys::currentModifiers.withoutFlags (modifier);
  2027. return isModifier;
  2028. }
  2029. // Alt and Num lock are not defined by standard X
  2030. // modifier constants: check what they're mapped to
  2031. static void updateModifierMappings() noexcept
  2032. {
  2033. ScopedXLock xlock (display);
  2034. int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  2035. int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  2036. Keys::AltMask = 0;
  2037. Keys::NumLockMask = 0;
  2038. if (auto* mapping = XGetModifierMapping (display))
  2039. {
  2040. for (int modifierIdx = 0; modifierIdx < 8; ++modifierIdx)
  2041. {
  2042. for (int keyIndex = 0; keyIndex < mapping->max_keypermod; ++keyIndex)
  2043. {
  2044. auto key = mapping->modifiermap[(modifierIdx * mapping->max_keypermod) + keyIndex];
  2045. if (key == altLeftCode)
  2046. Keys::AltMask = 1 << modifierIdx;
  2047. else if (key == numLockCode)
  2048. Keys::NumLockMask = 1 << modifierIdx;
  2049. }
  2050. }
  2051. XFreeModifiermap (mapping);
  2052. }
  2053. }
  2054. //==============================================================================
  2055. static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
  2056. {
  2057. XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  2058. }
  2059. void removeWindowDecorations (Window wndH)
  2060. {
  2061. Atom hints = Atoms::getIfExists (display, "_MOTIF_WM_HINTS");
  2062. if (hints != None)
  2063. {
  2064. MotifWmHints motifHints;
  2065. zerostruct (motifHints);
  2066. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  2067. motifHints.decorations = 0;
  2068. ScopedXLock xlock (display);
  2069. xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
  2070. }
  2071. hints = Atoms::getIfExists (display, "_WIN_HINTS");
  2072. if (hints != None)
  2073. {
  2074. long gnomeHints = 0;
  2075. ScopedXLock xlock (display);
  2076. xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
  2077. }
  2078. hints = Atoms::getIfExists (display, "KWM_WIN_DECORATION");
  2079. if (hints != None)
  2080. {
  2081. long kwmHints = 2; /*KDE_tinyDecoration*/
  2082. ScopedXLock xlock (display);
  2083. xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
  2084. }
  2085. hints = Atoms::getIfExists (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  2086. if (hints != None)
  2087. {
  2088. ScopedXLock xlock (display);
  2089. xchangeProperty (wndH, atoms->windowType, XA_ATOM, 32, &hints, 1);
  2090. }
  2091. }
  2092. void addWindowButtons (Window wndH)
  2093. {
  2094. ScopedXLock xlock (display);
  2095. Atom hints = Atoms::getIfExists (display, "_MOTIF_WM_HINTS");
  2096. if (hints != None)
  2097. {
  2098. MotifWmHints motifHints;
  2099. zerostruct (motifHints);
  2100. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  2101. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  2102. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  2103. if ((styleFlags & windowHasCloseButton) != 0)
  2104. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  2105. if ((styleFlags & windowHasMinimiseButton) != 0)
  2106. {
  2107. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  2108. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  2109. }
  2110. if ((styleFlags & windowHasMaximiseButton) != 0)
  2111. {
  2112. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  2113. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  2114. }
  2115. if ((styleFlags & windowIsResizable) != 0)
  2116. {
  2117. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  2118. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  2119. }
  2120. xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
  2121. }
  2122. hints = Atoms::getIfExists (display, "_NET_WM_ALLOWED_ACTIONS");
  2123. if (hints != None)
  2124. {
  2125. Atom netHints [6];
  2126. int num = 0;
  2127. if ((styleFlags & windowIsResizable) != 0)
  2128. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_RESIZE");
  2129. if ((styleFlags & windowHasMaximiseButton) != 0)
  2130. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_FULLSCREEN");
  2131. if ((styleFlags & windowHasMinimiseButton) != 0)
  2132. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_MINIMIZE");
  2133. if ((styleFlags & windowHasCloseButton) != 0)
  2134. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_CLOSE");
  2135. xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
  2136. }
  2137. }
  2138. void setWindowType()
  2139. {
  2140. Atom netHints [2];
  2141. if ((styleFlags & windowIsTemporary) != 0
  2142. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  2143. netHints [0] = Atoms::getIfExists (display, "_NET_WM_WINDOW_TYPE_COMBO");
  2144. else
  2145. netHints [0] = Atoms::getIfExists (display, "_NET_WM_WINDOW_TYPE_NORMAL");
  2146. xchangeProperty (windowH, atoms->windowType, XA_ATOM, 32, &netHints, 1);
  2147. int numHints = 0;
  2148. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  2149. netHints [numHints++] = Atoms::getIfExists (display, "_NET_WM_STATE_SKIP_TASKBAR");
  2150. if (component.isAlwaysOnTop())
  2151. netHints [numHints++] = Atoms::getIfExists (display, "_NET_WM_STATE_ABOVE");
  2152. if (numHints > 0)
  2153. xchangeProperty (windowH, atoms->windowState, XA_ATOM, 32, &netHints, numHints);
  2154. }
  2155. void createWindow (Window parentToAddTo)
  2156. {
  2157. ScopedXLock xlock (display);
  2158. resetDragAndDrop();
  2159. // Get defaults for various properties
  2160. const int screen = DefaultScreen (display);
  2161. Window root = RootWindow (display, screen);
  2162. parentWindow = parentToAddTo;
  2163. // Try to obtain a 32-bit visual or fallback to 24 or 16
  2164. visual = Visuals::findVisualFormat (display, (styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  2165. if (visual == nullptr)
  2166. {
  2167. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  2168. Process::terminate();
  2169. }
  2170. // Create and install a colormap suitable fr our visual
  2171. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  2172. XInstallColormap (display, colormap);
  2173. // Set up the window attributes
  2174. XSetWindowAttributes swa;
  2175. swa.border_pixel = 0;
  2176. swa.background_pixmap = None;
  2177. swa.colormap = colormap;
  2178. swa.override_redirect = ((styleFlags & windowIsTemporary) != 0) ? True : False;
  2179. swa.event_mask = getAllEventsMask();
  2180. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  2181. 0, 0, 1, 1,
  2182. 0, depth, InputOutput, visual,
  2183. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  2184. &swa);
  2185. // Set the window context to identify the window handle object
  2186. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  2187. {
  2188. // Failed
  2189. jassertfalse;
  2190. Logger::outputDebugString ("Failed to create context information for window.\n");
  2191. XDestroyWindow (display, windowH);
  2192. windowH = 0;
  2193. return;
  2194. }
  2195. // Set window manager hints
  2196. XWMHints* wmHints = XAllocWMHints();
  2197. wmHints->flags = InputHint | StateHint;
  2198. wmHints->input = True; // Locally active input model
  2199. wmHints->initial_state = NormalState;
  2200. XSetWMHints (display, windowH, wmHints);
  2201. XFree (wmHints);
  2202. // Set the window type
  2203. setWindowType();
  2204. // Define decoration
  2205. if ((styleFlags & windowHasTitleBar) == 0)
  2206. removeWindowDecorations (windowH);
  2207. else
  2208. addWindowButtons (windowH);
  2209. setTitle (component.getName());
  2210. // Associate the PID, allowing to be shut down when something goes wrong
  2211. unsigned long pid = (unsigned long) getpid();
  2212. xchangeProperty (windowH, atoms->pid, XA_CARDINAL, 32, &pid, 1);
  2213. // Set window manager protocols
  2214. xchangeProperty (windowH, atoms->protocols, XA_ATOM, 32, atoms->protocolList, 2);
  2215. // Set drag and drop flags
  2216. xchangeProperty (windowH, atoms->XdndTypeList, XA_ATOM, 32, atoms->allowedMimeTypes, numElementsInArray (atoms->allowedMimeTypes));
  2217. xchangeProperty (windowH, atoms->XdndActionList, XA_ATOM, 32, atoms->allowedActions, numElementsInArray (atoms->allowedActions));
  2218. xchangeProperty (windowH, atoms->XdndActionDescription, XA_STRING, 8, "", 0);
  2219. xchangeProperty (windowH, atoms->XdndAware, XA_ATOM, 32, &atoms->DndVersion, 1);
  2220. unsigned long info[2] = { 0, 1 };
  2221. xchangeProperty (windowH, atoms->XembedInfo, atoms->XembedInfo, 32, (unsigned char*) info, 2);
  2222. initialisePointerMap();
  2223. updateModifierMappings();
  2224. #if JUCE_USE_XSHM
  2225. if (XSHMHelpers::isShmAvailable (display))
  2226. shmCompletionEvent = XShmGetEventBase (display) + ShmCompletion;
  2227. #endif
  2228. }
  2229. void destroyWindow()
  2230. {
  2231. ScopedXLock xlock (display);
  2232. XPointer handlePointer;
  2233. if (keyProxy != 0)
  2234. deleteKeyProxy();
  2235. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  2236. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  2237. XDestroyWindow (display, windowH);
  2238. // Wait for it to complete and then remove any events for this
  2239. // window from the event queue.
  2240. XSync (display, false);
  2241. XEvent event;
  2242. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  2243. {}
  2244. }
  2245. int getAllEventsMask() const noexcept
  2246. {
  2247. return NoEventMask | KeyPressMask | KeyReleaseMask
  2248. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  2249. | ExposureMask | StructureNotifyMask | FocusChangeMask
  2250. | ((styleFlags & windowIgnoresMouseClicks) != 0 ? 0 : (ButtonPressMask | ButtonReleaseMask));
  2251. }
  2252. template <typename EventType>
  2253. static int64 getEventTime (const EventType& t)
  2254. {
  2255. return getEventTime (t.time);
  2256. }
  2257. static int64 getEventTime (::Time t)
  2258. {
  2259. static int64 eventTimeOffset = 0x12345678;
  2260. auto thisMessageTime = (int64) t;
  2261. if (eventTimeOffset == 0x12345678)
  2262. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  2263. return eventTimeOffset + thisMessageTime;
  2264. }
  2265. long getUserTime() const
  2266. {
  2267. GetXProperty prop (display, windowH, atoms->userTime, 0, 65536, false, XA_CARDINAL);
  2268. if (! prop.success)
  2269. return 0;
  2270. long result;
  2271. memcpy (&result, prop.data, sizeof (long));
  2272. return result;
  2273. }
  2274. void updateBorderSize()
  2275. {
  2276. if ((styleFlags & windowHasTitleBar) == 0)
  2277. {
  2278. windowBorder = BorderSize<int> (0);
  2279. }
  2280. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  2281. {
  2282. ScopedXLock xlock (display);
  2283. Atom hints = Atoms::getIfExists (display, "_NET_FRAME_EXTENTS");
  2284. if (hints != None)
  2285. {
  2286. GetXProperty prop (display, windowH, hints, 0, 4, false, XA_CARDINAL);
  2287. if (prop.success && prop.actualFormat == 32)
  2288. {
  2289. auto data = prop.data;
  2290. std::array<unsigned long, 4> sizes;
  2291. for (auto& size : sizes)
  2292. {
  2293. memcpy (&size, data, sizeof (unsigned long));
  2294. data += sizeof (unsigned long);
  2295. }
  2296. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  2297. (int) sizes[3], (int) sizes[1]);
  2298. }
  2299. }
  2300. }
  2301. }
  2302. void updateWindowBounds()
  2303. {
  2304. jassert (windowH != 0);
  2305. if (windowH != 0)
  2306. {
  2307. Window root, child;
  2308. int wx = 0, wy = 0;
  2309. unsigned int ww = 0, wh = 0, bw, bitDepth;
  2310. ScopedXLock xlock (display);
  2311. if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth) && parentWindow == 0)
  2312. if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  2313. wx = wy = 0;
  2314. Rectangle<int> physicalBounds (wx, wy, (int) ww, (int) wh);
  2315. updateScaleFactorFromNewBounds (physicalBounds, true);
  2316. bounds = (parentWindow == 0 ? Desktop::getInstance().getDisplays().physicalToLogical (physicalBounds)
  2317. : physicalBounds / currentScaleFactor);
  2318. }
  2319. }
  2320. //==============================================================================
  2321. struct DragState
  2322. {
  2323. DragState (::Display* d)
  2324. {
  2325. if (isText)
  2326. allowedTypes.add (Atoms::getCreating (d, "text/plain"));
  2327. else
  2328. allowedTypes.add (Atoms::getCreating (d, "text/uri-list"));
  2329. }
  2330. bool isText = false;
  2331. bool dragging = false; // currently performing outgoing external dnd as Xdnd source, have grabbed mouse
  2332. bool expectingStatus = false; // XdndPosition sent, waiting for XdndStatus
  2333. bool canDrop = false; // target window signals it will accept the drop
  2334. Window targetWindow = None; // potential drop target
  2335. int xdndVersion = -1; // negotiated version with target
  2336. Rectangle<int> silentRect;
  2337. String textOrFiles;
  2338. Array<Atom> allowedTypes;
  2339. std::function<void()> completionCallback;
  2340. };
  2341. //==============================================================================
  2342. void resetDragAndDrop()
  2343. {
  2344. dragInfo.clear();
  2345. dragInfo.position = Point<int> (-1, -1);
  2346. dragAndDropCurrentMimeType = 0;
  2347. dragAndDropSourceWindow = 0;
  2348. srcMimeTypeAtomList.clear();
  2349. finishAfterDropDataReceived = false;
  2350. }
  2351. void resetExternalDragState()
  2352. {
  2353. dragState.reset (new DragState (display));
  2354. }
  2355. void sendDragAndDropMessage (XClientMessageEvent& msg)
  2356. {
  2357. msg.type = ClientMessage;
  2358. msg.display = display;
  2359. msg.window = dragAndDropSourceWindow;
  2360. msg.format = 32;
  2361. msg.data.l[0] = (long) windowH;
  2362. ScopedXLock xlock (display);
  2363. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  2364. }
  2365. bool sendExternalDragAndDropMessage (XClientMessageEvent& msg, Window targetWindow)
  2366. {
  2367. msg.type = ClientMessage;
  2368. msg.display = display;
  2369. msg.window = targetWindow;
  2370. msg.format = 32;
  2371. msg.data.l[0] = (long) windowH;
  2372. ScopedXLock xlock (display);
  2373. return XSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
  2374. }
  2375. void sendExternalDragAndDropDrop (Window targetWindow)
  2376. {
  2377. XClientMessageEvent msg;
  2378. zerostruct (msg);
  2379. msg.message_type = atoms->XdndDrop;
  2380. msg.data.l[2] = CurrentTime;
  2381. sendExternalDragAndDropMessage (msg, targetWindow);
  2382. }
  2383. void sendExternalDragAndDropEnter (Window targetWindow)
  2384. {
  2385. XClientMessageEvent msg;
  2386. zerostruct (msg);
  2387. msg.message_type = atoms->XdndEnter;
  2388. msg.data.l[1] = (dragState->xdndVersion << 24);
  2389. for (int i = 0; i < 3; ++i)
  2390. msg.data.l[i + 2] = (long) dragState->allowedTypes[i];
  2391. sendExternalDragAndDropMessage (msg, targetWindow);
  2392. }
  2393. void sendExternalDragAndDropPosition (Window targetWindow)
  2394. {
  2395. XClientMessageEvent msg;
  2396. zerostruct (msg);
  2397. msg.message_type = atoms->XdndPosition;
  2398. Point<int> mousePos (Desktop::getInstance().getMousePosition());
  2399. if (dragState->silentRect.contains (mousePos)) // we've been asked to keep silent
  2400. return;
  2401. auto& displays = Desktop::getInstance().getDisplays();
  2402. mousePos = displays.logicalToPhysical (mousePos);
  2403. msg.data.l[1] = 0;
  2404. msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
  2405. msg.data.l[3] = CurrentTime;
  2406. msg.data.l[4] = (long) atoms->XdndActionCopy; // this is all JUCE currently supports
  2407. dragState->expectingStatus = sendExternalDragAndDropMessage (msg, targetWindow);
  2408. }
  2409. void sendDragAndDropStatus (bool acceptDrop, Atom dropAction)
  2410. {
  2411. XClientMessageEvent msg;
  2412. zerostruct (msg);
  2413. msg.message_type = atoms->XdndStatus;
  2414. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  2415. msg.data.l[4] = (long) dropAction;
  2416. sendDragAndDropMessage (msg);
  2417. }
  2418. void sendExternalDragAndDropLeave (Window targetWindow)
  2419. {
  2420. XClientMessageEvent msg;
  2421. zerostruct (msg);
  2422. msg.message_type = atoms->XdndLeave;
  2423. sendExternalDragAndDropMessage (msg, targetWindow);
  2424. }
  2425. void sendDragAndDropFinish()
  2426. {
  2427. XClientMessageEvent msg;
  2428. zerostruct (msg);
  2429. msg.message_type = atoms->XdndFinished;
  2430. sendDragAndDropMessage (msg);
  2431. }
  2432. void handleExternalSelectionClear()
  2433. {
  2434. if (dragState->dragging)
  2435. externalResetDragAndDrop();
  2436. }
  2437. void handleExternalSelectionRequest (const XEvent& evt)
  2438. {
  2439. Atom targetType = evt.xselectionrequest.target;
  2440. XEvent s;
  2441. s.xselection.type = SelectionNotify;
  2442. s.xselection.requestor = evt.xselectionrequest.requestor;
  2443. s.xselection.selection = evt.xselectionrequest.selection;
  2444. s.xselection.target = targetType;
  2445. s.xselection.property = None;
  2446. s.xselection.time = evt.xselectionrequest.time;
  2447. if (dragState->allowedTypes.contains (targetType))
  2448. {
  2449. s.xselection.property = evt.xselectionrequest.property;
  2450. xchangeProperty (evt.xselectionrequest.requestor,
  2451. evt.xselectionrequest.property,
  2452. targetType, 8,
  2453. dragState->textOrFiles.toRawUTF8(),
  2454. (int) dragState->textOrFiles.getNumBytesAsUTF8());
  2455. }
  2456. XSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
  2457. }
  2458. void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
  2459. {
  2460. if (dragState->expectingStatus)
  2461. {
  2462. dragState->expectingStatus = false;
  2463. dragState->canDrop = false;
  2464. dragState->silentRect = Rectangle<int>();
  2465. if ((clientMsg.data.l[1] & 1) != 0
  2466. && ((Atom) clientMsg.data.l[4] == atoms->XdndActionCopy
  2467. || (Atom) clientMsg.data.l[4] == atoms->XdndActionPrivate))
  2468. {
  2469. if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
  2470. dragState->silentRect.setBounds ((int) clientMsg.data.l[2] >> 16,
  2471. (int) clientMsg.data.l[2] & 0xffff,
  2472. (int) clientMsg.data.l[3] >> 16,
  2473. (int) clientMsg.data.l[3] & 0xffff);
  2474. dragState->canDrop = true;
  2475. }
  2476. }
  2477. }
  2478. void handleExternalDragButtonReleaseEvent()
  2479. {
  2480. if (dragState->dragging)
  2481. XUngrabPointer (display, CurrentTime);
  2482. if (dragState->canDrop)
  2483. {
  2484. sendExternalDragAndDropDrop (dragState->targetWindow);
  2485. }
  2486. else
  2487. {
  2488. sendExternalDragAndDropLeave (dragState->targetWindow);
  2489. externalResetDragAndDrop();
  2490. }
  2491. }
  2492. void handleExternalDragMotionNotify()
  2493. {
  2494. Window targetWindow = externalFindDragTargetWindow (RootWindow (display, DefaultScreen (display)));
  2495. if (dragState->targetWindow != targetWindow)
  2496. {
  2497. if (dragState->targetWindow != None)
  2498. sendExternalDragAndDropLeave (dragState->targetWindow);
  2499. dragState->canDrop = false;
  2500. dragState->silentRect = Rectangle<int>();
  2501. if (targetWindow == None)
  2502. return;
  2503. dragState->xdndVersion = getDnDVersionForWindow (targetWindow);
  2504. if (dragState->xdndVersion == -1)
  2505. return;
  2506. sendExternalDragAndDropEnter (targetWindow);
  2507. dragState->targetWindow = targetWindow;
  2508. }
  2509. if (! dragState->expectingStatus)
  2510. sendExternalDragAndDropPosition (targetWindow);
  2511. }
  2512. void handleDragAndDropPosition (const XClientMessageEvent& clientMsg)
  2513. {
  2514. if (dragAndDropSourceWindow == 0)
  2515. return;
  2516. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2517. Point<int> dropPos ((int) clientMsg.data.l[2] >> 16,
  2518. (int) clientMsg.data.l[2] & 0xffff);
  2519. dropPos = Desktop::getInstance().getDisplays().physicalToLogical (dropPos);
  2520. dropPos -= bounds.getPosition();
  2521. Atom targetAction = atoms->XdndActionCopy;
  2522. for (int i = numElementsInArray (atoms->allowedActions); --i >= 0;)
  2523. {
  2524. if ((Atom) clientMsg.data.l[4] == atoms->allowedActions[i])
  2525. {
  2526. targetAction = atoms->allowedActions[i];
  2527. break;
  2528. }
  2529. }
  2530. sendDragAndDropStatus (true, targetAction);
  2531. if (dragInfo.position != dropPos)
  2532. {
  2533. dragInfo.position = dropPos;
  2534. if (dragInfo.isEmpty())
  2535. updateDraggedFileList (clientMsg);
  2536. if (! dragInfo.isEmpty())
  2537. handleDragMove (dragInfo);
  2538. }
  2539. }
  2540. void handleDragAndDropDrop (const XClientMessageEvent& clientMsg)
  2541. {
  2542. if (dragInfo.isEmpty())
  2543. {
  2544. // no data, transaction finished in handleDragAndDropSelection()
  2545. finishAfterDropDataReceived = true;
  2546. updateDraggedFileList (clientMsg);
  2547. }
  2548. else
  2549. {
  2550. handleDragAndDropDataReceived(); // data was already received
  2551. }
  2552. }
  2553. void handleDragAndDropDataReceived()
  2554. {
  2555. DragInfo dragInfoCopy (dragInfo);
  2556. sendDragAndDropFinish();
  2557. resetDragAndDrop();
  2558. if (! dragInfoCopy.isEmpty())
  2559. handleDragDrop (dragInfoCopy);
  2560. }
  2561. void handleDragAndDropEnter (const XClientMessageEvent& clientMsg)
  2562. {
  2563. dragInfo.clear();
  2564. srcMimeTypeAtomList.clear();
  2565. dragAndDropCurrentMimeType = 0;
  2566. auto dndCurrentVersion = static_cast<unsigned long> (clientMsg.data.l[1] & 0xff000000) >> 24;
  2567. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  2568. {
  2569. dragAndDropSourceWindow = 0;
  2570. return;
  2571. }
  2572. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2573. if ((clientMsg.data.l[1] & 1) != 0)
  2574. {
  2575. ScopedXLock xlock (display);
  2576. GetXProperty prop (display, dragAndDropSourceWindow, atoms->XdndTypeList, 0, 0x8000000L, false, XA_ATOM);
  2577. if (prop.success
  2578. && prop.actualType == XA_ATOM
  2579. && prop.actualFormat == 32
  2580. && prop.numItems != 0)
  2581. {
  2582. auto* types = prop.data;
  2583. for (unsigned long i = 0; i < prop.numItems; ++i)
  2584. {
  2585. unsigned long type;
  2586. memcpy (&type, types, sizeof (unsigned long));
  2587. if (type != None)
  2588. srcMimeTypeAtomList.add (type);
  2589. types += sizeof (unsigned long);
  2590. }
  2591. }
  2592. }
  2593. if (srcMimeTypeAtomList.isEmpty())
  2594. {
  2595. for (int i = 2; i < 5; ++i)
  2596. if (clientMsg.data.l[i] != None)
  2597. srcMimeTypeAtomList.add ((unsigned long) clientMsg.data.l[i]);
  2598. if (srcMimeTypeAtomList.isEmpty())
  2599. {
  2600. dragAndDropSourceWindow = 0;
  2601. return;
  2602. }
  2603. }
  2604. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  2605. for (int j = 0; j < numElementsInArray (atoms->allowedMimeTypes); ++j)
  2606. if (srcMimeTypeAtomList[i] == atoms->allowedMimeTypes[j])
  2607. dragAndDropCurrentMimeType = atoms->allowedMimeTypes[j];
  2608. handleDragAndDropPosition (clientMsg);
  2609. }
  2610. void handleDragAndDropSelection (const XEvent& evt)
  2611. {
  2612. dragInfo.clear();
  2613. if (evt.xselection.property != None)
  2614. {
  2615. StringArray lines;
  2616. {
  2617. MemoryBlock dropData;
  2618. for (;;)
  2619. {
  2620. GetXProperty prop (display, evt.xany.window, evt.xselection.property,
  2621. (long) (dropData.getSize() / 4), 65536, false, AnyPropertyType);
  2622. if (! prop.success)
  2623. break;
  2624. dropData.append (prop.data, (size_t) (prop.actualFormat / 8) * prop.numItems);
  2625. if (prop.bytesLeft <= 0)
  2626. break;
  2627. }
  2628. lines.addLines (dropData.toString());
  2629. }
  2630. if (Atoms::isMimeTypeFile (display, dragAndDropCurrentMimeType))
  2631. {
  2632. for (int i = 0; i < lines.size(); ++i)
  2633. dragInfo.files.add (URL::removeEscapeChars (lines[i].replace ("file://", String(), true)));
  2634. dragInfo.files.trim();
  2635. dragInfo.files.removeEmptyStrings();
  2636. }
  2637. else
  2638. {
  2639. dragInfo.text = lines.joinIntoString ("\n");
  2640. }
  2641. if (finishAfterDropDataReceived)
  2642. handleDragAndDropDataReceived();
  2643. }
  2644. }
  2645. void updateDraggedFileList (const XClientMessageEvent& clientMsg)
  2646. {
  2647. jassert (dragInfo.isEmpty());
  2648. if (dragAndDropSourceWindow != None
  2649. && dragAndDropCurrentMimeType != None)
  2650. {
  2651. ScopedXLock xlock (display);
  2652. XConvertSelection (display,
  2653. atoms->XdndSelection,
  2654. dragAndDropCurrentMimeType,
  2655. Atoms::getCreating (display, "JXSelectionWindowProperty"),
  2656. windowH,
  2657. (::Time) clientMsg.data.l[2]);
  2658. }
  2659. }
  2660. bool isWindowDnDAware (Window w) const
  2661. {
  2662. int numProperties = 0;
  2663. auto* properties = XListProperties (display, w, &numProperties);
  2664. bool dndAwarePropFound = false;
  2665. for (int i = 0; i < numProperties; ++i)
  2666. if (properties[i] == atoms->XdndAware)
  2667. dndAwarePropFound = true;
  2668. if (properties != nullptr)
  2669. XFree (properties);
  2670. return dndAwarePropFound;
  2671. }
  2672. int getDnDVersionForWindow (Window targetWindow)
  2673. {
  2674. GetXProperty prop (display, targetWindow, atoms->XdndAware,
  2675. 0, 2, false, AnyPropertyType);
  2676. if (prop.success && prop.data != None && prop.actualFormat == 32 && prop.numItems == 1)
  2677. return jmin ((int) prop.data[0], (int) atoms->DndVersion);
  2678. return -1;
  2679. }
  2680. Window externalFindDragTargetWindow (Window targetWindow)
  2681. {
  2682. if (targetWindow == None)
  2683. return None;
  2684. if (isWindowDnDAware (targetWindow))
  2685. return targetWindow;
  2686. Window child, phonyWin;
  2687. int phony;
  2688. unsigned int uphony;
  2689. XQueryPointer (display, targetWindow, &phonyWin, &child,
  2690. &phony, &phony, &phony, &phony, &uphony);
  2691. return externalFindDragTargetWindow (child);
  2692. }
  2693. bool externalDragInit (bool isText, const String& textOrFiles, std::function<void()> cb)
  2694. {
  2695. ScopedXLock xlock (display);
  2696. resetExternalDragState();
  2697. dragState->isText = isText;
  2698. dragState->textOrFiles = textOrFiles;
  2699. dragState->targetWindow = windowH;
  2700. dragState->completionCallback = cb;
  2701. const int pointerGrabMask = Button1MotionMask | ButtonReleaseMask;
  2702. if (XGrabPointer (display, windowH, True, pointerGrabMask,
  2703. GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
  2704. {
  2705. // No other method of changing the pointer seems to work, this call is needed from this very context
  2706. XChangeActivePointerGrab (display, pointerGrabMask, (Cursor) createDraggingHandCursor(), CurrentTime);
  2707. XSetSelectionOwner (display, atoms->XdndSelection, windowH, CurrentTime);
  2708. // save the available types to XdndTypeList
  2709. xchangeProperty (windowH, atoms->XdndTypeList, XA_ATOM, 32,
  2710. dragState->allowedTypes.getRawDataPointer(),
  2711. dragState->allowedTypes.size());
  2712. dragState->dragging = true;
  2713. dragState->xdndVersion = getDnDVersionForWindow (dragState->targetWindow);
  2714. sendExternalDragAndDropEnter (dragState->targetWindow);
  2715. handleExternalDragMotionNotify();
  2716. return true;
  2717. }
  2718. return false;
  2719. }
  2720. void externalResetDragAndDrop()
  2721. {
  2722. if (dragState->dragging)
  2723. {
  2724. ScopedXLock xlock (display);
  2725. XUngrabPointer (display, CurrentTime);
  2726. }
  2727. if (dragState->completionCallback != nullptr)
  2728. dragState->completionCallback();
  2729. resetExternalDragState();
  2730. }
  2731. std::unique_ptr<DragState> dragState;
  2732. DragInfo dragInfo;
  2733. Atom dragAndDropCurrentMimeType;
  2734. Window dragAndDropSourceWindow;
  2735. bool finishAfterDropDataReceived;
  2736. Array<Atom> srcMimeTypeAtomList;
  2737. int pointerMap[5] = {};
  2738. void initialisePointerMap()
  2739. {
  2740. const int numButtons = XGetPointerMapping (display, nullptr, 0);
  2741. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2742. if (numButtons == 2)
  2743. {
  2744. pointerMap[0] = Keys::LeftButton;
  2745. pointerMap[1] = Keys::RightButton;
  2746. }
  2747. else if (numButtons >= 3)
  2748. {
  2749. pointerMap[0] = Keys::LeftButton;
  2750. pointerMap[1] = Keys::MiddleButton;
  2751. pointerMap[2] = Keys::RightButton;
  2752. if (numButtons >= 5)
  2753. {
  2754. pointerMap[3] = Keys::WheelUp;
  2755. pointerMap[4] = Keys::WheelDown;
  2756. }
  2757. }
  2758. }
  2759. static Point<int> lastMousePos;
  2760. static void clearLastMousePos() noexcept
  2761. {
  2762. lastMousePos = Point<int> (0x100000, 0x100000);
  2763. }
  2764. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  2765. };
  2766. bool LinuxComponentPeer::isActiveApplication = false;
  2767. Point<int> LinuxComponentPeer::lastMousePos;
  2768. ::Display* LinuxComponentPeer::display = nullptr;
  2769. //==============================================================================
  2770. namespace WindowingHelpers
  2771. {
  2772. static void windowMessageReceive (XEvent& event)
  2773. {
  2774. if (event.xany.window != None)
  2775. {
  2776. #if JUCE_X11_SUPPORTS_XEMBED
  2777. if (! juce_handleXEmbedEvent (nullptr, &event))
  2778. #endif
  2779. {
  2780. if (auto* peer = LinuxComponentPeer::getPeerFor (event.xany.window))
  2781. peer->handleWindowMessage (event);
  2782. }
  2783. }
  2784. else if (event.xany.type == KeymapNotify)
  2785. {
  2786. auto& keymapEvent = (const XKeymapEvent&) event.xkeymap;
  2787. memcpy (Keys::keyStates, keymapEvent.key_vector, 32);
  2788. }
  2789. }
  2790. }
  2791. struct WindowingCallbackInitialiser
  2792. {
  2793. WindowingCallbackInitialiser()
  2794. {
  2795. dispatchWindowMessage = WindowingHelpers::windowMessageReceive;
  2796. }
  2797. };
  2798. static WindowingCallbackInitialiser windowingInitialiser;
  2799. //==============================================================================
  2800. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess()
  2801. {
  2802. return LinuxComponentPeer::isActiveApplication;
  2803. }
  2804. // N/A on Linux as far as I know.
  2805. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2806. JUCE_API void JUCE_CALLTYPE Process::hide() {}
  2807. //==============================================================================
  2808. void Desktop::setKioskComponent (Component* comp, bool enableOrDisable, bool /* allowMenusAndBars */)
  2809. {
  2810. if (enableOrDisable)
  2811. comp->setBounds (getDisplays().getMainDisplay().totalArea);
  2812. }
  2813. void Desktop::allowedOrientationsChanged() {}
  2814. //==============================================================================
  2815. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  2816. {
  2817. return new LinuxComponentPeer (*this, styleFlags, (Window) nativeWindowToAttachTo);
  2818. }
  2819. //==============================================================================
  2820. void Displays::findDisplays (float masterScale)
  2821. {
  2822. ScopedXDisplay xDisplay;
  2823. if (auto display = xDisplay.display)
  2824. {
  2825. Atom hints = Atoms::getIfExists (display, "_NET_WORKAREA");
  2826. auto getWorkAreaPropertyData = [&] (int screenNum) -> unsigned char*
  2827. {
  2828. if (hints != None)
  2829. {
  2830. GetXProperty prop (display, RootWindow (display, screenNum), hints, 0, 4, false, XA_CARDINAL);
  2831. if (prop.success && prop.actualType == XA_CARDINAL && prop.actualFormat == 32 && prop.numItems == 4)
  2832. return prop.data;
  2833. }
  2834. return nullptr;
  2835. };
  2836. #if JUCE_USE_XRANDR
  2837. {
  2838. int major_opcode, first_event, first_error;
  2839. if (XQueryExtension (display, "RANDR", &major_opcode, &first_event, &first_error))
  2840. {
  2841. auto& xrandr = XRandrWrapper::getInstance();
  2842. auto numMonitors = ScreenCount (display);
  2843. auto mainDisplay = xrandr.getOutputPrimary (display, RootWindow (display, 0));
  2844. for (int i = 0; i < numMonitors; ++i)
  2845. {
  2846. if (getWorkAreaPropertyData (i) == nullptr)
  2847. continue;
  2848. if (auto* screens = xrandr.getScreenResources (display, RootWindow (display, i)))
  2849. {
  2850. for (int j = 0; j < screens->noutput; ++j)
  2851. {
  2852. if (screens->outputs[j])
  2853. {
  2854. // Xrandr on the raspberry pi fails to determine the main display (mainDisplay == 0)!
  2855. // Detect this edge case and make the first found display the main display
  2856. if (! mainDisplay)
  2857. mainDisplay = screens->outputs[j];
  2858. if (auto* output = xrandr.getOutputInfo (display, screens, screens->outputs[j]))
  2859. {
  2860. if (output->crtc)
  2861. {
  2862. if (auto* crtc = xrandr.getCrtcInfo (display, screens, output->crtc))
  2863. {
  2864. Display d;
  2865. d.totalArea = Rectangle<int> (crtc->x, crtc->y,
  2866. (int) crtc->width, (int) crtc->height);
  2867. d.isMain = (mainDisplay == screens->outputs[j]) && (i == 0);
  2868. d.dpi = getDisplayDPI (display, 0);
  2869. // The raspberry pi returns a zero sized display, so we need to guard for divide-by-zero
  2870. if (output->mm_width > 0 && output->mm_height > 0)
  2871. d.dpi = ((static_cast<double> (crtc->width) * 25.4 * 0.5) / static_cast<double> (output->mm_width))
  2872. + ((static_cast<double> (crtc->height) * 25.4 * 0.5) / static_cast<double> (output->mm_height));
  2873. double scale = getScaleForDisplay (output->name, d.dpi);
  2874. scale = (scale <= 0.1 ? 1.0 : scale);
  2875. d.scale = masterScale * scale;
  2876. if (d.isMain)
  2877. displays.insert (0, d);
  2878. else
  2879. displays.add (d);
  2880. xrandr.freeCrtcInfo (crtc);
  2881. }
  2882. }
  2883. xrandr.freeOutputInfo (output);
  2884. }
  2885. }
  2886. }
  2887. xrandr.freeScreenResources (screens);
  2888. }
  2889. }
  2890. if (! displays.isEmpty() && ! displays.getReference (0).isMain)
  2891. displays.getReference (0).isMain = true;
  2892. }
  2893. }
  2894. if (displays.isEmpty())
  2895. #endif
  2896. #if JUCE_USE_XINERAMA
  2897. {
  2898. auto screens = XineramaQueryDisplays (display);
  2899. int numMonitors = screens.size();
  2900. for (int index = 0; index < numMonitors; ++index)
  2901. {
  2902. for (int j = numMonitors; --j >= 0;)
  2903. {
  2904. if (screens[j].screen_number == index)
  2905. {
  2906. Display d;
  2907. d.totalArea = Rectangle<int> (screens[j].x_org,
  2908. screens[j].y_org,
  2909. screens[j].width,
  2910. screens[j].height);
  2911. d.isMain = (index == 0);
  2912. d.scale = masterScale;
  2913. d.dpi = getDisplayDPI (display, 0); // (all screens share the same DPI)
  2914. displays.add (d);
  2915. }
  2916. }
  2917. }
  2918. }
  2919. if (displays.isEmpty())
  2920. #endif
  2921. {
  2922. if (hints != None)
  2923. {
  2924. auto numMonitors = ScreenCount (display);
  2925. for (int i = 0; i < numMonitors; ++i)
  2926. {
  2927. if (auto* positionData = getWorkAreaPropertyData (i))
  2928. {
  2929. std::array<long, 4> position;
  2930. for (auto& p : position)
  2931. {
  2932. memcpy (&p, positionData, sizeof (long));
  2933. positionData += sizeof (long);
  2934. }
  2935. Display d;
  2936. d.totalArea = Rectangle<int> ((int) position[0], (int) position[1],
  2937. (int) position[2], (int) position[3]);
  2938. d.isMain = displays.isEmpty();
  2939. d.scale = masterScale;
  2940. d.dpi = getDisplayDPI (display, i);
  2941. displays.add (d);
  2942. }
  2943. }
  2944. }
  2945. if (displays.isEmpty())
  2946. {
  2947. Display d;
  2948. d.totalArea = Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  2949. DisplayHeight (display, DefaultScreen (display)));
  2950. d.isMain = true;
  2951. d.scale = masterScale;
  2952. d.dpi = getDisplayDPI (display, 0);
  2953. displays.add (d);
  2954. }
  2955. }
  2956. for (auto& d : displays)
  2957. d.userArea = d.totalArea; // JUCE currently does not support requesting the user area on Linux
  2958. updateToLogical();
  2959. }
  2960. }
  2961. //==============================================================================
  2962. bool MouseInputSource::SourceList::addSource()
  2963. {
  2964. if (sources.isEmpty())
  2965. {
  2966. addSource (0, MouseInputSource::InputSourceType::mouse);
  2967. return true;
  2968. }
  2969. return false;
  2970. }
  2971. bool MouseInputSource::SourceList::canUseTouch()
  2972. {
  2973. return false;
  2974. }
  2975. bool Desktop::canUseSemiTransparentWindows() noexcept
  2976. {
  2977. #if JUCE_USE_XRENDER
  2978. auto display = XWindowSystem::getInstance()->displayRef();
  2979. if (XRender::hasCompositingWindowManager (display))
  2980. {
  2981. int matchedDepth = 0, desiredDepth = 32;
  2982. return Visuals::findVisualFormat (display, desiredDepth, matchedDepth) != 0
  2983. && matchedDepth == desiredDepth;
  2984. }
  2985. #endif
  2986. return false;
  2987. }
  2988. Point<float> MouseInputSource::getCurrentRawMousePosition()
  2989. {
  2990. ScopedXDisplay xDisplay;
  2991. auto display = xDisplay.display;
  2992. if (display == nullptr)
  2993. return {};
  2994. Window root, child;
  2995. int x, y, winx, winy;
  2996. unsigned int mask;
  2997. ScopedXLock xlock (display);
  2998. if (XQueryPointer (display,
  2999. RootWindow (display, DefaultScreen (display)),
  3000. &root, &child,
  3001. &x, &y, &winx, &winy, &mask) == False)
  3002. {
  3003. // Pointer not on the default screen
  3004. x = y = -1;
  3005. }
  3006. return Desktop::getInstance().getDisplays().physicalToLogical (Point<float> ((float) x, (float) y));
  3007. }
  3008. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3009. {
  3010. ScopedXDisplay xDisplay;
  3011. if (auto display = xDisplay.display)
  3012. {
  3013. ScopedXLock xlock (display);
  3014. Window root = RootWindow (display, DefaultScreen (display));
  3015. newPosition = Desktop::getInstance().getDisplays().logicalToPhysical (newPosition);
  3016. XWarpPointer (display, None, root, 0, 0, 0, 0, roundToInt (newPosition.getX()), roundToInt (newPosition.getY()));
  3017. }
  3018. }
  3019. double Desktop::getDefaultMasterScale()
  3020. {
  3021. return 1.0;
  3022. }
  3023. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  3024. {
  3025. return upright;
  3026. }
  3027. //==============================================================================
  3028. static bool screenSaverAllowed = true;
  3029. void Desktop::setScreenSaverEnabled (bool isEnabled)
  3030. {
  3031. if (screenSaverAllowed != isEnabled)
  3032. {
  3033. screenSaverAllowed = isEnabled;
  3034. ScopedXDisplay xDisplay;
  3035. if (auto display = xDisplay.display)
  3036. {
  3037. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  3038. static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
  3039. if (xScreenSaverSuspend == nullptr)
  3040. if (void* h = dlopen ("libXss.so.1", RTLD_GLOBAL | RTLD_NOW))
  3041. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  3042. ScopedXLock xlock (display);
  3043. if (xScreenSaverSuspend != nullptr)
  3044. xScreenSaverSuspend (display, ! isEnabled);
  3045. }
  3046. }
  3047. }
  3048. bool Desktop::isScreenSaverEnabled()
  3049. {
  3050. return screenSaverAllowed;
  3051. }
  3052. //==============================================================================
  3053. Image juce_createIconForFile (const File& /* file */)
  3054. {
  3055. return {};
  3056. }
  3057. //==============================================================================
  3058. void LookAndFeel::playAlertSound()
  3059. {
  3060. std::cout << "\a" << std::flush;
  3061. }
  3062. //==============================================================================
  3063. Rectangle<int> juce_LinuxScaledToPhysicalBounds (ComponentPeer* peer, Rectangle<int> bounds)
  3064. {
  3065. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3066. bounds *= linuxPeer->getPlatformScaleFactor();
  3067. return bounds;
  3068. }
  3069. void juce_LinuxAddRepaintListener (ComponentPeer* peer, Component* dummy)
  3070. {
  3071. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3072. linuxPeer->addOpenGLRepaintListener (dummy);
  3073. }
  3074. void juce_LinuxRemoveRepaintListener (ComponentPeer* peer, Component* dummy)
  3075. {
  3076. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3077. linuxPeer->removeOpenGLRepaintListener (dummy);
  3078. }
  3079. unsigned long juce_createKeyProxyWindow (ComponentPeer* peer)
  3080. {
  3081. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3082. return linuxPeer->createKeyProxy();
  3083. return 0;
  3084. }
  3085. void juce_deleteKeyProxyWindow (ComponentPeer* peer)
  3086. {
  3087. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3088. linuxPeer->deleteKeyProxy();
  3089. }
  3090. //==============================================================================
  3091. #if JUCE_MODAL_LOOPS_PERMITTED
  3092. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3093. const String& title, const String& message,
  3094. Component* /* associatedComponent */)
  3095. {
  3096. AlertWindow::showMessageBox (iconType, title, message);
  3097. }
  3098. #endif
  3099. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3100. const String& title, const String& message,
  3101. Component* associatedComponent,
  3102. ModalComponentManager::Callback* callback)
  3103. {
  3104. AlertWindow::showMessageBoxAsync (iconType, title, message, String(), associatedComponent, callback);
  3105. }
  3106. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3107. const String& title, const String& message,
  3108. Component* associatedComponent,
  3109. ModalComponentManager::Callback* callback)
  3110. {
  3111. return AlertWindow::showOkCancelBox (iconType, title, message, String(), String(),
  3112. associatedComponent, callback);
  3113. }
  3114. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3115. const String& title, const String& message,
  3116. Component* associatedComponent,
  3117. ModalComponentManager::Callback* callback)
  3118. {
  3119. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  3120. String(), String(), String(),
  3121. associatedComponent, callback);
  3122. }
  3123. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  3124. const String& title, const String& message,
  3125. Component* associatedComponent,
  3126. ModalComponentManager::Callback* callback)
  3127. {
  3128. return AlertWindow::showOkCancelBox (iconType, title, message, TRANS ("Yes"), TRANS ("No"),
  3129. associatedComponent, callback);
  3130. }
  3131. //============================== X11 - MouseCursor =============================
  3132. std::map<Cursor, Display*> cursorMap;
  3133. void* CustomMouseCursorInfo::create() const
  3134. {
  3135. ScopedXDisplay xDisplay;
  3136. auto display = xDisplay.display;
  3137. if (display == nullptr)
  3138. return nullptr;
  3139. ScopedXLock xlock (display);
  3140. auto imageW = (unsigned int) image.getWidth();
  3141. auto imageH = (unsigned int) image.getHeight();
  3142. int hotspotX = hotspot.x;
  3143. int hotspotY = hotspot.y;
  3144. #if JUCE_USE_XCURSOR
  3145. {
  3146. using tXcursorSupportsARGB = XcursorBool (*) (Display*);
  3147. using tXcursorImageCreate = XcursorImage* (*) (int, int);
  3148. using tXcursorImageDestroy = void (*) (XcursorImage*);
  3149. using tXcursorImageLoadCursor = Cursor (*) (Display*, const XcursorImage*);
  3150. static tXcursorSupportsARGB xcursorSupportsARGB = nullptr;
  3151. static tXcursorImageCreate xcursorImageCreate = nullptr;
  3152. static tXcursorImageDestroy xcursorImageDestroy = nullptr;
  3153. static tXcursorImageLoadCursor xcursorImageLoadCursor = nullptr;
  3154. static bool hasBeenLoaded = false;
  3155. if (! hasBeenLoaded)
  3156. {
  3157. hasBeenLoaded = true;
  3158. if (void* h = dlopen ("libXcursor.so.1", RTLD_GLOBAL | RTLD_NOW))
  3159. {
  3160. xcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  3161. xcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  3162. xcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  3163. xcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  3164. if (xcursorSupportsARGB == nullptr || xcursorImageCreate == nullptr
  3165. || xcursorImageLoadCursor == nullptr || xcursorImageDestroy == nullptr
  3166. || ! xcursorSupportsARGB (display))
  3167. xcursorSupportsARGB = nullptr;
  3168. }
  3169. }
  3170. if (xcursorSupportsARGB != nullptr)
  3171. {
  3172. if (XcursorImage* xcImage = xcursorImageCreate ((int) imageW, (int) imageH))
  3173. {
  3174. xcImage->xhot = (XcursorDim) hotspotX;
  3175. xcImage->yhot = (XcursorDim) hotspotY;
  3176. XcursorPixel* dest = xcImage->pixels;
  3177. for (int y = 0; y < (int) imageH; ++y)
  3178. for (int x = 0; x < (int) imageW; ++x)
  3179. *dest++ = image.getPixelAt (x, y).getARGB();
  3180. void* result = (void*) xcursorImageLoadCursor (display, xcImage);
  3181. xcursorImageDestroy (xcImage);
  3182. if (result != nullptr)
  3183. {
  3184. cursorMap[(Cursor) result] = display;
  3185. return result;
  3186. }
  3187. }
  3188. }
  3189. }
  3190. #endif
  3191. Window root = RootWindow (display, DefaultScreen (display));
  3192. unsigned int cursorW, cursorH;
  3193. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  3194. return nullptr;
  3195. Image im (Image::ARGB, (int) cursorW, (int) cursorH, true);
  3196. {
  3197. Graphics g (im);
  3198. if (imageW > cursorW || imageH > cursorH)
  3199. {
  3200. hotspotX = (hotspotX * (int) cursorW) / (int) imageW;
  3201. hotspotY = (hotspotY * (int) cursorH) / (int) imageH;
  3202. g.drawImage (image, Rectangle<float> ((float) imageW, (float) imageH),
  3203. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize);
  3204. }
  3205. else
  3206. {
  3207. g.drawImageAt (image, 0, 0);
  3208. }
  3209. }
  3210. const unsigned int stride = (cursorW + 7) >> 3;
  3211. HeapBlock<char> maskPlane, sourcePlane;
  3212. maskPlane.calloc (stride * cursorH);
  3213. sourcePlane.calloc (stride * cursorH);
  3214. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  3215. for (int y = (int) cursorH; --y >= 0;)
  3216. {
  3217. for (int x = (int) cursorW; --x >= 0;)
  3218. {
  3219. auto mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  3220. auto offset = (unsigned int) y * stride + ((unsigned int) x >> 3);
  3221. auto c = im.getPixelAt (x, y);
  3222. if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
  3223. if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
  3224. }
  3225. }
  3226. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3227. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3228. XColor white, black;
  3229. black.red = black.green = black.blue = 0;
  3230. white.red = white.green = white.blue = 0xffff;
  3231. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black,
  3232. (unsigned int) hotspotX, (unsigned int) hotspotY);
  3233. XFreePixmap (display, sourcePixmap);
  3234. XFreePixmap (display, maskPixmap);
  3235. cursorMap[(Cursor) result] = display;
  3236. return result;
  3237. }
  3238. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool)
  3239. {
  3240. if (cursorHandle != nullptr)
  3241. {
  3242. ScopedXDisplay xDisplay;
  3243. if (auto display = xDisplay.display)
  3244. {
  3245. ScopedXLock xlock (display);
  3246. XFreeCursor (display, (Cursor) cursorHandle);
  3247. }
  3248. }
  3249. }
  3250. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  3251. {
  3252. ScopedXDisplay xDisplay;
  3253. auto display = xDisplay.display;
  3254. if (display == nullptr)
  3255. return None;
  3256. unsigned int shape;
  3257. switch (type)
  3258. {
  3259. case NormalCursor:
  3260. case ParentCursor: return None; // Use parent cursor
  3261. case NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), {}).create();
  3262. case WaitCursor: shape = XC_watch; break;
  3263. case IBeamCursor: shape = XC_xterm; break;
  3264. case PointingHandCursor: shape = XC_hand2; break;
  3265. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  3266. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  3267. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  3268. case TopEdgeResizeCursor: shape = XC_top_side; break;
  3269. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  3270. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  3271. case RightEdgeResizeCursor: shape = XC_right_side; break;
  3272. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  3273. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  3274. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  3275. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  3276. case CrosshairCursor: shape = XC_crosshair; break;
  3277. case DraggingHandCursor: return createDraggingHandCursor();
  3278. case CopyingCursor:
  3279. {
  3280. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3281. 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,
  3282. 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,
  3283. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3284. const int copyCursorSize = 119;
  3285. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), { 1, 3 }).create();
  3286. }
  3287. default:
  3288. jassertfalse;
  3289. return None;
  3290. }
  3291. ScopedXLock xlock (display);
  3292. auto* result = (void*) XCreateFontCursor (display, shape);
  3293. cursorMap[(Cursor) result] = display;
  3294. return result;
  3295. }
  3296. void MouseCursor::showInWindow (ComponentPeer* peer) const
  3297. {
  3298. if (auto* lp = dynamic_cast<LinuxComponentPeer*> (peer))
  3299. {
  3300. ScopedXDisplay xDisplay;
  3301. if (cursorHandle != nullptr && xDisplay.display != cursorMap[(Cursor) getHandle()])
  3302. {
  3303. auto oldHandle = (Cursor) getHandle();
  3304. if (auto* customInfo = cursorHandle->getCustomInfo())
  3305. cursorHandle->setHandle (customInfo->create());
  3306. else
  3307. cursorHandle->setHandle (createStandardMouseCursor (cursorHandle->getType()));
  3308. cursorMap.erase (oldHandle);
  3309. }
  3310. lp->showMouseCursor ((Cursor) getHandle());
  3311. }
  3312. }
  3313. //=================================== X11 - DND ================================
  3314. static LinuxComponentPeer* getPeerForDragEvent (Component* sourceComp)
  3315. {
  3316. if (sourceComp == nullptr)
  3317. if (auto* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  3318. sourceComp = draggingSource->getComponentUnderMouse();
  3319. if (sourceComp != nullptr)
  3320. if (auto* lp = dynamic_cast<LinuxComponentPeer*> (sourceComp->getPeer()))
  3321. return lp;
  3322. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  3323. return nullptr;
  3324. }
  3325. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles,
  3326. Component* sourceComp, std::function<void()> callback)
  3327. {
  3328. if (files.isEmpty())
  3329. return false;
  3330. if (auto* lp = getPeerForDragEvent (sourceComp))
  3331. return lp->externalDragFileInit (files, canMoveFiles, callback);
  3332. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3333. jassertfalse;
  3334. return false;
  3335. }
  3336. bool DragAndDropContainer::performExternalDragDropOfText (const String& text, Component* sourceComp,
  3337. std::function<void()> callback)
  3338. {
  3339. if (text.isEmpty())
  3340. return false;
  3341. if (auto* lp = getPeerForDragEvent (sourceComp))
  3342. return lp->externalDragTextInit (text, callback);
  3343. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3344. jassertfalse;
  3345. return false;
  3346. }
  3347. } // namespace juce