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.

4220 lines
151KB

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