Audio plugin host https://kx.studio/carla
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.

4260 lines
153KB

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