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.

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