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.

4117 lines
146KB

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