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.

4346 lines
155KB

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