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.

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