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.

4083 lines
145KB

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