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.

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