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.

4199 lines
150KB

  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 (0, getMousePos (buttonPressEvent), getEventTime (buttonPressEvent), wheel);
  1770. }
  1771. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent, int buttonModifierFlag)
  1772. {
  1773. currentModifiers = currentModifiers.withFlags (buttonModifierFlag);
  1774. toFront (true);
  1775. handleMouseEvent (0, getMousePos (buttonPressEvent), currentModifiers,
  1776. MouseInputSource::invalidPressure, getEventTime (buttonPressEvent));
  1777. }
  1778. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent)
  1779. {
  1780. updateKeyModifiers ((int) buttonPressEvent.state);
  1781. switch (pointerMap [buttonPressEvent.button - Button1])
  1782. {
  1783. case Keys::WheelUp: handleWheelEvent (buttonPressEvent, 50.0f / 256.0f); break;
  1784. case Keys::WheelDown: handleWheelEvent (buttonPressEvent, -50.0f / 256.0f); break;
  1785. case Keys::LeftButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::leftButtonModifier); break;
  1786. case Keys::RightButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::rightButtonModifier); break;
  1787. case Keys::MiddleButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::middleButtonModifier); break;
  1788. default: break;
  1789. }
  1790. clearLastMousePos();
  1791. }
  1792. void handleButtonReleaseEvent (const XButtonReleasedEvent& buttonRelEvent)
  1793. {
  1794. updateKeyModifiers ((int) buttonRelEvent.state);
  1795. if (parentWindow != 0)
  1796. updateWindowBounds();
  1797. switch (pointerMap [buttonRelEvent.button - Button1])
  1798. {
  1799. case Keys::LeftButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
  1800. case Keys::RightButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
  1801. case Keys::MiddleButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
  1802. default: break;
  1803. }
  1804. if (dragState->dragging)
  1805. handleExternalDragButtonReleaseEvent();
  1806. handleMouseEvent (0, getMousePos (buttonRelEvent), currentModifiers,
  1807. MouseInputSource::invalidPressure, getEventTime (buttonRelEvent));
  1808. clearLastMousePos();
  1809. }
  1810. void handleMotionNotifyEvent (const XPointerMovedEvent& movedEvent)
  1811. {
  1812. updateKeyModifiers ((int) movedEvent.state);
  1813. lastMousePos = Point<int> (movedEvent.x_root, movedEvent.y_root);
  1814. if (dragState->dragging)
  1815. handleExternalDragMotionNotify();
  1816. handleMouseEvent (0, getMousePos (movedEvent), currentModifiers,
  1817. MouseInputSource::invalidPressure, getEventTime (movedEvent));
  1818. }
  1819. void handleEnterNotifyEvent (const XEnterWindowEvent& enterEvent)
  1820. {
  1821. if (parentWindow != 0)
  1822. updateWindowBounds();
  1823. clearLastMousePos();
  1824. if (! currentModifiers.isAnyMouseButtonDown())
  1825. {
  1826. updateKeyModifiers ((int) enterEvent.state);
  1827. handleMouseEvent (0, getMousePos (enterEvent), currentModifiers,
  1828. MouseInputSource::invalidPressure, getEventTime (enterEvent));
  1829. }
  1830. }
  1831. void handleLeaveNotifyEvent (const XLeaveWindowEvent& leaveEvent)
  1832. {
  1833. // Suppress the normal leave if we've got a pointer grab, or if
  1834. // it's a bogus one caused by clicking a mouse button when running
  1835. // in a Window manager
  1836. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent.mode == NotifyNormal)
  1837. || leaveEvent.mode == NotifyUngrab)
  1838. {
  1839. updateKeyModifiers ((int) leaveEvent.state);
  1840. handleMouseEvent (0, getMousePos (leaveEvent), currentModifiers,
  1841. MouseInputSource::invalidPressure, getEventTime (leaveEvent));
  1842. }
  1843. }
  1844. void handleFocusInEvent()
  1845. {
  1846. isActiveApplication = true;
  1847. if (isFocused())
  1848. handleFocusGain();
  1849. }
  1850. void handleFocusOutEvent()
  1851. {
  1852. isActiveApplication = false;
  1853. if (! isFocused())
  1854. handleFocusLoss();
  1855. }
  1856. void handleExposeEvent (XExposeEvent& exposeEvent)
  1857. {
  1858. // Batch together all pending expose events
  1859. XEvent nextEvent;
  1860. ScopedXLock xlock (display);
  1861. // if we have opengl contexts then just repaint them all
  1862. // regardless if this is really necessary
  1863. repaintOpenGLContexts();
  1864. if (exposeEvent.window != windowH)
  1865. {
  1866. Window child;
  1867. XTranslateCoordinates (display, exposeEvent.window, windowH,
  1868. exposeEvent.x, exposeEvent.y, &exposeEvent.x, &exposeEvent.y,
  1869. &child);
  1870. }
  1871. // exposeEvent is in local window local coordinates so do not convert with
  1872. // physicalToScaled, but rather use currentScaleFactor
  1873. repaint (Rectangle<int> (exposeEvent.x, exposeEvent.y,
  1874. exposeEvent.width, exposeEvent.height) / currentScaleFactor);
  1875. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  1876. {
  1877. XPeekEvent (display, &nextEvent);
  1878. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent.window)
  1879. break;
  1880. XNextEvent (display, &nextEvent);
  1881. const XExposeEvent& nextExposeEvent = (const XExposeEvent&) nextEvent.xexpose;
  1882. repaint (Rectangle<int> (nextExposeEvent.x, nextExposeEvent.y,
  1883. nextExposeEvent.width, nextExposeEvent.height) / currentScaleFactor);
  1884. }
  1885. }
  1886. void handleConfigureNotifyEvent (XConfigureEvent& confEvent)
  1887. {
  1888. updateWindowBounds();
  1889. updateBorderSize();
  1890. handleMovedOrResized();
  1891. // if the native title bar is dragged, need to tell any active menus, etc.
  1892. if ((styleFlags & windowHasTitleBar) != 0
  1893. && component.isCurrentlyBlockedByAnotherModalComponent())
  1894. {
  1895. if (Component* const currentModalComp = Component::getCurrentlyModalComponent())
  1896. currentModalComp->inputAttemptWhenModal();
  1897. }
  1898. if (confEvent.window == windowH
  1899. && confEvent.above != 0
  1900. && isFrontWindow())
  1901. {
  1902. handleBroughtToFront();
  1903. }
  1904. }
  1905. void handleReparentNotifyEvent()
  1906. {
  1907. parentWindow = 0;
  1908. Window wRoot = 0;
  1909. Window* wChild = nullptr;
  1910. unsigned int numChildren;
  1911. {
  1912. ScopedXLock xlock (display);
  1913. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  1914. }
  1915. if (parentWindow == windowH || parentWindow == wRoot)
  1916. parentWindow = 0;
  1917. handleGravityNotify();
  1918. }
  1919. void handleGravityNotify()
  1920. {
  1921. updateWindowBounds();
  1922. updateBorderSize();
  1923. handleMovedOrResized();
  1924. }
  1925. void handleMappingNotify (XMappingEvent& mappingEvent)
  1926. {
  1927. if (mappingEvent.request != MappingPointer)
  1928. {
  1929. // Deal with modifier/keyboard mapping
  1930. ScopedXLock xlock (display);
  1931. XRefreshKeyboardMapping (&mappingEvent);
  1932. updateModifierMappings();
  1933. }
  1934. }
  1935. void handleClientMessageEvent (XClientMessageEvent& clientMsg, XEvent& event)
  1936. {
  1937. if (clientMsg.message_type == atoms->protocols && clientMsg.format == 32)
  1938. {
  1939. const Atom atom = (Atom) clientMsg.data.l[0];
  1940. if (atom == atoms->protocolList [Atoms::PING])
  1941. {
  1942. Window root = RootWindow (display, DefaultScreen (display));
  1943. clientMsg.window = root;
  1944. XSendEvent (display, root, False, NoEventMask, &event);
  1945. XFlush (display);
  1946. }
  1947. else if (atom == atoms->protocolList [Atoms::TAKE_FOCUS])
  1948. {
  1949. if ((getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0)
  1950. {
  1951. XWindowAttributes atts;
  1952. ScopedXLock xlock (display);
  1953. if (clientMsg.window != 0
  1954. && XGetWindowAttributes (display, clientMsg.window, &atts))
  1955. {
  1956. if (atts.map_state == IsViewable)
  1957. XSetInputFocus (display, clientMsg.window, RevertToParent, (::Time) clientMsg.data.l[1]);
  1958. }
  1959. }
  1960. }
  1961. else if (atom == atoms->protocolList [Atoms::DELETE_WINDOW])
  1962. {
  1963. handleUserClosingWindow();
  1964. }
  1965. }
  1966. else if (clientMsg.message_type == atoms->XdndEnter)
  1967. {
  1968. handleDragAndDropEnter (clientMsg);
  1969. }
  1970. else if (clientMsg.message_type == atoms->XdndLeave)
  1971. {
  1972. handleDragExit (dragInfo);
  1973. resetDragAndDrop();
  1974. }
  1975. else if (clientMsg.message_type == atoms->XdndPosition)
  1976. {
  1977. handleDragAndDropPosition (clientMsg);
  1978. }
  1979. else if (clientMsg.message_type == atoms->XdndDrop)
  1980. {
  1981. handleDragAndDropDrop (clientMsg);
  1982. }
  1983. else if (clientMsg.message_type == atoms->XdndStatus)
  1984. {
  1985. handleExternalDragAndDropStatus (clientMsg);
  1986. }
  1987. else if (clientMsg.message_type == atoms->XdndFinished)
  1988. {
  1989. externalResetDragAndDrop();
  1990. }
  1991. }
  1992. bool externalDragTextInit (const String& text)
  1993. {
  1994. if (dragState->dragging)
  1995. return false;
  1996. return externalDragInit (true, text);
  1997. }
  1998. bool externalDragFileInit (const StringArray& files, bool /*canMoveFiles*/)
  1999. {
  2000. if (dragState->dragging)
  2001. return false;
  2002. StringArray uriList;
  2003. for (int i = 0; i < files.size(); ++i)
  2004. {
  2005. const String& f = files[i];
  2006. if (f.matchesWildcard ("?*://*", false))
  2007. uriList.add (f);
  2008. else
  2009. uriList.add ("file://" + f);
  2010. }
  2011. return externalDragInit (false, uriList.joinIntoString ("\r\n"));
  2012. }
  2013. //==============================================================================
  2014. void showMouseCursor (Cursor cursor) noexcept
  2015. {
  2016. ScopedXLock xlock (display);
  2017. XDefineCursor (display, windowH, cursor);
  2018. }
  2019. //==============================================================================
  2020. double getCurrentScale() noexcept
  2021. {
  2022. return currentScaleFactor;
  2023. }
  2024. //==============================================================================
  2025. void addOpenGLRepaintListener (Component* dummy)
  2026. {
  2027. if (dummy != nullptr)
  2028. glRepaintListeners.addIfNotAlreadyThere (dummy);
  2029. }
  2030. void removeOpenGLRepaintListener (Component* dummy)
  2031. {
  2032. if (dummy != nullptr)
  2033. glRepaintListeners.removeAllInstancesOf (dummy);
  2034. }
  2035. void repaintOpenGLContexts()
  2036. {
  2037. for (int i = 0; i < glRepaintListeners.size(); ++i)
  2038. {
  2039. if (Component* c = glRepaintListeners [i])
  2040. c->handleCommandMessage (0);
  2041. }
  2042. }
  2043. //==============================================================================
  2044. bool dontRepaint;
  2045. static ModifierKeys currentModifiers;
  2046. static bool isActiveApplication;
  2047. private:
  2048. //==============================================================================
  2049. class LinuxRepaintManager : public Timer
  2050. {
  2051. public:
  2052. LinuxRepaintManager (LinuxComponentPeer& p, ::Display* _display)
  2053. : peer (p), lastTimeImageUsed (0),
  2054. display (_display)
  2055. {
  2056. #if JUCE_USE_XSHM
  2057. shmPaintsPending = 0;
  2058. useARGBImagesForRendering = XSHMHelpers::isShmAvailable (display);
  2059. if (useARGBImagesForRendering)
  2060. {
  2061. ScopedXLock xlock (display);
  2062. XShmSegmentInfo segmentinfo;
  2063. XImage* const testImage
  2064. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  2065. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  2066. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  2067. XDestroyImage (testImage);
  2068. }
  2069. #endif
  2070. }
  2071. void timerCallback() override
  2072. {
  2073. #if JUCE_USE_XSHM
  2074. if (shmPaintsPending != 0)
  2075. return;
  2076. #endif
  2077. if (! regionsNeedingRepaint.isEmpty())
  2078. {
  2079. stopTimer();
  2080. performAnyPendingRepaintsNow();
  2081. }
  2082. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  2083. {
  2084. stopTimer();
  2085. image = Image();
  2086. }
  2087. }
  2088. void repaint (const Rectangle<int>& area)
  2089. {
  2090. if (! isTimerRunning())
  2091. startTimer (repaintTimerPeriod);
  2092. regionsNeedingRepaint.add (area * peer.currentScaleFactor);
  2093. }
  2094. void performAnyPendingRepaintsNow()
  2095. {
  2096. #if JUCE_USE_XSHM
  2097. if (shmPaintsPending != 0)
  2098. {
  2099. startTimer (repaintTimerPeriod);
  2100. return;
  2101. }
  2102. #endif
  2103. RectangleList<int> originalRepaintRegion (regionsNeedingRepaint);
  2104. regionsNeedingRepaint.clear();
  2105. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  2106. if (! totalArea.isEmpty())
  2107. {
  2108. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  2109. || image.getHeight() < totalArea.getHeight())
  2110. {
  2111. #if JUCE_USE_XSHM
  2112. image = Image (new XBitmapImage (display, useARGBImagesForRendering ? Image::ARGB
  2113. : Image::RGB,
  2114. #else
  2115. image = Image (new XBitmapImage (display, Image::RGB,
  2116. #endif
  2117. (totalArea.getWidth() + 31) & ~31,
  2118. (totalArea.getHeight() + 31) & ~31,
  2119. false, (unsigned int) peer.depth, peer.visual));
  2120. }
  2121. startTimer (repaintTimerPeriod);
  2122. RectangleList<int> adjustedList (originalRepaintRegion);
  2123. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  2124. if (peer.depth == 32)
  2125. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  2126. image.clear (*i - totalArea.getPosition());
  2127. {
  2128. ScopedPointer<LowLevelGraphicsContext> context (peer.getComponent().getLookAndFeel()
  2129. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList));
  2130. context->addTransform (AffineTransform::scale ((float) peer.currentScaleFactor));
  2131. peer.handlePaint (*context);
  2132. }
  2133. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  2134. {
  2135. XBitmapImage* xbitmap = static_cast<XBitmapImage*> (image.getPixelData());
  2136. #if JUCE_USE_XSHM
  2137. if (xbitmap->isUsingXShm())
  2138. ++shmPaintsPending;
  2139. #endif
  2140. xbitmap->blitToWindow (peer.windowH,
  2141. i->getX(), i->getY(),
  2142. (unsigned int) i->getWidth(),
  2143. (unsigned int) i->getHeight(),
  2144. i->getX() - totalArea.getX(), i->getY() - totalArea.getY());
  2145. }
  2146. }
  2147. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  2148. startTimer (repaintTimerPeriod);
  2149. }
  2150. #if JUCE_USE_XSHM
  2151. void notifyPaintCompleted() noexcept { --shmPaintsPending; }
  2152. #endif
  2153. private:
  2154. enum { repaintTimerPeriod = 1000 / 100 };
  2155. LinuxComponentPeer& peer;
  2156. Image image;
  2157. uint32 lastTimeImageUsed;
  2158. RectangleList<int> regionsNeedingRepaint;
  2159. ::Display* display;
  2160. #if JUCE_USE_XSHM
  2161. bool useARGBImagesForRendering;
  2162. int shmPaintsPending;
  2163. #endif
  2164. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  2165. };
  2166. ScopedPointer<Atoms> atoms;
  2167. ScopedPointer<LinuxRepaintManager> repainter;
  2168. friend class LinuxRepaintManager;
  2169. Window windowH, parentWindow;
  2170. Rectangle<int> bounds;
  2171. Image taskbarImage;
  2172. bool fullScreen, mapped;
  2173. Visual* visual;
  2174. int depth;
  2175. BorderSize<int> windowBorder;
  2176. bool isAlwaysOnTop;
  2177. double currentScaleFactor;
  2178. Array<Component*> glRepaintListeners;
  2179. enum { KeyPressEventType = 2 };
  2180. static ::Display* display;
  2181. struct MotifWmHints
  2182. {
  2183. unsigned long flags;
  2184. unsigned long functions;
  2185. unsigned long decorations;
  2186. long input_mode;
  2187. unsigned long status;
  2188. };
  2189. static void updateKeyStates (const int keycode, const bool press) noexcept
  2190. {
  2191. const int keybyte = keycode >> 3;
  2192. const int keybit = (1 << (keycode & 7));
  2193. if (press)
  2194. Keys::keyStates [keybyte] |= keybit;
  2195. else
  2196. Keys::keyStates [keybyte] &= ~keybit;
  2197. }
  2198. static void updateKeyModifiers (const int status) noexcept
  2199. {
  2200. int keyMods = 0;
  2201. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  2202. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  2203. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  2204. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  2205. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  2206. Keys::capsLock = ((status & LockMask) != 0);
  2207. }
  2208. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) noexcept
  2209. {
  2210. int modifier = 0;
  2211. bool isModifier = true;
  2212. switch (sym)
  2213. {
  2214. case XK_Shift_L:
  2215. case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
  2216. case XK_Control_L:
  2217. case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
  2218. case XK_Alt_L:
  2219. case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
  2220. case XK_Num_Lock:
  2221. if (press)
  2222. Keys::numLock = ! Keys::numLock;
  2223. break;
  2224. case XK_Caps_Lock:
  2225. if (press)
  2226. Keys::capsLock = ! Keys::capsLock;
  2227. break;
  2228. case XK_Scroll_Lock:
  2229. break;
  2230. default:
  2231. isModifier = false;
  2232. break;
  2233. }
  2234. currentModifiers = press ? currentModifiers.withFlags (modifier)
  2235. : currentModifiers.withoutFlags (modifier);
  2236. return isModifier;
  2237. }
  2238. // Alt and Num lock are not defined by standard X
  2239. // modifier constants: check what they're mapped to
  2240. static void updateModifierMappings() noexcept
  2241. {
  2242. ScopedXLock xlock (display);
  2243. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  2244. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  2245. Keys::AltMask = 0;
  2246. Keys::NumLockMask = 0;
  2247. if (XModifierKeymap* const mapping = XGetModifierMapping (display))
  2248. {
  2249. for (int i = 0; i < 8; i++)
  2250. {
  2251. if (mapping->modifiermap [i << 1] == altLeftCode)
  2252. Keys::AltMask = 1 << i;
  2253. else if (mapping->modifiermap [i << 1] == numLockCode)
  2254. Keys::NumLockMask = 1 << i;
  2255. }
  2256. XFreeModifiermap (mapping);
  2257. }
  2258. }
  2259. //==============================================================================
  2260. static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
  2261. {
  2262. XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  2263. }
  2264. void removeWindowDecorations (Window wndH)
  2265. {
  2266. Atom hints = Atoms::getIfExists (display, "_MOTIF_WM_HINTS");
  2267. if (hints != None)
  2268. {
  2269. MotifWmHints motifHints;
  2270. zerostruct (motifHints);
  2271. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  2272. motifHints.decorations = 0;
  2273. ScopedXLock xlock (display);
  2274. xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
  2275. }
  2276. hints = Atoms::getIfExists (display, "_WIN_HINTS");
  2277. if (hints != None)
  2278. {
  2279. long gnomeHints = 0;
  2280. ScopedXLock xlock (display);
  2281. xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
  2282. }
  2283. hints = Atoms::getIfExists (display, "KWM_WIN_DECORATION");
  2284. if (hints != None)
  2285. {
  2286. long kwmHints = 2; /*KDE_tinyDecoration*/
  2287. ScopedXLock xlock (display);
  2288. xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
  2289. }
  2290. hints = Atoms::getIfExists (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  2291. if (hints != None)
  2292. {
  2293. ScopedXLock xlock (display);
  2294. xchangeProperty (wndH, atoms->windowType, XA_ATOM, 32, &hints, 1);
  2295. }
  2296. }
  2297. void addWindowButtons (Window wndH)
  2298. {
  2299. ScopedXLock xlock (display);
  2300. Atom hints = Atoms::getIfExists (display, "_MOTIF_WM_HINTS");
  2301. if (hints != None)
  2302. {
  2303. MotifWmHints motifHints;
  2304. zerostruct (motifHints);
  2305. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  2306. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  2307. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  2308. if ((styleFlags & windowHasCloseButton) != 0)
  2309. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  2310. if ((styleFlags & windowHasMinimiseButton) != 0)
  2311. {
  2312. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  2313. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  2314. }
  2315. if ((styleFlags & windowHasMaximiseButton) != 0)
  2316. {
  2317. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  2318. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  2319. }
  2320. if ((styleFlags & windowIsResizable) != 0)
  2321. {
  2322. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  2323. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  2324. }
  2325. xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
  2326. }
  2327. hints = Atoms::getIfExists (display, "_NET_WM_ALLOWED_ACTIONS");
  2328. if (hints != None)
  2329. {
  2330. Atom netHints [6];
  2331. int num = 0;
  2332. if ((styleFlags & windowIsResizable) != 0)
  2333. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_RESIZE");
  2334. if ((styleFlags & windowHasMaximiseButton) != 0)
  2335. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_FULLSCREEN");
  2336. if ((styleFlags & windowHasMinimiseButton) != 0)
  2337. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_MINIMIZE");
  2338. if ((styleFlags & windowHasCloseButton) != 0)
  2339. netHints [num++] = Atoms::getIfExists (display, "_NET_WM_ACTION_CLOSE");
  2340. xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
  2341. }
  2342. }
  2343. void setWindowType()
  2344. {
  2345. Atom netHints [2];
  2346. if ((styleFlags & windowIsTemporary) != 0
  2347. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  2348. netHints [0] = Atoms::getIfExists (display, "_NET_WM_WINDOW_TYPE_COMBO");
  2349. else
  2350. netHints [0] = Atoms::getIfExists (display, "_NET_WM_WINDOW_TYPE_NORMAL");
  2351. xchangeProperty (windowH, atoms->windowType, XA_ATOM, 32, &netHints, 1);
  2352. int numHints = 0;
  2353. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  2354. netHints [numHints++] = Atoms::getIfExists (display, "_NET_WM_STATE_SKIP_TASKBAR");
  2355. if (component.isAlwaysOnTop())
  2356. netHints [numHints++] = Atoms::getIfExists (display, "_NET_WM_STATE_ABOVE");
  2357. if (numHints > 0)
  2358. xchangeProperty (windowH, atoms->windowState, XA_ATOM, 32, &netHints, numHints);
  2359. }
  2360. void createWindow (Window parentToAddTo)
  2361. {
  2362. ScopedXLock xlock (display);
  2363. resetDragAndDrop();
  2364. // Get defaults for various properties
  2365. const int screen = DefaultScreen (display);
  2366. Window root = RootWindow (display, screen);
  2367. parentWindow = parentToAddTo;
  2368. // Try to obtain a 32-bit visual or fallback to 24 or 16
  2369. visual = Visuals::findVisualFormat (display, (styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  2370. if (visual == nullptr)
  2371. {
  2372. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  2373. Process::terminate();
  2374. }
  2375. // Create and install a colormap suitable fr our visual
  2376. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  2377. XInstallColormap (display, colormap);
  2378. // Set up the window attributes
  2379. XSetWindowAttributes swa;
  2380. swa.border_pixel = 0;
  2381. swa.background_pixmap = None;
  2382. swa.colormap = colormap;
  2383. swa.override_redirect = ((styleFlags & windowIsTemporary) != 0) ? True : False;
  2384. swa.event_mask = getAllEventsMask();
  2385. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  2386. 0, 0, 1, 1,
  2387. 0, depth, InputOutput, visual,
  2388. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  2389. &swa);
  2390. unsigned int buttonMask = EnterWindowMask | LeaveWindowMask | PointerMotionMask;
  2391. if ((styleFlags & windowIgnoresMouseClicks) == 0)
  2392. buttonMask |= ButtonPressMask | ButtonReleaseMask;
  2393. // Set the window context to identify the window handle object
  2394. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  2395. {
  2396. // Failed
  2397. jassertfalse;
  2398. Logger::outputDebugString ("Failed to create context information for window.\n");
  2399. XDestroyWindow (display, windowH);
  2400. windowH = 0;
  2401. return;
  2402. }
  2403. // Set window manager hints
  2404. XWMHints* wmHints = XAllocWMHints();
  2405. wmHints->flags = InputHint | StateHint;
  2406. wmHints->input = True; // Locally active input model
  2407. wmHints->initial_state = NormalState;
  2408. XSetWMHints (display, windowH, wmHints);
  2409. XFree (wmHints);
  2410. // Set the window type
  2411. setWindowType();
  2412. // Define decoration
  2413. if ((styleFlags & windowHasTitleBar) == 0)
  2414. removeWindowDecorations (windowH);
  2415. else
  2416. addWindowButtons (windowH);
  2417. setTitle (component.getName());
  2418. // Associate the PID, allowing to be shut down when something goes wrong
  2419. unsigned long pid = (unsigned long) getpid();
  2420. xchangeProperty (windowH, atoms->pid, XA_CARDINAL, 32, &pid, 1);
  2421. // Set window manager protocols
  2422. xchangeProperty (windowH, atoms->protocols, XA_ATOM, 32, atoms->protocolList, 2);
  2423. // Set drag and drop flags
  2424. xchangeProperty (windowH, atoms->XdndTypeList, XA_ATOM, 32, atoms->allowedMimeTypes, numElementsInArray (atoms->allowedMimeTypes));
  2425. xchangeProperty (windowH, atoms->XdndActionList, XA_ATOM, 32, atoms->allowedActions, numElementsInArray (atoms->allowedActions));
  2426. xchangeProperty (windowH, atoms->XdndActionDescription, XA_STRING, 8, "", 0);
  2427. xchangeProperty (windowH, atoms->XdndAware, XA_ATOM, 32, &atoms->DndVersion, 1);
  2428. initialisePointerMap();
  2429. updateModifierMappings();
  2430. }
  2431. void destroyWindow()
  2432. {
  2433. ScopedXLock xlock (display);
  2434. XPointer handlePointer;
  2435. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  2436. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  2437. XDestroyWindow (display, windowH);
  2438. // Wait for it to complete and then remove any events for this
  2439. // window from the event queue.
  2440. XSync (display, false);
  2441. XEvent event;
  2442. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  2443. {}
  2444. }
  2445. int getAllEventsMask() const noexcept
  2446. {
  2447. return NoEventMask | KeyPressMask | KeyReleaseMask
  2448. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  2449. | ExposureMask | StructureNotifyMask | FocusChangeMask
  2450. | ((styleFlags & windowIgnoresMouseClicks) != 0 ? 0 : (ButtonPressMask | ButtonReleaseMask));
  2451. }
  2452. template <typename EventType>
  2453. static int64 getEventTime (const EventType& t)
  2454. {
  2455. return getEventTime (t.time);
  2456. }
  2457. static int64 getEventTime (::Time t)
  2458. {
  2459. static int64 eventTimeOffset = 0x12345678;
  2460. const int64 thisMessageTime = (int64) t;
  2461. if (eventTimeOffset == 0x12345678)
  2462. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  2463. return eventTimeOffset + thisMessageTime;
  2464. }
  2465. long getUserTime() const
  2466. {
  2467. GetXProperty prop (display, windowH, atoms->userTime, 0, 65536, false, XA_CARDINAL);
  2468. return prop.success ? *(long*) prop.data : 0;
  2469. }
  2470. void updateBorderSize()
  2471. {
  2472. if ((styleFlags & windowHasTitleBar) == 0)
  2473. {
  2474. windowBorder = BorderSize<int> (0);
  2475. }
  2476. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  2477. {
  2478. ScopedXLock xlock (display);
  2479. Atom hints = Atoms::getIfExists (display, "_NET_FRAME_EXTENTS");
  2480. if (hints != None)
  2481. {
  2482. GetXProperty prop (display, windowH, hints, 0, 4, false, XA_CARDINAL);
  2483. if (prop.success && prop.actualFormat == 32)
  2484. {
  2485. const unsigned long* const sizes = (const unsigned long*) prop.data;
  2486. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  2487. (int) sizes[3], (int) sizes[1]);
  2488. }
  2489. }
  2490. }
  2491. }
  2492. void updateWindowBounds()
  2493. {
  2494. jassert (windowH != 0);
  2495. if (windowH != 0)
  2496. {
  2497. Window root, child;
  2498. int wx = 0, wy = 0;
  2499. unsigned int ww = 0, wh = 0, bw, bitDepth;
  2500. ScopedXLock xlock (display);
  2501. if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth))
  2502. if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  2503. wx = wy = 0;
  2504. Rectangle<int> physicalBounds (wx, wy, (int) ww, (int) wh);
  2505. currentScaleFactor =
  2506. DisplayGeometry::getInstance().findDisplayForRect (physicalBounds, false).scale;
  2507. bounds = DisplayGeometry::physicalToScaled (physicalBounds);
  2508. }
  2509. }
  2510. //==============================================================================
  2511. struct DragState
  2512. {
  2513. DragState(::Display* _display)
  2514. : isText (false), dragging (false), expectingStatus (false),
  2515. canDrop (false), targetWindow (None), xdndVersion (-1)
  2516. {
  2517. if (isText)
  2518. allowedTypes.add (Atoms::getCreating (_display, "text/plain"));
  2519. else
  2520. allowedTypes.add (Atoms::getCreating (_display, "text/uri-list"));
  2521. }
  2522. bool isText;
  2523. bool dragging; // currently performing outgoing external dnd as Xdnd source, have grabbed mouse
  2524. bool expectingStatus; // XdndPosition sent, waiting for XdndStatus
  2525. bool canDrop; // target window signals it will accept the drop
  2526. Window targetWindow; // potential drop target
  2527. int xdndVersion; // negotiated version with target
  2528. Rectangle<int> silentRect;
  2529. String textOrFiles;
  2530. Array<Atom> allowedTypes;
  2531. };
  2532. //==============================================================================
  2533. void resetDragAndDrop()
  2534. {
  2535. dragInfo.clear();
  2536. dragInfo.position = Point<int> (-1, -1);
  2537. dragAndDropCurrentMimeType = 0;
  2538. dragAndDropSourceWindow = 0;
  2539. srcMimeTypeAtomList.clear();
  2540. finishAfterDropDataReceived = false;
  2541. }
  2542. void resetExternalDragState()
  2543. {
  2544. dragState = new DragState (display);
  2545. }
  2546. void sendDragAndDropMessage (XClientMessageEvent& msg)
  2547. {
  2548. msg.type = ClientMessage;
  2549. msg.display = display;
  2550. msg.window = dragAndDropSourceWindow;
  2551. msg.format = 32;
  2552. msg.data.l[0] = (long) windowH;
  2553. ScopedXLock xlock (display);
  2554. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  2555. }
  2556. bool sendExternalDragAndDropMessage (XClientMessageEvent& msg, const Window targetWindow)
  2557. {
  2558. msg.type = ClientMessage;
  2559. msg.display = display;
  2560. msg.window = targetWindow;
  2561. msg.format = 32;
  2562. msg.data.l[0] = (long) windowH;
  2563. ScopedXLock xlock (display);
  2564. return XSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
  2565. }
  2566. void sendExternalDragAndDropDrop (const Window targetWindow)
  2567. {
  2568. XClientMessageEvent msg;
  2569. zerostruct (msg);
  2570. msg.message_type = atoms->XdndDrop;
  2571. msg.data.l[2] = CurrentTime;
  2572. sendExternalDragAndDropMessage (msg, targetWindow);
  2573. }
  2574. void sendExternalDragAndDropEnter (const Window targetWindow)
  2575. {
  2576. XClientMessageEvent msg;
  2577. zerostruct (msg);
  2578. msg.message_type = atoms->XdndEnter;
  2579. msg.data.l[1] = (dragState->xdndVersion << 24);
  2580. for (int i = 0; i < 3; ++i)
  2581. msg.data.l[i + 2] = (long) dragState->allowedTypes[i];
  2582. sendExternalDragAndDropMessage (msg, targetWindow);
  2583. }
  2584. void sendExternalDragAndDropPosition (const Window targetWindow)
  2585. {
  2586. XClientMessageEvent msg;
  2587. zerostruct (msg);
  2588. msg.message_type = atoms->XdndPosition;
  2589. Point<int> mousePos (Desktop::getInstance().getMousePosition());
  2590. if (dragState->silentRect.contains (mousePos)) // we've been asked to keep silent
  2591. return;
  2592. mousePos = DisplayGeometry::scaledToPhysical (mousePos);
  2593. msg.data.l[1] = 0;
  2594. msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
  2595. msg.data.l[3] = CurrentTime;
  2596. msg.data.l[4] = (long) atoms->XdndActionCopy; // this is all JUCE currently supports
  2597. dragState->expectingStatus = sendExternalDragAndDropMessage (msg, targetWindow);
  2598. }
  2599. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  2600. {
  2601. XClientMessageEvent msg;
  2602. zerostruct (msg);
  2603. msg.message_type = atoms->XdndStatus;
  2604. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  2605. msg.data.l[4] = (long) dropAction;
  2606. sendDragAndDropMessage (msg);
  2607. }
  2608. void sendExternalDragAndDropLeave (const Window targetWindow)
  2609. {
  2610. XClientMessageEvent msg;
  2611. zerostruct (msg);
  2612. msg.message_type = atoms->XdndLeave;
  2613. sendExternalDragAndDropMessage (msg, targetWindow);
  2614. }
  2615. void sendDragAndDropFinish()
  2616. {
  2617. XClientMessageEvent msg;
  2618. zerostruct (msg);
  2619. msg.message_type = atoms->XdndFinished;
  2620. sendDragAndDropMessage (msg);
  2621. }
  2622. void handleExternalSelectionClear()
  2623. {
  2624. if (dragState->dragging)
  2625. externalResetDragAndDrop();
  2626. }
  2627. void handleExternalSelectionRequest (const XEvent& evt)
  2628. {
  2629. Atom targetType = evt.xselectionrequest.target;
  2630. XEvent s;
  2631. s.xselection.type = SelectionNotify;
  2632. s.xselection.requestor = evt.xselectionrequest.requestor;
  2633. s.xselection.selection = evt.xselectionrequest.selection;
  2634. s.xselection.target = targetType;
  2635. s.xselection.property = None;
  2636. s.xselection.time = evt.xselectionrequest.time;
  2637. if (dragState->allowedTypes.contains (targetType))
  2638. {
  2639. s.xselection.property = evt.xselectionrequest.property;
  2640. xchangeProperty (evt.xselectionrequest.requestor,
  2641. evt.xselectionrequest.property,
  2642. targetType, 8,
  2643. dragState->textOrFiles.toRawUTF8(),
  2644. (int) dragState->textOrFiles.getNumBytesAsUTF8());
  2645. }
  2646. XSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
  2647. }
  2648. void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
  2649. {
  2650. if (dragState->expectingStatus)
  2651. {
  2652. dragState->expectingStatus = false;
  2653. dragState->canDrop = false;
  2654. dragState->silentRect = Rectangle<int>();
  2655. if ((clientMsg.data.l[1] & 1) != 0
  2656. && ((Atom) clientMsg.data.l[4] == atoms->XdndActionCopy
  2657. || (Atom) clientMsg.data.l[4] == atoms->XdndActionPrivate))
  2658. {
  2659. if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
  2660. dragState->silentRect.setBounds ((int) clientMsg.data.l[2] >> 16,
  2661. (int) clientMsg.data.l[2] & 0xffff,
  2662. (int) clientMsg.data.l[3] >> 16,
  2663. (int) clientMsg.data.l[3] & 0xffff);
  2664. dragState->canDrop = true;
  2665. }
  2666. }
  2667. }
  2668. void handleExternalDragButtonReleaseEvent()
  2669. {
  2670. if (dragState->dragging)
  2671. XUngrabPointer (display, CurrentTime);
  2672. if (dragState->canDrop)
  2673. {
  2674. sendExternalDragAndDropDrop (dragState->targetWindow);
  2675. }
  2676. else
  2677. {
  2678. sendExternalDragAndDropLeave (dragState->targetWindow);
  2679. externalResetDragAndDrop();
  2680. }
  2681. }
  2682. void handleExternalDragMotionNotify()
  2683. {
  2684. Window targetWindow = externalFindDragTargetWindow (RootWindow (display, DefaultScreen (display)));
  2685. if (dragState->targetWindow != targetWindow)
  2686. {
  2687. if (dragState->targetWindow != None)
  2688. sendExternalDragAndDropLeave (dragState->targetWindow);
  2689. dragState->canDrop = false;
  2690. dragState->silentRect = Rectangle<int>();
  2691. if (targetWindow == None)
  2692. return;
  2693. GetXProperty prop (display, targetWindow, atoms->XdndAware,
  2694. 0, 2, false, AnyPropertyType);
  2695. if (prop.success
  2696. && prop.data != None
  2697. && prop.actualFormat == 32
  2698. && prop.numItems == 1)
  2699. {
  2700. dragState->xdndVersion = jmin ((int) prop.data[0], (int) atoms->DndVersion);
  2701. }
  2702. else
  2703. {
  2704. dragState->xdndVersion = -1;
  2705. return;
  2706. }
  2707. sendExternalDragAndDropEnter (targetWindow);
  2708. dragState->targetWindow = targetWindow;
  2709. }
  2710. if (! dragState->expectingStatus)
  2711. sendExternalDragAndDropPosition (targetWindow);
  2712. }
  2713. void handleDragAndDropPosition (const XClientMessageEvent& clientMsg)
  2714. {
  2715. if (dragAndDropSourceWindow == 0)
  2716. return;
  2717. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2718. Point<int> dropPos ((int) clientMsg.data.l[2] >> 16,
  2719. (int) clientMsg.data.l[2] & 0xffff);
  2720. dropPos -= bounds.getPosition();
  2721. Atom targetAction = atoms->XdndActionCopy;
  2722. for (int i = numElementsInArray (atoms->allowedActions); --i >= 0;)
  2723. {
  2724. if ((Atom) clientMsg.data.l[4] == atoms->allowedActions[i])
  2725. {
  2726. targetAction = atoms->allowedActions[i];
  2727. break;
  2728. }
  2729. }
  2730. sendDragAndDropStatus (true, targetAction);
  2731. if (dragInfo.position != dropPos)
  2732. {
  2733. dragInfo.position = dropPos;
  2734. if (dragInfo.isEmpty())
  2735. updateDraggedFileList (clientMsg);
  2736. if (! dragInfo.isEmpty())
  2737. handleDragMove (dragInfo);
  2738. }
  2739. }
  2740. void handleDragAndDropDrop (const XClientMessageEvent& clientMsg)
  2741. {
  2742. if (dragInfo.isEmpty())
  2743. {
  2744. // no data, transaction finished in handleDragAndDropSelection()
  2745. finishAfterDropDataReceived = true;
  2746. updateDraggedFileList (clientMsg);
  2747. }
  2748. else
  2749. {
  2750. handleDragAndDropDataReceived(); // data was already received
  2751. }
  2752. }
  2753. void handleDragAndDropDataReceived()
  2754. {
  2755. DragInfo dragInfoCopy (dragInfo);
  2756. sendDragAndDropFinish();
  2757. resetDragAndDrop();
  2758. if (! dragInfoCopy.isEmpty())
  2759. handleDragDrop (dragInfoCopy);
  2760. }
  2761. void handleDragAndDropEnter (const XClientMessageEvent& clientMsg)
  2762. {
  2763. dragInfo.clear();
  2764. srcMimeTypeAtomList.clear();
  2765. dragAndDropCurrentMimeType = 0;
  2766. const unsigned long dndCurrentVersion = static_cast<unsigned long> (clientMsg.data.l[1] & 0xff000000) >> 24;
  2767. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  2768. {
  2769. dragAndDropSourceWindow = 0;
  2770. return;
  2771. }
  2772. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2773. if ((clientMsg.data.l[1] & 1) != 0)
  2774. {
  2775. ScopedXLock xlock (display);
  2776. GetXProperty prop (display, dragAndDropSourceWindow, atoms->XdndTypeList, 0, 0x8000000L, false, XA_ATOM);
  2777. if (prop.success
  2778. && prop.actualType == XA_ATOM
  2779. && prop.actualFormat == 32
  2780. && prop.numItems != 0)
  2781. {
  2782. const unsigned long* const types = (const unsigned long*) prop.data;
  2783. for (unsigned long i = 0; i < prop.numItems; ++i)
  2784. if (types[i] != None)
  2785. srcMimeTypeAtomList.add (types[i]);
  2786. }
  2787. }
  2788. if (srcMimeTypeAtomList.size() == 0)
  2789. {
  2790. for (int i = 2; i < 5; ++i)
  2791. if (clientMsg.data.l[i] != None)
  2792. srcMimeTypeAtomList.add ((unsigned long) clientMsg.data.l[i]);
  2793. if (srcMimeTypeAtomList.size() == 0)
  2794. {
  2795. dragAndDropSourceWindow = 0;
  2796. return;
  2797. }
  2798. }
  2799. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  2800. for (int j = 0; j < numElementsInArray (atoms->allowedMimeTypes); ++j)
  2801. if (srcMimeTypeAtomList[i] == atoms->allowedMimeTypes[j])
  2802. dragAndDropCurrentMimeType = atoms->allowedMimeTypes[j];
  2803. handleDragAndDropPosition (clientMsg);
  2804. }
  2805. void handleDragAndDropSelection (const XEvent& evt)
  2806. {
  2807. dragInfo.clear();
  2808. if (evt.xselection.property != None)
  2809. {
  2810. StringArray lines;
  2811. {
  2812. MemoryBlock dropData;
  2813. for (;;)
  2814. {
  2815. GetXProperty prop (display, evt.xany.window, evt.xselection.property,
  2816. dropData.getSize() / 4, 65536, false, AnyPropertyType);
  2817. if (! prop.success)
  2818. break;
  2819. dropData.append (prop.data, prop.numItems * (size_t) prop.actualFormat / 8);
  2820. if (prop.bytesLeft <= 0)
  2821. break;
  2822. }
  2823. lines.addLines (dropData.toString());
  2824. }
  2825. if (Atoms::isMimeTypeFile (display, dragAndDropCurrentMimeType))
  2826. {
  2827. for (int i = 0; i < lines.size(); ++i)
  2828. dragInfo.files.add (URL::removeEscapeChars (lines[i].replace ("file://", String(), true)));
  2829. dragInfo.files.trim();
  2830. dragInfo.files.removeEmptyStrings();
  2831. }
  2832. else
  2833. {
  2834. dragInfo.text = lines.joinIntoString ("\n");
  2835. }
  2836. if (finishAfterDropDataReceived)
  2837. handleDragAndDropDataReceived();
  2838. }
  2839. }
  2840. void updateDraggedFileList (const XClientMessageEvent& clientMsg)
  2841. {
  2842. jassert (dragInfo.isEmpty());
  2843. if (dragAndDropSourceWindow != None
  2844. && dragAndDropCurrentMimeType != None)
  2845. {
  2846. ScopedXLock xlock (display);
  2847. XConvertSelection (display,
  2848. atoms->XdndSelection,
  2849. dragAndDropCurrentMimeType,
  2850. Atoms::getCreating (display, "JXSelectionWindowProperty"),
  2851. windowH,
  2852. (::Time) clientMsg.data.l[2]);
  2853. }
  2854. }
  2855. bool isWindowDnDAware (Window w) const
  2856. {
  2857. int numProperties = 0;
  2858. Atom* const properties = XListProperties (display, w, &numProperties);
  2859. bool dndAwarePropFound = false;
  2860. for (int i = 0; i < numProperties; ++i)
  2861. if (properties[i] == atoms->XdndAware)
  2862. dndAwarePropFound = true;
  2863. if (properties != nullptr)
  2864. XFree (properties);
  2865. return dndAwarePropFound;
  2866. }
  2867. Window externalFindDragTargetWindow (Window targetWindow)
  2868. {
  2869. if (targetWindow == None)
  2870. return None;
  2871. if (isWindowDnDAware (targetWindow))
  2872. return targetWindow;
  2873. Window child, phonyWin;
  2874. int phony;
  2875. unsigned int uphony;
  2876. XQueryPointer (display, targetWindow, &phonyWin, &child,
  2877. &phony, &phony, &phony, &phony, &uphony);
  2878. return externalFindDragTargetWindow (child);
  2879. }
  2880. bool externalDragInit (bool isText, const String& textOrFiles)
  2881. {
  2882. ScopedXLock xlock (display);
  2883. resetExternalDragState();
  2884. dragState->isText = isText;
  2885. dragState->textOrFiles = textOrFiles;
  2886. dragState->targetWindow = windowH;
  2887. const int pointerGrabMask = Button1MotionMask | ButtonReleaseMask;
  2888. if (XGrabPointer (display, windowH, True, pointerGrabMask,
  2889. GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
  2890. {
  2891. // No other method of changing the pointer seems to work, this call is needed from this very context
  2892. XChangeActivePointerGrab (display, pointerGrabMask, (Cursor) createDraggingHandCursor(), CurrentTime);
  2893. XSetSelectionOwner (display, atoms->XdndSelection, windowH, CurrentTime);
  2894. // save the available types to XdndTypeList
  2895. xchangeProperty (windowH, atoms->XdndTypeList, XA_ATOM, 32,
  2896. dragState->allowedTypes.getRawDataPointer(),
  2897. dragState->allowedTypes.size());
  2898. dragState->dragging = true;
  2899. handleExternalDragMotionNotify();
  2900. return true;
  2901. }
  2902. return false;
  2903. }
  2904. void externalResetDragAndDrop()
  2905. {
  2906. if (dragState->dragging)
  2907. {
  2908. ScopedXLock xlock (display);
  2909. XUngrabPointer (display, CurrentTime);
  2910. }
  2911. resetExternalDragState();
  2912. }
  2913. ScopedPointer<DragState> dragState;
  2914. DragInfo dragInfo;
  2915. Atom dragAndDropCurrentMimeType;
  2916. Window dragAndDropSourceWindow;
  2917. bool finishAfterDropDataReceived;
  2918. Array<Atom> srcMimeTypeAtomList;
  2919. int pointerMap[5];
  2920. void initialisePointerMap()
  2921. {
  2922. const int numButtons = XGetPointerMapping (display, 0, 0);
  2923. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2924. if (numButtons == 2)
  2925. {
  2926. pointerMap[0] = Keys::LeftButton;
  2927. pointerMap[1] = Keys::RightButton;
  2928. }
  2929. else if (numButtons >= 3)
  2930. {
  2931. pointerMap[0] = Keys::LeftButton;
  2932. pointerMap[1] = Keys::MiddleButton;
  2933. pointerMap[2] = Keys::RightButton;
  2934. if (numButtons >= 5)
  2935. {
  2936. pointerMap[3] = Keys::WheelUp;
  2937. pointerMap[4] = Keys::WheelDown;
  2938. }
  2939. }
  2940. }
  2941. static Point<int> lastMousePos;
  2942. static void clearLastMousePos() noexcept
  2943. {
  2944. lastMousePos = Point<int> (0x100000, 0x100000);
  2945. }
  2946. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  2947. };
  2948. ModifierKeys LinuxComponentPeer::currentModifiers;
  2949. bool LinuxComponentPeer::isActiveApplication = false;
  2950. Point<int> LinuxComponentPeer::lastMousePos;
  2951. ::Display* LinuxComponentPeer::display = nullptr;
  2952. //==============================================================================
  2953. namespace WindowingHelpers {
  2954. static void windowMessageReceive (XEvent& event)
  2955. {
  2956. if (event.xany.window != None)
  2957. {
  2958. if (LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event.xany.window))
  2959. peer->handleWindowMessage (event);
  2960. }
  2961. else if (event.xany.type == KeymapNotify)
  2962. {
  2963. const XKeymapEvent& keymapEvent = (const XKeymapEvent&) event.xkeymap;
  2964. memcpy (Keys::keyStates, keymapEvent.key_vector, 32);
  2965. }
  2966. }
  2967. }
  2968. struct WindowingCallbackInitialiser
  2969. {
  2970. WindowingCallbackInitialiser()
  2971. {
  2972. dispatchWindowMessage = WindowingHelpers::windowMessageReceive;
  2973. }
  2974. };
  2975. static WindowingCallbackInitialiser windowingInitialiser;
  2976. //==============================================================================
  2977. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess()
  2978. {
  2979. return LinuxComponentPeer::isActiveApplication;
  2980. }
  2981. // N/A on Linux as far as I know.
  2982. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2983. JUCE_API void JUCE_CALLTYPE Process::hide() {}
  2984. //==============================================================================
  2985. void ModifierKeys::updateCurrentModifiers() noexcept
  2986. {
  2987. currentModifiers = LinuxComponentPeer::currentModifiers;
  2988. }
  2989. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2990. {
  2991. ScopedXDisplay xDisplay;
  2992. ::Display* display = xDisplay.get();
  2993. if (display != nullptr)
  2994. {
  2995. Window root, child;
  2996. int x, y, winx, winy;
  2997. unsigned int mask;
  2998. int mouseMods = 0;
  2999. ScopedXLock xlock (display);
  3000. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  3001. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  3002. {
  3003. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  3004. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  3005. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  3006. }
  3007. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  3008. }
  3009. return LinuxComponentPeer::currentModifiers;
  3010. }
  3011. //==============================================================================
  3012. void Desktop::setKioskComponent (Component* comp, bool enableOrDisable, bool /* allowMenusAndBars */)
  3013. {
  3014. if (enableOrDisable)
  3015. comp->setBounds (getDisplays().getMainDisplay().totalArea);
  3016. }
  3017. void Desktop::allowedOrientationsChanged() {}
  3018. //==============================================================================
  3019. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  3020. {
  3021. return new LinuxComponentPeer (*this, styleFlags, (Window) nativeWindowToAttachTo);
  3022. }
  3023. //==============================================================================
  3024. void Desktop::Displays::findDisplays (float masterScale)
  3025. {
  3026. ScopedXDisplay xDisplay;
  3027. ::Display* display = xDisplay.get();
  3028. DisplayGeometry& geometry = DisplayGeometry::getOrCreateInstance (display, masterScale);
  3029. // add the main display first
  3030. int mainDisplayIdx;
  3031. for (mainDisplayIdx = 0; mainDisplayIdx < geometry.infos.size(); ++mainDisplayIdx)
  3032. {
  3033. const DisplayGeometry::ExtendedInfo& info = geometry.infos.getReference (mainDisplayIdx);
  3034. if (info.isMain)
  3035. break;
  3036. }
  3037. // no main display found then use the first
  3038. if (mainDisplayIdx >= geometry.infos.size())
  3039. mainDisplayIdx = 0;
  3040. // add the main display
  3041. {
  3042. const DisplayGeometry::ExtendedInfo& info =
  3043. geometry.infos.getReference (mainDisplayIdx);
  3044. Desktop::Displays::Display d;
  3045. d.isMain = true;
  3046. d.scale = masterScale * info.scale;
  3047. d.dpi = info.dpi;
  3048. d.totalArea = DisplayGeometry::physicalToScaled (info.totalBounds);
  3049. d.userArea = (info.usableBounds / d.scale) + info.topLeftScaled;
  3050. displays.add (d);
  3051. }
  3052. for (int i = 0; i < geometry.infos.size(); ++i)
  3053. {
  3054. // don't add the main display a second time
  3055. if (i == mainDisplayIdx)
  3056. continue;
  3057. const DisplayGeometry::ExtendedInfo& info = geometry.infos.getReference (i);
  3058. Desktop::Displays::Display d;
  3059. d.isMain = false;
  3060. d.scale = masterScale * info.scale;
  3061. d.dpi = info.dpi;
  3062. d.totalArea = DisplayGeometry::physicalToScaled (info.totalBounds);
  3063. d.userArea = (info.usableBounds / d.scale) + info.topLeftScaled;
  3064. displays.add (d);
  3065. }
  3066. }
  3067. //==============================================================================
  3068. bool MouseInputSource::SourceList::addSource()
  3069. {
  3070. if (sources.size() == 0)
  3071. {
  3072. addSource (0, true);
  3073. return true;
  3074. }
  3075. return false;
  3076. }
  3077. bool Desktop::canUseSemiTransparentWindows() noexcept
  3078. {
  3079. #if JUCE_USE_XRENDER
  3080. if (XRender::hasCompositingWindowManager())
  3081. {
  3082. int matchedDepth = 0, desiredDepth = 32;
  3083. return Visuals::findVisualFormat (display, desiredDepth, matchedDepth) != 0
  3084. && matchedDepth == desiredDepth;
  3085. }
  3086. #endif
  3087. return false;
  3088. }
  3089. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3090. {
  3091. ScopedXDisplay xDisplay;
  3092. ::Display* display = xDisplay.get();
  3093. if (display == nullptr)
  3094. return Point<float>();
  3095. Window root, child;
  3096. int x, y, winx, winy;
  3097. unsigned int mask;
  3098. ScopedXLock xlock (display);
  3099. if (XQueryPointer (display,
  3100. RootWindow (display, DefaultScreen (display)),
  3101. &root, &child,
  3102. &x, &y, &winx, &winy, &mask) == False)
  3103. {
  3104. // Pointer not on the default screen
  3105. x = y = -1;
  3106. }
  3107. return DisplayGeometry::physicalToScaled (Point<float> ((float) x, (float) y));
  3108. }
  3109. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3110. {
  3111. ScopedXDisplay xDisplay;
  3112. ::Display* display = xDisplay.get();
  3113. if (display != nullptr)
  3114. {
  3115. ScopedXLock xlock (display);
  3116. Window root = RootWindow (display, DefaultScreen (display));
  3117. newPosition = DisplayGeometry::scaledToPhysical (newPosition);
  3118. XWarpPointer (display, None, root, 0, 0, 0, 0, roundToInt (newPosition.getX()), roundToInt (newPosition.getY()));
  3119. }
  3120. }
  3121. double Desktop::getDefaultMasterScale()
  3122. {
  3123. return 1.0;
  3124. }
  3125. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  3126. {
  3127. return upright;
  3128. }
  3129. //==============================================================================
  3130. static bool screenSaverAllowed = true;
  3131. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3132. {
  3133. if (screenSaverAllowed != isEnabled)
  3134. {
  3135. screenSaverAllowed = isEnabled;
  3136. ScopedXDisplay xDisplay;
  3137. ::Display* display = xDisplay.get();
  3138. if (display != nullptr)
  3139. {
  3140. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  3141. static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
  3142. if (xScreenSaverSuspend == nullptr)
  3143. if (void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW))
  3144. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  3145. ScopedXLock xlock (display);
  3146. if (xScreenSaverSuspend != nullptr)
  3147. xScreenSaverSuspend (display, ! isEnabled);
  3148. }
  3149. }
  3150. }
  3151. bool Desktop::isScreenSaverEnabled()
  3152. {
  3153. return screenSaverAllowed;
  3154. }
  3155. //==============================================================================
  3156. Image juce_createIconForFile (const File& /* file */)
  3157. {
  3158. return Image();
  3159. }
  3160. //==============================================================================
  3161. void LookAndFeel::playAlertSound()
  3162. {
  3163. std::cout << "\a" << std::flush;
  3164. }
  3165. //==============================================================================
  3166. Rectangle<int> juce_LinuxScaledToPhysicalBounds (ComponentPeer* peer, const Rectangle<int>& bounds)
  3167. {
  3168. Rectangle<int> retval = bounds;
  3169. if (LinuxComponentPeer* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3170. retval *= linuxPeer->getCurrentScale();
  3171. return retval;
  3172. }
  3173. void juce_LinuxAddRepaintListener (ComponentPeer* peer, Component* dummy)
  3174. {
  3175. if (LinuxComponentPeer* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3176. linuxPeer->addOpenGLRepaintListener (dummy);
  3177. }
  3178. void juce_LinuxRemoveRepaintListener (ComponentPeer* peer, Component* dummy)
  3179. {
  3180. if (LinuxComponentPeer* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3181. linuxPeer->removeOpenGLRepaintListener (dummy);
  3182. }
  3183. //==============================================================================
  3184. #if JUCE_MODAL_LOOPS_PERMITTED
  3185. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3186. const String& title, const String& message,
  3187. Component* /* associatedComponent */)
  3188. {
  3189. AlertWindow::showMessageBox (iconType, title, message);
  3190. }
  3191. #endif
  3192. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3193. const String& title, const String& message,
  3194. Component* associatedComponent,
  3195. ModalComponentManager::Callback* callback)
  3196. {
  3197. AlertWindow::showMessageBoxAsync (iconType, title, message, String(), associatedComponent, callback);
  3198. }
  3199. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3200. const String& title, const String& message,
  3201. Component* associatedComponent,
  3202. ModalComponentManager::Callback* callback)
  3203. {
  3204. return AlertWindow::showOkCancelBox (iconType, title, message, String(), String(),
  3205. associatedComponent, callback);
  3206. }
  3207. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3208. const String& title, const String& message,
  3209. Component* associatedComponent,
  3210. ModalComponentManager::Callback* callback)
  3211. {
  3212. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  3213. String(), String(), String(),
  3214. associatedComponent, callback);
  3215. }
  3216. //============================== X11 - MouseCursor =============================
  3217. void* CustomMouseCursorInfo::create() const
  3218. {
  3219. ScopedXDisplay xDisplay;
  3220. ::Display* display = xDisplay.get();
  3221. if (display == nullptr)
  3222. return nullptr;
  3223. ScopedXLock xlock (display);
  3224. const unsigned int imageW = (unsigned int) image.getWidth();
  3225. const unsigned int imageH = (unsigned int) image.getHeight();
  3226. int hotspotX = hotspot.x;
  3227. int hotspotY = hotspot.y;
  3228. #if JUCE_USE_XCURSOR
  3229. {
  3230. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  3231. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  3232. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  3233. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  3234. static tXcursorSupportsARGB xcursorSupportsARGB = nullptr;
  3235. static tXcursorImageCreate xcursorImageCreate = nullptr;
  3236. static tXcursorImageDestroy xcursorImageDestroy = nullptr;
  3237. static tXcursorImageLoadCursor xcursorImageLoadCursor = nullptr;
  3238. static bool hasBeenLoaded = false;
  3239. if (! hasBeenLoaded)
  3240. {
  3241. hasBeenLoaded = true;
  3242. if (void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW))
  3243. {
  3244. xcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  3245. xcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  3246. xcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  3247. xcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  3248. if (xcursorSupportsARGB == nullptr || xcursorImageCreate == nullptr
  3249. || xcursorImageLoadCursor == nullptr || xcursorImageDestroy == nullptr
  3250. || ! xcursorSupportsARGB (display))
  3251. xcursorSupportsARGB = nullptr;
  3252. }
  3253. }
  3254. if (xcursorSupportsARGB != nullptr)
  3255. {
  3256. if (XcursorImage* xcImage = xcursorImageCreate ((int) imageW, (int) imageH))
  3257. {
  3258. xcImage->xhot = (XcursorDim) hotspotX;
  3259. xcImage->yhot = (XcursorDim) hotspotY;
  3260. XcursorPixel* dest = xcImage->pixels;
  3261. for (int y = 0; y < (int) imageH; ++y)
  3262. for (int x = 0; x < (int) imageW; ++x)
  3263. *dest++ = image.getPixelAt (x, y).getARGB();
  3264. void* result = (void*) xcursorImageLoadCursor (display, xcImage);
  3265. xcursorImageDestroy (xcImage);
  3266. if (result != nullptr)
  3267. return result;
  3268. }
  3269. }
  3270. }
  3271. #endif
  3272. Window root = RootWindow (display, DefaultScreen (display));
  3273. unsigned int cursorW, cursorH;
  3274. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  3275. return nullptr;
  3276. Image im (Image::ARGB, (int) cursorW, (int) cursorH, true);
  3277. {
  3278. Graphics g (im);
  3279. if (imageW > cursorW || imageH > cursorH)
  3280. {
  3281. hotspotX = (hotspotX * (int) cursorW) / (int) imageW;
  3282. hotspotY = (hotspotY * (int) cursorH) / (int) imageH;
  3283. g.drawImage (image, Rectangle<float> ((float) imageW, (float) imageH),
  3284. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize);
  3285. }
  3286. else
  3287. {
  3288. g.drawImageAt (image, 0, 0);
  3289. }
  3290. }
  3291. const unsigned int stride = (cursorW + 7) >> 3;
  3292. HeapBlock<char> maskPlane, sourcePlane;
  3293. maskPlane.calloc (stride * cursorH);
  3294. sourcePlane.calloc (stride * cursorH);
  3295. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  3296. for (int y = (int) cursorH; --y >= 0;)
  3297. {
  3298. for (int x = (int) cursorW; --x >= 0;)
  3299. {
  3300. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  3301. const unsigned int offset = (unsigned int) y * stride + ((unsigned int) x >> 3);
  3302. const Colour c (im.getPixelAt (x, y));
  3303. if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
  3304. if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
  3305. }
  3306. }
  3307. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3308. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3309. XColor white, black;
  3310. black.red = black.green = black.blue = 0;
  3311. white.red = white.green = white.blue = 0xffff;
  3312. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black,
  3313. (unsigned int) hotspotX, (unsigned int) hotspotY);
  3314. XFreePixmap (display, sourcePixmap);
  3315. XFreePixmap (display, maskPixmap);
  3316. return result;
  3317. }
  3318. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  3319. {
  3320. ScopedXDisplay xDisplay;
  3321. ::Display* display = xDisplay.get();
  3322. if (cursorHandle != nullptr && display != nullptr)
  3323. {
  3324. ScopedXLock xlock (display);
  3325. XFreeCursor (display, (Cursor) cursorHandle);
  3326. }
  3327. }
  3328. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  3329. {
  3330. ScopedXDisplay xDisplay;
  3331. ::Display* display = xDisplay.get();
  3332. if (display == nullptr)
  3333. return None;
  3334. unsigned int shape;
  3335. switch (type)
  3336. {
  3337. case NormalCursor:
  3338. case ParentCursor: return None; // Use parent cursor
  3339. case NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), 0, 0).create();
  3340. case WaitCursor: shape = XC_watch; break;
  3341. case IBeamCursor: shape = XC_xterm; break;
  3342. case PointingHandCursor: shape = XC_hand2; break;
  3343. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  3344. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  3345. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  3346. case TopEdgeResizeCursor: shape = XC_top_side; break;
  3347. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  3348. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  3349. case RightEdgeResizeCursor: shape = XC_right_side; break;
  3350. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  3351. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  3352. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  3353. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  3354. case CrosshairCursor: shape = XC_crosshair; break;
  3355. case DraggingHandCursor: return createDraggingHandCursor();
  3356. case CopyingCursor:
  3357. {
  3358. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3359. 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,
  3360. 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,
  3361. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3362. const int copyCursorSize = 119;
  3363. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
  3364. }
  3365. default:
  3366. jassertfalse;
  3367. return None;
  3368. }
  3369. ScopedXLock xlock (display);
  3370. return (void*) XCreateFontCursor (display, shape);
  3371. }
  3372. void MouseCursor::showInWindow (ComponentPeer* peer) const
  3373. {
  3374. if (LinuxComponentPeer* const lp = dynamic_cast<LinuxComponentPeer*> (peer))
  3375. lp->showMouseCursor ((Cursor) getHandle());
  3376. }
  3377. void MouseCursor::showInAllWindows() const
  3378. {
  3379. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  3380. showInWindow (ComponentPeer::getPeer (i));
  3381. }
  3382. //=================================== X11 - DND ================================
  3383. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  3384. {
  3385. if (files.size() == 0)
  3386. return false;
  3387. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0))
  3388. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  3389. if (LinuxComponentPeer* const lp = dynamic_cast<LinuxComponentPeer*> (sourceComp->getPeer()))
  3390. return lp->externalDragFileInit (files, canMoveFiles);
  3391. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3392. jassertfalse;
  3393. return false;
  3394. }
  3395. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  3396. {
  3397. if (text.isEmpty())
  3398. return false;
  3399. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0))
  3400. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  3401. if (LinuxComponentPeer* const lp = dynamic_cast<LinuxComponentPeer*> (sourceComp->getPeer()))
  3402. return lp->externalDragTextInit (text);
  3403. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3404. jassertfalse;
  3405. return false;
  3406. }