The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4342 lines
154KB

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