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.

4134 lines
147KB

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