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.

4214 lines
151KB

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