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.

4292 lines
153KB

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