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.

4342 lines
155KB

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