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.

4361 lines
155KB

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