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.

4345 lines
155KB

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