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.

4032 lines
144KB

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