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.

4186 lines
150KB

  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 class ContainerDeletePolicy<XRRScreenResources>;
  806. friend class ContainerDeletePolicy<XRROutputInfo>;
  807. friend class 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 class ContainerDeletePolicy<XRRScreenResources>;
  875. friend class ContainerDeletePolicy<XRROutputInfo>;
  876. friend class 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. handleMouseWheel (0, getMousePos (buttonPressEvent), getEventTime (buttonPressEvent), wheel);
  1816. }
  1817. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent, int buttonModifierFlag)
  1818. {
  1819. currentModifiers = currentModifiers.withFlags (buttonModifierFlag);
  1820. toFront (true);
  1821. handleMouseEvent (0, getMousePos (buttonPressEvent), currentModifiers, getEventTime (buttonPressEvent));
  1822. }
  1823. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent)
  1824. {
  1825. updateKeyModifiers ((int) buttonPressEvent.state);
  1826. switch (pointerMap [buttonPressEvent.button - Button1])
  1827. {
  1828. case Keys::WheelUp: handleWheelEvent (buttonPressEvent, 50.0f / 256.0f); break;
  1829. case Keys::WheelDown: handleWheelEvent (buttonPressEvent, -50.0f / 256.0f); break;
  1830. case Keys::LeftButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::leftButtonModifier); break;
  1831. case Keys::RightButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::rightButtonModifier); break;
  1832. case Keys::MiddleButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::middleButtonModifier); break;
  1833. default: break;
  1834. }
  1835. clearLastMousePos();
  1836. }
  1837. void handleButtonReleaseEvent (const XButtonReleasedEvent& buttonRelEvent)
  1838. {
  1839. updateKeyModifiers ((int) buttonRelEvent.state);
  1840. if (parentWindow != 0)
  1841. updateWindowBounds();
  1842. switch (pointerMap [buttonRelEvent.button - Button1])
  1843. {
  1844. case Keys::LeftButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
  1845. case Keys::RightButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
  1846. case Keys::MiddleButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
  1847. default: break;
  1848. }
  1849. if (dragState.dragging)
  1850. handleExternalDragButtonReleaseEvent();
  1851. handleMouseEvent (0, getMousePos (buttonRelEvent), currentModifiers, getEventTime (buttonRelEvent));
  1852. clearLastMousePos();
  1853. }
  1854. void handleMotionNotifyEvent (const XPointerMovedEvent& movedEvent)
  1855. {
  1856. updateKeyModifiers ((int) movedEvent.state);
  1857. lastMousePos = Point<int> (movedEvent.x_root, movedEvent.y_root);
  1858. if (dragState.dragging)
  1859. handleExternalDragMotionNotify();
  1860. handleMouseEvent (0, getMousePos (movedEvent), currentModifiers, getEventTime (movedEvent));
  1861. }
  1862. void handleEnterNotifyEvent (const XEnterWindowEvent& enterEvent)
  1863. {
  1864. if (parentWindow != 0)
  1865. updateWindowBounds();
  1866. clearLastMousePos();
  1867. if (! currentModifiers.isAnyMouseButtonDown())
  1868. {
  1869. updateKeyModifiers ((int) enterEvent.state);
  1870. handleMouseEvent (0, getMousePos (enterEvent), currentModifiers, getEventTime (enterEvent));
  1871. }
  1872. }
  1873. void handleLeaveNotifyEvent (const XLeaveWindowEvent& leaveEvent)
  1874. {
  1875. // Suppress the normal leave if we've got a pointer grab, or if
  1876. // it's a bogus one caused by clicking a mouse button when running
  1877. // in a Window manager
  1878. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent.mode == NotifyNormal)
  1879. || leaveEvent.mode == NotifyUngrab)
  1880. {
  1881. updateKeyModifiers ((int) leaveEvent.state);
  1882. handleMouseEvent (0, getMousePos (leaveEvent), currentModifiers, getEventTime (leaveEvent));
  1883. }
  1884. }
  1885. void handleFocusInEvent()
  1886. {
  1887. isActiveApplication = true;
  1888. if (isFocused())
  1889. handleFocusGain();
  1890. }
  1891. void handleFocusOutEvent()
  1892. {
  1893. isActiveApplication = false;
  1894. if (! isFocused())
  1895. handleFocusLoss();
  1896. }
  1897. void handleExposeEvent (XExposeEvent& exposeEvent)
  1898. {
  1899. // Batch together all pending expose events
  1900. XEvent nextEvent;
  1901. ScopedXLock xlock;
  1902. if (exposeEvent.window != windowH)
  1903. {
  1904. Window child;
  1905. XTranslateCoordinates (display, exposeEvent.window, windowH,
  1906. exposeEvent.x, exposeEvent.y, &exposeEvent.x, &exposeEvent.y,
  1907. &child);
  1908. }
  1909. // exposeEvent is in local window local coordinates so do not convert with
  1910. // physicalToScaled, but rather use currentScaleFactor
  1911. repaint (Rectangle<int> (exposeEvent.x, exposeEvent.y,
  1912. exposeEvent.width, exposeEvent.height) / currentScaleFactor);
  1913. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  1914. {
  1915. XPeekEvent (display, &nextEvent);
  1916. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent.window)
  1917. break;
  1918. XNextEvent (display, &nextEvent);
  1919. const XExposeEvent& nextExposeEvent = (const XExposeEvent&) nextEvent.xexpose;
  1920. repaint (Rectangle<int> (nextExposeEvent.x, nextExposeEvent.y,
  1921. nextExposeEvent.width, nextExposeEvent.height) / currentScaleFactor);
  1922. }
  1923. }
  1924. void handleConfigureNotifyEvent (XConfigureEvent& confEvent)
  1925. {
  1926. updateWindowBounds();
  1927. updateBorderSize();
  1928. handleMovedOrResized();
  1929. // if the native title bar is dragged, need to tell any active menus, etc.
  1930. if ((styleFlags & windowHasTitleBar) != 0
  1931. && component.isCurrentlyBlockedByAnotherModalComponent())
  1932. {
  1933. if (Component* const currentModalComp = Component::getCurrentlyModalComponent())
  1934. currentModalComp->inputAttemptWhenModal();
  1935. }
  1936. if (confEvent.window == windowH
  1937. && confEvent.above != 0
  1938. && isFrontWindow())
  1939. {
  1940. handleBroughtToFront();
  1941. }
  1942. }
  1943. void handleReparentNotifyEvent()
  1944. {
  1945. parentWindow = 0;
  1946. Window wRoot = 0;
  1947. Window* wChild = nullptr;
  1948. unsigned int numChildren;
  1949. {
  1950. ScopedXLock xlock;
  1951. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  1952. }
  1953. if (parentWindow == windowH || parentWindow == wRoot)
  1954. parentWindow = 0;
  1955. handleGravityNotify();
  1956. }
  1957. void handleGravityNotify()
  1958. {
  1959. updateWindowBounds();
  1960. updateBorderSize();
  1961. handleMovedOrResized();
  1962. }
  1963. void handleMappingNotify (XMappingEvent& mappingEvent)
  1964. {
  1965. if (mappingEvent.request != MappingPointer)
  1966. {
  1967. // Deal with modifier/keyboard mapping
  1968. ScopedXLock xlock;
  1969. XRefreshKeyboardMapping (&mappingEvent);
  1970. updateModifierMappings();
  1971. }
  1972. }
  1973. void handleClientMessageEvent (XClientMessageEvent& clientMsg, XEvent& event)
  1974. {
  1975. const Atoms& atoms = Atoms::get();
  1976. if (clientMsg.message_type == atoms.protocols && clientMsg.format == 32)
  1977. {
  1978. const Atom atom = (Atom) clientMsg.data.l[0];
  1979. if (atom == atoms.protocolList [Atoms::PING])
  1980. {
  1981. Window root = RootWindow (display, DefaultScreen (display));
  1982. clientMsg.window = root;
  1983. XSendEvent (display, root, False, NoEventMask, &event);
  1984. XFlush (display);
  1985. }
  1986. else if (atom == atoms.protocolList [Atoms::TAKE_FOCUS])
  1987. {
  1988. if ((getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0)
  1989. {
  1990. XWindowAttributes atts;
  1991. ScopedXLock xlock;
  1992. if (clientMsg.window != 0
  1993. && XGetWindowAttributes (display, clientMsg.window, &atts))
  1994. {
  1995. if (atts.map_state == IsViewable)
  1996. XSetInputFocus (display, clientMsg.window, RevertToParent, (::Time) clientMsg.data.l[1]);
  1997. }
  1998. }
  1999. }
  2000. else if (atom == atoms.protocolList [Atoms::DELETE_WINDOW])
  2001. {
  2002. handleUserClosingWindow();
  2003. }
  2004. }
  2005. else if (clientMsg.message_type == atoms.XdndEnter)
  2006. {
  2007. handleDragAndDropEnter (clientMsg);
  2008. }
  2009. else if (clientMsg.message_type == atoms.XdndLeave)
  2010. {
  2011. handleDragExit (dragInfo);
  2012. resetDragAndDrop();
  2013. }
  2014. else if (clientMsg.message_type == atoms.XdndPosition)
  2015. {
  2016. handleDragAndDropPosition (clientMsg);
  2017. }
  2018. else if (clientMsg.message_type == atoms.XdndDrop)
  2019. {
  2020. handleDragAndDropDrop (clientMsg);
  2021. }
  2022. else if (clientMsg.message_type == atoms.XdndStatus)
  2023. {
  2024. handleExternalDragAndDropStatus (clientMsg);
  2025. }
  2026. else if (clientMsg.message_type == atoms.XdndFinished)
  2027. {
  2028. externalResetDragAndDrop();
  2029. }
  2030. }
  2031. bool externalDragTextInit (const String& text)
  2032. {
  2033. if (dragState.dragging)
  2034. return false;
  2035. return externalDragInit (true, text);
  2036. }
  2037. bool externalDragFileInit (const StringArray& files, bool /*canMoveFiles*/)
  2038. {
  2039. if (dragState.dragging)
  2040. return false;
  2041. StringArray uriList;
  2042. for (int i = 0; i < files.size(); ++i)
  2043. {
  2044. const String& f = files[i];
  2045. if (f.matchesWildcard ("?*://*", false))
  2046. uriList.add (f);
  2047. else
  2048. uriList.add ("file://" + f);
  2049. }
  2050. return externalDragInit (false, uriList.joinIntoString ("\r\n"));
  2051. }
  2052. //==============================================================================
  2053. void showMouseCursor (Cursor cursor) noexcept
  2054. {
  2055. ScopedXLock xlock;
  2056. XDefineCursor (display, windowH, cursor);
  2057. }
  2058. //==============================================================================
  2059. double getCurrentScale() noexcept
  2060. {
  2061. return currentScaleFactor;
  2062. }
  2063. //==============================================================================
  2064. bool dontRepaint;
  2065. static ModifierKeys currentModifiers;
  2066. static bool isActiveApplication;
  2067. private:
  2068. //==============================================================================
  2069. class LinuxRepaintManager : public Timer
  2070. {
  2071. public:
  2072. LinuxRepaintManager (LinuxComponentPeer& p)
  2073. : peer (p), lastTimeImageUsed (0)
  2074. {
  2075. #if JUCE_USE_XSHM
  2076. shmPaintsPending = 0;
  2077. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  2078. if (useARGBImagesForRendering)
  2079. {
  2080. ScopedXLock xlock;
  2081. XShmSegmentInfo segmentinfo;
  2082. XImage* const testImage
  2083. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  2084. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  2085. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  2086. XDestroyImage (testImage);
  2087. }
  2088. #endif
  2089. }
  2090. void timerCallback() override
  2091. {
  2092. #if JUCE_USE_XSHM
  2093. if (shmPaintsPending != 0)
  2094. return;
  2095. #endif
  2096. if (! regionsNeedingRepaint.isEmpty())
  2097. {
  2098. stopTimer();
  2099. performAnyPendingRepaintsNow();
  2100. }
  2101. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  2102. {
  2103. stopTimer();
  2104. image = Image::null;
  2105. }
  2106. }
  2107. void repaint (const Rectangle<int>& area)
  2108. {
  2109. if (! isTimerRunning())
  2110. startTimer (repaintTimerPeriod);
  2111. regionsNeedingRepaint.add (area * peer.currentScaleFactor);
  2112. }
  2113. void performAnyPendingRepaintsNow()
  2114. {
  2115. #if JUCE_USE_XSHM
  2116. if (shmPaintsPending != 0)
  2117. {
  2118. startTimer (repaintTimerPeriod);
  2119. return;
  2120. }
  2121. #endif
  2122. RectangleList<int> originalRepaintRegion (regionsNeedingRepaint);
  2123. regionsNeedingRepaint.clear();
  2124. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  2125. if (! totalArea.isEmpty())
  2126. {
  2127. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  2128. || image.getHeight() < totalArea.getHeight())
  2129. {
  2130. #if JUCE_USE_XSHM
  2131. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  2132. : Image::RGB,
  2133. #else
  2134. image = Image (new XBitmapImage (Image::RGB,
  2135. #endif
  2136. (totalArea.getWidth() + 31) & ~31,
  2137. (totalArea.getHeight() + 31) & ~31,
  2138. false, (unsigned int) peer.depth, peer.visual));
  2139. }
  2140. startTimer (repaintTimerPeriod);
  2141. RectangleList<int> adjustedList (originalRepaintRegion);
  2142. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  2143. if (peer.depth == 32)
  2144. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  2145. image.clear (*i - totalArea.getPosition());
  2146. {
  2147. ScopedPointer<LowLevelGraphicsContext> context (peer.getComponent().getLookAndFeel()
  2148. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList));
  2149. context->addTransform (AffineTransform::scale ((float) peer.currentScaleFactor));
  2150. peer.handlePaint (*context);
  2151. }
  2152. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  2153. {
  2154. XBitmapImage* xbitmap = static_cast<XBitmapImage*> (image.getPixelData());
  2155. #if JUCE_USE_XSHM
  2156. if (xbitmap->isUsingXShm())
  2157. ++shmPaintsPending;
  2158. #endif
  2159. xbitmap->blitToWindow (peer.windowH,
  2160. i->getX(), i->getY(),
  2161. (unsigned int) i->getWidth(),
  2162. (unsigned int) i->getHeight(),
  2163. i->getX() - totalArea.getX(), i->getY() - totalArea.getY());
  2164. }
  2165. }
  2166. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  2167. startTimer (repaintTimerPeriod);
  2168. }
  2169. #if JUCE_USE_XSHM
  2170. void notifyPaintCompleted() noexcept { --shmPaintsPending; }
  2171. #endif
  2172. private:
  2173. enum { repaintTimerPeriod = 1000 / 100 };
  2174. LinuxComponentPeer& peer;
  2175. Image image;
  2176. uint32 lastTimeImageUsed;
  2177. RectangleList<int> regionsNeedingRepaint;
  2178. #if JUCE_USE_XSHM
  2179. bool useARGBImagesForRendering;
  2180. int shmPaintsPending;
  2181. #endif
  2182. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  2183. };
  2184. ScopedPointer<LinuxRepaintManager> repainter;
  2185. friend class LinuxRepaintManager;
  2186. Window windowH, parentWindow;
  2187. Rectangle<int> bounds;
  2188. Image taskbarImage;
  2189. bool fullScreen, mapped;
  2190. Visual* visual;
  2191. int depth;
  2192. BorderSize<int> windowBorder;
  2193. bool isAlwaysOnTop;
  2194. double currentScaleFactor;
  2195. enum { KeyPressEventType = 2 };
  2196. struct MotifWmHints
  2197. {
  2198. unsigned long flags;
  2199. unsigned long functions;
  2200. unsigned long decorations;
  2201. long input_mode;
  2202. unsigned long status;
  2203. };
  2204. static void updateKeyStates (const int keycode, const bool press) noexcept
  2205. {
  2206. const int keybyte = keycode >> 3;
  2207. const int keybit = (1 << (keycode & 7));
  2208. if (press)
  2209. Keys::keyStates [keybyte] |= keybit;
  2210. else
  2211. Keys::keyStates [keybyte] &= ~keybit;
  2212. }
  2213. static void updateKeyModifiers (const int status) noexcept
  2214. {
  2215. int keyMods = 0;
  2216. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  2217. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  2218. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  2219. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  2220. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  2221. Keys::capsLock = ((status & LockMask) != 0);
  2222. }
  2223. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) noexcept
  2224. {
  2225. int modifier = 0;
  2226. bool isModifier = true;
  2227. switch (sym)
  2228. {
  2229. case XK_Shift_L:
  2230. case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
  2231. case XK_Control_L:
  2232. case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
  2233. case XK_Alt_L:
  2234. case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
  2235. case XK_Num_Lock:
  2236. if (press)
  2237. Keys::numLock = ! Keys::numLock;
  2238. break;
  2239. case XK_Caps_Lock:
  2240. if (press)
  2241. Keys::capsLock = ! Keys::capsLock;
  2242. break;
  2243. case XK_Scroll_Lock:
  2244. break;
  2245. default:
  2246. isModifier = false;
  2247. break;
  2248. }
  2249. currentModifiers = press ? currentModifiers.withFlags (modifier)
  2250. : currentModifiers.withoutFlags (modifier);
  2251. return isModifier;
  2252. }
  2253. // Alt and Num lock are not defined by standard X
  2254. // modifier constants: check what they're mapped to
  2255. static void updateModifierMappings() noexcept
  2256. {
  2257. ScopedXLock xlock;
  2258. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  2259. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  2260. Keys::AltMask = 0;
  2261. Keys::NumLockMask = 0;
  2262. if (XModifierKeymap* const mapping = XGetModifierMapping (display))
  2263. {
  2264. for (int i = 0; i < 8; i++)
  2265. {
  2266. if (mapping->modifiermap [i << 1] == altLeftCode)
  2267. Keys::AltMask = 1 << i;
  2268. else if (mapping->modifiermap [i << 1] == numLockCode)
  2269. Keys::NumLockMask = 1 << i;
  2270. }
  2271. XFreeModifiermap (mapping);
  2272. }
  2273. }
  2274. //==============================================================================
  2275. static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
  2276. {
  2277. XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  2278. }
  2279. void removeWindowDecorations (Window wndH)
  2280. {
  2281. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  2282. if (hints != None)
  2283. {
  2284. MotifWmHints motifHints;
  2285. zerostruct (motifHints);
  2286. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  2287. motifHints.decorations = 0;
  2288. ScopedXLock xlock;
  2289. xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
  2290. }
  2291. hints = Atoms::getIfExists ("_WIN_HINTS");
  2292. if (hints != None)
  2293. {
  2294. long gnomeHints = 0;
  2295. ScopedXLock xlock;
  2296. xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
  2297. }
  2298. hints = Atoms::getIfExists ("KWM_WIN_DECORATION");
  2299. if (hints != None)
  2300. {
  2301. long kwmHints = 2; /*KDE_tinyDecoration*/
  2302. ScopedXLock xlock;
  2303. xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
  2304. }
  2305. }
  2306. void addWindowButtons (Window wndH)
  2307. {
  2308. ScopedXLock xlock;
  2309. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  2310. if (hints != None)
  2311. {
  2312. MotifWmHints motifHints;
  2313. zerostruct (motifHints);
  2314. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  2315. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  2316. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  2317. if ((styleFlags & windowHasCloseButton) != 0)
  2318. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  2319. if ((styleFlags & windowHasMinimiseButton) != 0)
  2320. {
  2321. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  2322. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  2323. }
  2324. if ((styleFlags & windowHasMaximiseButton) != 0)
  2325. {
  2326. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  2327. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  2328. }
  2329. if ((styleFlags & windowIsResizable) != 0)
  2330. {
  2331. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  2332. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  2333. }
  2334. xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
  2335. }
  2336. hints = Atoms::getIfExists ("_NET_WM_ALLOWED_ACTIONS");
  2337. if (hints != None)
  2338. {
  2339. Atom netHints [6];
  2340. int num = 0;
  2341. if ((styleFlags & windowIsResizable) != 0)
  2342. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_RESIZE");
  2343. if ((styleFlags & windowHasMaximiseButton) != 0)
  2344. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_FULLSCREEN");
  2345. if ((styleFlags & windowHasMinimiseButton) != 0)
  2346. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_MINIMIZE");
  2347. if ((styleFlags & windowHasCloseButton) != 0)
  2348. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_CLOSE");
  2349. xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
  2350. }
  2351. }
  2352. void setWindowType()
  2353. {
  2354. Atom netHints [2];
  2355. if (styleFlags & windowIsTemporary)
  2356. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_TOOLTIP");
  2357. else if ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows())
  2358. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_COMBO");
  2359. else
  2360. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_NORMAL");
  2361. netHints[1] = Atoms::getIfExists ("_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  2362. xchangeProperty (windowH, Atoms::get().windowType, XA_ATOM, 32, &netHints, 2);
  2363. int numHints = 0;
  2364. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  2365. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_SKIP_TASKBAR");
  2366. if (component.isAlwaysOnTop())
  2367. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_ABOVE");
  2368. if (numHints > 0)
  2369. xchangeProperty (windowH, Atoms::get().windowState, XA_ATOM, 32, &netHints, numHints);
  2370. }
  2371. void createWindow (Window parentToAddTo)
  2372. {
  2373. ScopedXLock xlock;
  2374. resetDragAndDrop();
  2375. // Get defaults for various properties
  2376. const int screen = DefaultScreen (display);
  2377. Window root = RootWindow (display, screen);
  2378. parentWindow = parentToAddTo;
  2379. // Try to obtain a 32-bit visual or fallback to 24 or 16
  2380. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  2381. if (visual == nullptr)
  2382. {
  2383. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  2384. Process::terminate();
  2385. }
  2386. // Create and install a colormap suitable fr our visual
  2387. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  2388. XInstallColormap (display, colormap);
  2389. // Set up the window attributes
  2390. XSetWindowAttributes swa;
  2391. swa.border_pixel = 0;
  2392. swa.background_pixmap = None;
  2393. swa.colormap = colormap;
  2394. swa.override_redirect = (styleFlags & windowIsTemporary) ? True : False;
  2395. swa.event_mask = getAllEventsMask();
  2396. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  2397. 0, 0, 1, 1,
  2398. 0, depth, InputOutput, visual,
  2399. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  2400. &swa);
  2401. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  2402. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  2403. GrabModeAsync, GrabModeAsync, None, None);
  2404. // Set the window context to identify the window handle object
  2405. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  2406. {
  2407. // Failed
  2408. jassertfalse;
  2409. Logger::outputDebugString ("Failed to create context information for window.\n");
  2410. XDestroyWindow (display, windowH);
  2411. windowH = 0;
  2412. return;
  2413. }
  2414. // Set window manager hints
  2415. XWMHints* wmHints = XAllocWMHints();
  2416. wmHints->flags = InputHint | StateHint;
  2417. wmHints->input = True; // Locally active input model
  2418. wmHints->initial_state = NormalState;
  2419. XSetWMHints (display, windowH, wmHints);
  2420. XFree (wmHints);
  2421. // Set the window type
  2422. setWindowType();
  2423. // Define decoration
  2424. if ((styleFlags & windowHasTitleBar) == 0)
  2425. removeWindowDecorations (windowH);
  2426. else
  2427. addWindowButtons (windowH);
  2428. setTitle (component.getName());
  2429. const Atoms& atoms = Atoms::get();
  2430. // Associate the PID, allowing to be shut down when something goes wrong
  2431. unsigned long pid = (unsigned long) getpid();
  2432. xchangeProperty (windowH, atoms.pid, XA_CARDINAL, 32, &pid, 1);
  2433. // Set window manager protocols
  2434. xchangeProperty (windowH, atoms.protocols, XA_ATOM, 32, atoms.protocolList, 2);
  2435. // Set drag and drop flags
  2436. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32, atoms.allowedMimeTypes, numElementsInArray (atoms.allowedMimeTypes));
  2437. xchangeProperty (windowH, atoms.XdndActionList, XA_ATOM, 32, atoms.allowedActions, numElementsInArray (atoms.allowedActions));
  2438. xchangeProperty (windowH, atoms.XdndActionDescription, XA_STRING, 8, "", 0);
  2439. xchangeProperty (windowH, atoms.XdndAware, XA_ATOM, 32, &Atoms::DndVersion, 1);
  2440. initialisePointerMap();
  2441. updateModifierMappings();
  2442. }
  2443. void destroyWindow()
  2444. {
  2445. ScopedXLock xlock;
  2446. XPointer handlePointer;
  2447. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  2448. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  2449. XDestroyWindow (display, windowH);
  2450. // Wait for it to complete and then remove any events for this
  2451. // window from the event queue.
  2452. XSync (display, false);
  2453. XEvent event;
  2454. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  2455. {}
  2456. }
  2457. static int getAllEventsMask() noexcept
  2458. {
  2459. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  2460. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  2461. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  2462. }
  2463. template <typename EventType>
  2464. static int64 getEventTime (const EventType& t)
  2465. {
  2466. return getEventTime (t.time);
  2467. }
  2468. static int64 getEventTime (::Time t)
  2469. {
  2470. static int64 eventTimeOffset = 0x12345678;
  2471. const int64 thisMessageTime = (int64) t;
  2472. if (eventTimeOffset == 0x12345678)
  2473. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  2474. return eventTimeOffset + thisMessageTime;
  2475. }
  2476. long getUserTime() const
  2477. {
  2478. GetXProperty prop (windowH, Atoms::get().userTime, 0, 65536, false, XA_CARDINAL);
  2479. return prop.success ? *(long*) prop.data : 0;
  2480. }
  2481. void updateBorderSize()
  2482. {
  2483. if ((styleFlags & windowHasTitleBar) == 0)
  2484. {
  2485. windowBorder = BorderSize<int> (0);
  2486. }
  2487. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  2488. {
  2489. ScopedXLock xlock;
  2490. Atom hints = Atoms::getIfExists ("_NET_FRAME_EXTENTS");
  2491. if (hints != None)
  2492. {
  2493. GetXProperty prop (windowH, hints, 0, 4, false, XA_CARDINAL);
  2494. if (prop.success && prop.actualFormat == 32)
  2495. {
  2496. const unsigned long* const sizes = (const unsigned long*) prop.data;
  2497. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  2498. (int) sizes[3], (int) sizes[1]);
  2499. }
  2500. }
  2501. }
  2502. }
  2503. void updateWindowBounds()
  2504. {
  2505. jassert (windowH != 0);
  2506. if (windowH != 0)
  2507. {
  2508. Window root, child;
  2509. int wx = 0, wy = 0;
  2510. unsigned int ww = 0, wh = 0, bw, bitDepth;
  2511. ScopedXLock xlock;
  2512. if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth))
  2513. if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  2514. wx = wy = 0;
  2515. Rectangle<int> physicalBounds (wx, wy, (int) ww, (int) wh);
  2516. currentScaleFactor =
  2517. DisplayGeometry::getInstance().findDisplayForRect (physicalBounds, false).scale;
  2518. bounds = DisplayGeometry::physicalToScaled (physicalBounds);
  2519. }
  2520. }
  2521. //==============================================================================
  2522. struct DragState
  2523. {
  2524. DragState() noexcept
  2525. : isText (false), dragging (false), expectingStatus (false),
  2526. canDrop (false), targetWindow (None), xdndVersion (-1)
  2527. {
  2528. }
  2529. bool isText;
  2530. bool dragging; // currently performing outgoing external dnd as Xdnd source, have grabbed mouse
  2531. bool expectingStatus; // XdndPosition sent, waiting for XdndStatus
  2532. bool canDrop; // target window signals it will accept the drop
  2533. Window targetWindow; // potential drop target
  2534. int xdndVersion; // negotiated version with target
  2535. Rectangle<int> silentRect;
  2536. String textOrFiles;
  2537. const Atom* getMimeTypes() const noexcept { return isText ? Atoms::get().externalAllowedTextMimeTypes
  2538. : Atoms::get().externalAllowedFileMimeTypes; }
  2539. int getNumMimeTypes() const noexcept { return isText ? numElementsInArray (Atoms::get().externalAllowedTextMimeTypes)
  2540. : numElementsInArray (Atoms::get().externalAllowedFileMimeTypes); }
  2541. bool matchesTarget (Atom targetType) const
  2542. {
  2543. for (int i = getNumMimeTypes(); --i >= 0;)
  2544. if (getMimeTypes()[i] == targetType)
  2545. return true;
  2546. return false;
  2547. }
  2548. };
  2549. //==============================================================================
  2550. void resetDragAndDrop()
  2551. {
  2552. dragInfo.clear();
  2553. dragInfo.position = Point<int> (-1, -1);
  2554. dragAndDropCurrentMimeType = 0;
  2555. dragAndDropSourceWindow = 0;
  2556. srcMimeTypeAtomList.clear();
  2557. finishAfterDropDataReceived = false;
  2558. }
  2559. void resetExternalDragState()
  2560. {
  2561. dragState = DragState();
  2562. }
  2563. void sendDragAndDropMessage (XClientMessageEvent& msg)
  2564. {
  2565. msg.type = ClientMessage;
  2566. msg.display = display;
  2567. msg.window = dragAndDropSourceWindow;
  2568. msg.format = 32;
  2569. msg.data.l[0] = (long) windowH;
  2570. ScopedXLock xlock;
  2571. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  2572. }
  2573. bool sendExternalDragAndDropMessage (XClientMessageEvent& msg, const Window targetWindow)
  2574. {
  2575. msg.type = ClientMessage;
  2576. msg.display = display;
  2577. msg.window = targetWindow;
  2578. msg.format = 32;
  2579. msg.data.l[0] = (long) windowH;
  2580. ScopedXLock xlock;
  2581. return XSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
  2582. }
  2583. void sendExternalDragAndDropDrop (const Window targetWindow)
  2584. {
  2585. XClientMessageEvent msg;
  2586. zerostruct (msg);
  2587. msg.message_type = Atoms::get().XdndDrop;
  2588. msg.data.l[2] = CurrentTime;
  2589. sendExternalDragAndDropMessage (msg, targetWindow);
  2590. }
  2591. void sendExternalDragAndDropEnter (const Window targetWindow)
  2592. {
  2593. XClientMessageEvent msg;
  2594. zerostruct (msg);
  2595. msg.message_type = Atoms::get().XdndEnter;
  2596. const Atom* mimeTypes = dragState.getMimeTypes();
  2597. const int numMimeTypes = dragState.getNumMimeTypes();
  2598. msg.data.l[1] = (dragState.xdndVersion << 24) | (numMimeTypes > 3);
  2599. msg.data.l[2] = numMimeTypes > 0 ? (long) mimeTypes[0] : 0;
  2600. msg.data.l[3] = numMimeTypes > 1 ? (long) mimeTypes[1] : 0;
  2601. msg.data.l[4] = numMimeTypes > 2 ? (long) mimeTypes[2] : 0;
  2602. sendExternalDragAndDropMessage (msg, targetWindow);
  2603. }
  2604. void sendExternalDragAndDropPosition (const Window targetWindow)
  2605. {
  2606. XClientMessageEvent msg;
  2607. zerostruct (msg);
  2608. msg.message_type = Atoms::get().XdndPosition;
  2609. Point<int> mousePos (Desktop::getInstance().getMousePosition());
  2610. if (dragState.silentRect.contains (mousePos)) // we've been asked to keep silent
  2611. return;
  2612. mousePos = DisplayGeometry::scaledToPhysical (mousePos);
  2613. msg.data.l[1] = 0;
  2614. msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
  2615. msg.data.l[3] = CurrentTime;
  2616. msg.data.l[4] = (long) Atoms::get().XdndActionCopy; // this is all JUCE currently supports
  2617. dragState.expectingStatus = sendExternalDragAndDropMessage (msg, targetWindow);
  2618. }
  2619. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  2620. {
  2621. XClientMessageEvent msg;
  2622. zerostruct (msg);
  2623. msg.message_type = Atoms::get().XdndStatus;
  2624. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  2625. msg.data.l[4] = (long) dropAction;
  2626. sendDragAndDropMessage (msg);
  2627. }
  2628. void sendExternalDragAndDropLeave (const Window targetWindow)
  2629. {
  2630. XClientMessageEvent msg;
  2631. zerostruct (msg);
  2632. msg.message_type = Atoms::get().XdndLeave;
  2633. sendExternalDragAndDropMessage (msg, targetWindow);
  2634. }
  2635. void sendDragAndDropFinish()
  2636. {
  2637. XClientMessageEvent msg;
  2638. zerostruct (msg);
  2639. msg.message_type = Atoms::get().XdndFinished;
  2640. sendDragAndDropMessage (msg);
  2641. }
  2642. void handleExternalSelectionClear()
  2643. {
  2644. if (dragState.dragging)
  2645. externalResetDragAndDrop();
  2646. }
  2647. void handleExternalSelectionRequest (const XEvent& evt)
  2648. {
  2649. Atom targetType = evt.xselectionrequest.target;
  2650. XEvent s;
  2651. s.xselection.type = SelectionNotify;
  2652. s.xselection.requestor = evt.xselectionrequest.requestor;
  2653. s.xselection.selection = evt.xselectionrequest.selection;
  2654. s.xselection.target = targetType;
  2655. s.xselection.property = None;
  2656. s.xselection.time = evt.xselectionrequest.time;
  2657. if (dragState.matchesTarget (targetType))
  2658. {
  2659. s.xselection.property = evt.xselectionrequest.property;
  2660. xchangeProperty (evt.xselectionrequest.requestor,
  2661. evt.xselectionrequest.property,
  2662. targetType, 8,
  2663. dragState.textOrFiles.toRawUTF8(),
  2664. (int) dragState.textOrFiles.getNumBytesAsUTF8());
  2665. }
  2666. XSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
  2667. }
  2668. void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
  2669. {
  2670. if (dragState.expectingStatus)
  2671. {
  2672. dragState.expectingStatus = false;
  2673. dragState.canDrop = false;
  2674. dragState.silentRect = Rectangle<int>();
  2675. if ((clientMsg.data.l[1] & 1) != 0
  2676. && ((Atom) clientMsg.data.l[4] == Atoms::get().XdndActionCopy
  2677. || (Atom) clientMsg.data.l[4] == Atoms::get().XdndActionPrivate))
  2678. {
  2679. if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
  2680. dragState.silentRect.setBounds ((int) clientMsg.data.l[2] >> 16,
  2681. (int) clientMsg.data.l[2] & 0xffff,
  2682. (int) clientMsg.data.l[3] >> 16,
  2683. (int) clientMsg.data.l[3] & 0xffff);
  2684. dragState.canDrop = true;
  2685. }
  2686. }
  2687. }
  2688. void handleExternalDragButtonReleaseEvent()
  2689. {
  2690. if (dragState.dragging)
  2691. XUngrabPointer (display, CurrentTime);
  2692. if (dragState.canDrop)
  2693. {
  2694. sendExternalDragAndDropDrop (dragState.targetWindow);
  2695. }
  2696. else
  2697. {
  2698. sendExternalDragAndDropLeave (dragState.targetWindow);
  2699. externalResetDragAndDrop();
  2700. }
  2701. }
  2702. void handleExternalDragMotionNotify()
  2703. {
  2704. Window targetWindow = externalFindDragTargetWindow (RootWindow (display, DefaultScreen (display)));
  2705. if (dragState.targetWindow != targetWindow)
  2706. {
  2707. if (dragState.targetWindow != None)
  2708. sendExternalDragAndDropLeave (dragState.targetWindow);
  2709. dragState.canDrop = false;
  2710. dragState.silentRect = Rectangle<int>();
  2711. if (targetWindow == None)
  2712. return;
  2713. GetXProperty prop (targetWindow, Atoms::get().XdndAware,
  2714. 0, 2, false, AnyPropertyType);
  2715. if (prop.success
  2716. && prop.data != None
  2717. && prop.actualFormat == 32
  2718. && prop.numItems == 1)
  2719. {
  2720. dragState.xdndVersion = jmin ((int) prop.data[0], (int) Atoms::DndVersion);
  2721. }
  2722. else
  2723. {
  2724. dragState.xdndVersion = -1;
  2725. return;
  2726. }
  2727. sendExternalDragAndDropEnter (targetWindow);
  2728. dragState.targetWindow = targetWindow;
  2729. }
  2730. if (! dragState.expectingStatus)
  2731. sendExternalDragAndDropPosition (targetWindow);
  2732. }
  2733. void handleDragAndDropPosition (const XClientMessageEvent& clientMsg)
  2734. {
  2735. if (dragAndDropSourceWindow == 0)
  2736. return;
  2737. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2738. Point<int> dropPos ((int) clientMsg.data.l[2] >> 16,
  2739. (int) clientMsg.data.l[2] & 0xffff);
  2740. dropPos -= bounds.getPosition();
  2741. const Atoms& atoms = Atoms::get();
  2742. Atom targetAction = atoms.XdndActionCopy;
  2743. for (int i = numElementsInArray (atoms.allowedActions); --i >= 0;)
  2744. {
  2745. if ((Atom) clientMsg.data.l[4] == atoms.allowedActions[i])
  2746. {
  2747. targetAction = atoms.allowedActions[i];
  2748. break;
  2749. }
  2750. }
  2751. sendDragAndDropStatus (true, targetAction);
  2752. if (dragInfo.position != dropPos)
  2753. {
  2754. dragInfo.position = dropPos;
  2755. if (dragInfo.isEmpty())
  2756. updateDraggedFileList (clientMsg);
  2757. if (! dragInfo.isEmpty())
  2758. handleDragMove (dragInfo);
  2759. }
  2760. }
  2761. void handleDragAndDropDrop (const XClientMessageEvent& clientMsg)
  2762. {
  2763. if (dragInfo.isEmpty())
  2764. {
  2765. // no data, transaction finished in handleDragAndDropSelection()
  2766. finishAfterDropDataReceived = true;
  2767. updateDraggedFileList (clientMsg);
  2768. }
  2769. else
  2770. {
  2771. handleDragAndDropDataReceived(); // data was already received
  2772. }
  2773. }
  2774. void handleDragAndDropDataReceived()
  2775. {
  2776. DragInfo dragInfoCopy (dragInfo);
  2777. sendDragAndDropFinish();
  2778. resetDragAndDrop();
  2779. if (! dragInfoCopy.isEmpty())
  2780. handleDragDrop (dragInfoCopy);
  2781. }
  2782. void handleDragAndDropEnter (const XClientMessageEvent& clientMsg)
  2783. {
  2784. dragInfo.clear();
  2785. srcMimeTypeAtomList.clear();
  2786. dragAndDropCurrentMimeType = 0;
  2787. const unsigned long dndCurrentVersion = static_cast<unsigned long> (clientMsg.data.l[1] & 0xff000000) >> 24;
  2788. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  2789. {
  2790. dragAndDropSourceWindow = 0;
  2791. return;
  2792. }
  2793. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2794. if ((clientMsg.data.l[1] & 1) != 0)
  2795. {
  2796. ScopedXLock xlock;
  2797. GetXProperty prop (dragAndDropSourceWindow, Atoms::get().XdndTypeList, 0, 0x8000000L, false, XA_ATOM);
  2798. if (prop.success
  2799. && prop.actualType == XA_ATOM
  2800. && prop.actualFormat == 32
  2801. && prop.numItems != 0)
  2802. {
  2803. const unsigned long* const types = (const unsigned long*) prop.data;
  2804. for (unsigned long i = 0; i < prop.numItems; ++i)
  2805. if (types[i] != None)
  2806. srcMimeTypeAtomList.add (types[i]);
  2807. }
  2808. }
  2809. if (srcMimeTypeAtomList.size() == 0)
  2810. {
  2811. for (int i = 2; i < 5; ++i)
  2812. if (clientMsg.data.l[i] != None)
  2813. srcMimeTypeAtomList.add ((unsigned long) clientMsg.data.l[i]);
  2814. if (srcMimeTypeAtomList.size() == 0)
  2815. {
  2816. dragAndDropSourceWindow = 0;
  2817. return;
  2818. }
  2819. }
  2820. const Atoms& atoms = Atoms::get();
  2821. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  2822. for (int j = 0; j < numElementsInArray (atoms.allowedMimeTypes); ++j)
  2823. if (srcMimeTypeAtomList[i] == atoms.allowedMimeTypes[j])
  2824. dragAndDropCurrentMimeType = atoms.allowedMimeTypes[j];
  2825. handleDragAndDropPosition (clientMsg);
  2826. }
  2827. void handleDragAndDropSelection (const XEvent& evt)
  2828. {
  2829. dragInfo.clear();
  2830. if (evt.xselection.property != None)
  2831. {
  2832. StringArray lines;
  2833. {
  2834. MemoryBlock dropData;
  2835. for (;;)
  2836. {
  2837. GetXProperty prop (evt.xany.window, evt.xselection.property,
  2838. dropData.getSize() / 4, 65536, false, AnyPropertyType);
  2839. if (! prop.success)
  2840. break;
  2841. dropData.append (prop.data, prop.numItems * (size_t) prop.actualFormat / 8);
  2842. if (prop.bytesLeft <= 0)
  2843. break;
  2844. }
  2845. lines.addLines (dropData.toString());
  2846. }
  2847. if (Atoms::isMimeTypeFile (dragAndDropCurrentMimeType))
  2848. {
  2849. for (int i = 0; i < lines.size(); ++i)
  2850. dragInfo.files.add (URL::removeEscapeChars (lines[i].replace ("file://", String::empty, true)));
  2851. dragInfo.files.trim();
  2852. dragInfo.files.removeEmptyStrings();
  2853. }
  2854. else
  2855. {
  2856. dragInfo.text = lines.joinIntoString ("\n");
  2857. }
  2858. if (finishAfterDropDataReceived)
  2859. handleDragAndDropDataReceived();
  2860. }
  2861. }
  2862. void updateDraggedFileList (const XClientMessageEvent& clientMsg)
  2863. {
  2864. jassert (dragInfo.isEmpty());
  2865. if (dragAndDropSourceWindow != None
  2866. && dragAndDropCurrentMimeType != None)
  2867. {
  2868. ScopedXLock xlock;
  2869. XConvertSelection (display,
  2870. Atoms::get().XdndSelection,
  2871. dragAndDropCurrentMimeType,
  2872. Atoms::getCreating ("JXSelectionWindowProperty"),
  2873. windowH,
  2874. (::Time) clientMsg.data.l[2]);
  2875. }
  2876. }
  2877. static bool isWindowDnDAware (Window w)
  2878. {
  2879. int numProperties = 0;
  2880. Atom* const atoms = XListProperties (display, w, &numProperties);
  2881. bool dndAwarePropFound = false;
  2882. for (int i = 0; i < numProperties; ++i)
  2883. if (atoms[i] == Atoms::get().XdndAware)
  2884. dndAwarePropFound = true;
  2885. if (atoms != nullptr)
  2886. XFree (atoms);
  2887. return dndAwarePropFound;
  2888. }
  2889. Window externalFindDragTargetWindow (Window targetWindow)
  2890. {
  2891. if (targetWindow == None)
  2892. return None;
  2893. if (isWindowDnDAware (targetWindow))
  2894. return targetWindow;
  2895. Window child, phonyWin;
  2896. int phony;
  2897. unsigned int uphony;
  2898. XQueryPointer (display, targetWindow, &phonyWin, &child,
  2899. &phony, &phony, &phony, &phony, &uphony);
  2900. return externalFindDragTargetWindow (child);
  2901. }
  2902. bool externalDragInit (bool isText, const String& textOrFiles)
  2903. {
  2904. ScopedXLock xlock;
  2905. resetExternalDragState();
  2906. dragState.isText = isText;
  2907. dragState.textOrFiles = textOrFiles;
  2908. dragState.targetWindow = windowH;
  2909. const int pointerGrabMask = Button1MotionMask | ButtonReleaseMask;
  2910. if (XGrabPointer (display, windowH, True, pointerGrabMask,
  2911. GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
  2912. {
  2913. // No other method of changing the pointer seems to work, this call is needed from this very context
  2914. XChangeActivePointerGrab (display, pointerGrabMask, (Cursor) createDraggingHandCursor(), CurrentTime);
  2915. const Atoms& atoms = Atoms::get();
  2916. XSetSelectionOwner (display, atoms.XdndSelection, windowH, CurrentTime);
  2917. // save the available types to XdndTypeList
  2918. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32,
  2919. dragState.getMimeTypes(),
  2920. dragState.getNumMimeTypes());
  2921. dragState.dragging = true;
  2922. handleExternalDragMotionNotify();
  2923. return true;
  2924. }
  2925. return false;
  2926. }
  2927. void externalResetDragAndDrop()
  2928. {
  2929. if (dragState.dragging)
  2930. {
  2931. ScopedXLock xlock;
  2932. XUngrabPointer (display, CurrentTime);
  2933. }
  2934. resetExternalDragState();
  2935. }
  2936. DragState dragState;
  2937. DragInfo dragInfo;
  2938. Atom dragAndDropCurrentMimeType;
  2939. Window dragAndDropSourceWindow;
  2940. bool finishAfterDropDataReceived;
  2941. Array<Atom> srcMimeTypeAtomList;
  2942. int pointerMap[5];
  2943. void initialisePointerMap()
  2944. {
  2945. const int numButtons = XGetPointerMapping (display, 0, 0);
  2946. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2947. if (numButtons == 2)
  2948. {
  2949. pointerMap[0] = Keys::LeftButton;
  2950. pointerMap[1] = Keys::RightButton;
  2951. }
  2952. else if (numButtons >= 3)
  2953. {
  2954. pointerMap[0] = Keys::LeftButton;
  2955. pointerMap[1] = Keys::MiddleButton;
  2956. pointerMap[2] = Keys::RightButton;
  2957. if (numButtons >= 5)
  2958. {
  2959. pointerMap[3] = Keys::WheelUp;
  2960. pointerMap[4] = Keys::WheelDown;
  2961. }
  2962. }
  2963. }
  2964. static Point<int> lastMousePos;
  2965. static void clearLastMousePos() noexcept
  2966. {
  2967. lastMousePos = Point<int> (0x100000, 0x100000);
  2968. }
  2969. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  2970. };
  2971. ModifierKeys LinuxComponentPeer::currentModifiers;
  2972. bool LinuxComponentPeer::isActiveApplication = false;
  2973. Point<int> LinuxComponentPeer::lastMousePos;
  2974. //==============================================================================
  2975. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess()
  2976. {
  2977. return LinuxComponentPeer::isActiveApplication;
  2978. }
  2979. // N/A on Linux as far as I know.
  2980. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2981. JUCE_API void JUCE_CALLTYPE Process::hide() {}
  2982. //==============================================================================
  2983. void ModifierKeys::updateCurrentModifiers() noexcept
  2984. {
  2985. currentModifiers = LinuxComponentPeer::currentModifiers;
  2986. }
  2987. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2988. {
  2989. if (display != nullptr)
  2990. {
  2991. Window root, child;
  2992. int x, y, winx, winy;
  2993. unsigned int mask;
  2994. int mouseMods = 0;
  2995. ScopedXLock xlock;
  2996. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  2997. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  2998. {
  2999. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  3000. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  3001. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  3002. }
  3003. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  3004. }
  3005. return LinuxComponentPeer::currentModifiers;
  3006. }
  3007. //==============================================================================
  3008. void Desktop::setKioskComponent (Component* comp, bool enableOrDisable, bool /* allowMenusAndBars */)
  3009. {
  3010. if (enableOrDisable)
  3011. comp->setBounds (getDisplays().getMainDisplay().totalArea);
  3012. }
  3013. //==============================================================================
  3014. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  3015. {
  3016. return new LinuxComponentPeer (*this, styleFlags, (Window) nativeWindowToAttachTo);
  3017. }
  3018. //==============================================================================
  3019. void Desktop::Displays::findDisplays (float masterScale)
  3020. {
  3021. DisplayGeometry& geometry = DisplayGeometry::getOrCreateInstance (display, masterScale);
  3022. for (int i = 0; i < geometry.infos.size(); ++i)
  3023. {
  3024. const DisplayGeometry::ExtendedInfo& info = geometry.infos.getReference (i);
  3025. Desktop::Displays::Display d;
  3026. d.isMain = info.isMain;
  3027. d.scale = masterScale * info.scale;
  3028. d.dpi = info.dpi;
  3029. d.totalArea = DisplayGeometry::physicalToScaled (info.totalBounds);
  3030. d.userArea = (info.usableBounds / d.scale) + info.topLeftScaled;
  3031. displays.add (d);
  3032. }
  3033. }
  3034. //==============================================================================
  3035. bool MouseInputSource::SourceList::addSource()
  3036. {
  3037. if (sources.size() == 0)
  3038. {
  3039. addSource (0, true);
  3040. return true;
  3041. }
  3042. return false;
  3043. }
  3044. bool Desktop::canUseSemiTransparentWindows() noexcept
  3045. {
  3046. #if JUCE_USE_XRENDER
  3047. if (XRender::hasCompositingWindowManager())
  3048. {
  3049. int matchedDepth = 0, desiredDepth = 32;
  3050. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  3051. && matchedDepth == desiredDepth;
  3052. }
  3053. #endif
  3054. return false;
  3055. }
  3056. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3057. {
  3058. if (display == nullptr)
  3059. return Point<float>();
  3060. Window root, child;
  3061. int x, y, winx, winy;
  3062. unsigned int mask;
  3063. ScopedXLock xlock;
  3064. if (XQueryPointer (display,
  3065. RootWindow (display, DefaultScreen (display)),
  3066. &root, &child,
  3067. &x, &y, &winx, &winy, &mask) == False)
  3068. {
  3069. // Pointer not on the default screen
  3070. x = y = -1;
  3071. }
  3072. return DisplayGeometry::physicalToScaled (Point<float> ((float) x, (float) y));
  3073. }
  3074. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3075. {
  3076. if (display != nullptr)
  3077. {
  3078. ScopedXLock xlock;
  3079. Window root = RootWindow (display, DefaultScreen (display));
  3080. newPosition = DisplayGeometry::scaledToPhysical (newPosition);
  3081. XWarpPointer (display, None, root, 0, 0, 0, 0, roundToInt (newPosition.getX()), roundToInt (newPosition.getY()));
  3082. }
  3083. }
  3084. double Desktop::getDefaultMasterScale()
  3085. {
  3086. return 1.0;
  3087. }
  3088. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  3089. {
  3090. return upright;
  3091. }
  3092. //==============================================================================
  3093. static bool screenSaverAllowed = true;
  3094. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3095. {
  3096. if (screenSaverAllowed != isEnabled)
  3097. {
  3098. screenSaverAllowed = isEnabled;
  3099. if (display != nullptr)
  3100. {
  3101. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  3102. static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
  3103. if (xScreenSaverSuspend == nullptr)
  3104. if (void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW))
  3105. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  3106. ScopedXLock xlock;
  3107. if (xScreenSaverSuspend != nullptr)
  3108. xScreenSaverSuspend (display, ! isEnabled);
  3109. }
  3110. }
  3111. }
  3112. bool Desktop::isScreenSaverEnabled()
  3113. {
  3114. return screenSaverAllowed;
  3115. }
  3116. //==============================================================================
  3117. void* CustomMouseCursorInfo::create() const
  3118. {
  3119. if (display == nullptr)
  3120. return nullptr;
  3121. ScopedXLock xlock;
  3122. const unsigned int imageW = (unsigned int) image.getWidth();
  3123. const unsigned int imageH = (unsigned int) image.getHeight();
  3124. int hotspotX = hotspot.x;
  3125. int hotspotY = hotspot.y;
  3126. #if JUCE_USE_XCURSOR
  3127. {
  3128. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  3129. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  3130. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  3131. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  3132. static tXcursorSupportsARGB xcursorSupportsARGB = nullptr;
  3133. static tXcursorImageCreate xcursorImageCreate = nullptr;
  3134. static tXcursorImageDestroy xcursorImageDestroy = nullptr;
  3135. static tXcursorImageLoadCursor xcursorImageLoadCursor = nullptr;
  3136. static bool hasBeenLoaded = false;
  3137. if (! hasBeenLoaded)
  3138. {
  3139. hasBeenLoaded = true;
  3140. if (void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW))
  3141. {
  3142. xcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  3143. xcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  3144. xcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  3145. xcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  3146. if (xcursorSupportsARGB == nullptr || xcursorImageCreate == nullptr
  3147. || xcursorImageLoadCursor == nullptr || xcursorImageDestroy == nullptr
  3148. || ! xcursorSupportsARGB (display))
  3149. xcursorSupportsARGB = nullptr;
  3150. }
  3151. }
  3152. if (xcursorSupportsARGB != nullptr)
  3153. {
  3154. if (XcursorImage* xcImage = xcursorImageCreate ((int) imageW, (int) imageH))
  3155. {
  3156. xcImage->xhot = (XcursorDim) hotspotX;
  3157. xcImage->yhot = (XcursorDim) hotspotY;
  3158. XcursorPixel* dest = xcImage->pixels;
  3159. for (int y = 0; y < (int) imageH; ++y)
  3160. for (int x = 0; x < (int) imageW; ++x)
  3161. *dest++ = image.getPixelAt (x, y).getARGB();
  3162. void* result = (void*) xcursorImageLoadCursor (display, xcImage);
  3163. xcursorImageDestroy (xcImage);
  3164. if (result != nullptr)
  3165. return result;
  3166. }
  3167. }
  3168. }
  3169. #endif
  3170. Window root = RootWindow (display, DefaultScreen (display));
  3171. unsigned int cursorW, cursorH;
  3172. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  3173. return nullptr;
  3174. Image im (Image::ARGB, (int) cursorW, (int) cursorH, true);
  3175. {
  3176. Graphics g (im);
  3177. if (imageW > cursorW || imageH > cursorH)
  3178. {
  3179. hotspotX = (hotspotX * (int) cursorW) / (int) imageW;
  3180. hotspotY = (hotspotY * (int) cursorH) / (int) imageH;
  3181. g.drawImageWithin (image, 0, 0, (int) imageW, (int) imageH,
  3182. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  3183. false);
  3184. }
  3185. else
  3186. {
  3187. g.drawImageAt (image, 0, 0);
  3188. }
  3189. }
  3190. const unsigned int stride = (cursorW + 7) >> 3;
  3191. HeapBlock<char> maskPlane, sourcePlane;
  3192. maskPlane.calloc (stride * cursorH);
  3193. sourcePlane.calloc (stride * cursorH);
  3194. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  3195. for (int y = (int) cursorH; --y >= 0;)
  3196. {
  3197. for (int x = (int) cursorW; --x >= 0;)
  3198. {
  3199. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  3200. const unsigned int offset = (unsigned int) y * stride + ((unsigned int) x >> 3);
  3201. const Colour c (im.getPixelAt (x, y));
  3202. if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
  3203. if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
  3204. }
  3205. }
  3206. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3207. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3208. XColor white, black;
  3209. black.red = black.green = black.blue = 0;
  3210. white.red = white.green = white.blue = 0xffff;
  3211. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black,
  3212. (unsigned int) hotspotX, (unsigned int) hotspotY);
  3213. XFreePixmap (display, sourcePixmap);
  3214. XFreePixmap (display, maskPixmap);
  3215. return result;
  3216. }
  3217. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  3218. {
  3219. if (cursorHandle != nullptr && display != nullptr)
  3220. {
  3221. ScopedXLock xlock;
  3222. XFreeCursor (display, (Cursor) cursorHandle);
  3223. }
  3224. }
  3225. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  3226. {
  3227. if (display == nullptr)
  3228. return None;
  3229. unsigned int shape;
  3230. switch (type)
  3231. {
  3232. case NormalCursor:
  3233. case ParentCursor: return None; // Use parent cursor
  3234. case NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), 0, 0).create();
  3235. case WaitCursor: shape = XC_watch; break;
  3236. case IBeamCursor: shape = XC_xterm; break;
  3237. case PointingHandCursor: shape = XC_hand2; break;
  3238. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  3239. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  3240. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  3241. case TopEdgeResizeCursor: shape = XC_top_side; break;
  3242. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  3243. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  3244. case RightEdgeResizeCursor: shape = XC_right_side; break;
  3245. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  3246. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  3247. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  3248. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  3249. case CrosshairCursor: shape = XC_crosshair; break;
  3250. case DraggingHandCursor: return createDraggingHandCursor();
  3251. case CopyingCursor:
  3252. {
  3253. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3254. 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,
  3255. 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,
  3256. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3257. const int copyCursorSize = 119;
  3258. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
  3259. }
  3260. default:
  3261. jassertfalse;
  3262. return None;
  3263. }
  3264. ScopedXLock xlock;
  3265. return (void*) XCreateFontCursor (display, shape);
  3266. }
  3267. void MouseCursor::showInWindow (ComponentPeer* peer) const
  3268. {
  3269. if (LinuxComponentPeer* const lp = dynamic_cast<LinuxComponentPeer*> (peer))
  3270. lp->showMouseCursor ((Cursor) getHandle());
  3271. }
  3272. void MouseCursor::showInAllWindows() const
  3273. {
  3274. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  3275. showInWindow (ComponentPeer::getPeer (i));
  3276. }
  3277. //==============================================================================
  3278. Image juce_createIconForFile (const File& /* file */)
  3279. {
  3280. return Image::null;
  3281. }
  3282. //==============================================================================
  3283. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  3284. {
  3285. if (files.size() == 0)
  3286. return false;
  3287. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  3288. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  3289. if (LinuxComponentPeer* const lp = dynamic_cast<LinuxComponentPeer*> (sourceComp->getPeer()))
  3290. return lp->externalDragFileInit (files, canMoveFiles);
  3291. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3292. jassertfalse;
  3293. return false;
  3294. }
  3295. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  3296. {
  3297. if (text.isEmpty())
  3298. return false;
  3299. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  3300. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  3301. if (LinuxComponentPeer* const lp = dynamic_cast<LinuxComponentPeer*> (sourceComp->getPeer()))
  3302. return lp->externalDragTextInit (text);
  3303. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3304. jassertfalse;
  3305. return false;
  3306. }
  3307. //==============================================================================
  3308. void LookAndFeel::playAlertSound()
  3309. {
  3310. std::cout << "\a" << std::flush;
  3311. }
  3312. //==============================================================================
  3313. Rectangle<int> juce_LinuxScaledToPhysicalBounds(ComponentPeer* peer, const Rectangle<int>& bounds)
  3314. {
  3315. Rectangle<int> retval = bounds;
  3316. if (LinuxComponentPeer* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3317. retval *= linuxPeer->getCurrentScale();
  3318. return retval;
  3319. }
  3320. //==============================================================================
  3321. #if JUCE_MODAL_LOOPS_PERMITTED
  3322. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3323. const String& title, const String& message,
  3324. Component* /* associatedComponent */)
  3325. {
  3326. AlertWindow::showMessageBox (iconType, title, message);
  3327. }
  3328. #endif
  3329. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3330. const String& title, const String& message,
  3331. Component* associatedComponent,
  3332. ModalComponentManager::Callback* callback)
  3333. {
  3334. AlertWindow::showMessageBoxAsync (iconType, title, message, String::empty, associatedComponent, callback);
  3335. }
  3336. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3337. const String& title, const String& message,
  3338. Component* associatedComponent,
  3339. ModalComponentManager::Callback* callback)
  3340. {
  3341. return AlertWindow::showOkCancelBox (iconType, title, message, String::empty, String::empty,
  3342. associatedComponent, callback);
  3343. }
  3344. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3345. const String& title, const String& message,
  3346. Component* associatedComponent,
  3347. ModalComponentManager::Callback* callback)
  3348. {
  3349. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  3350. String::empty, String::empty, String::empty,
  3351. associatedComponent, callback);
  3352. }
  3353. //==============================================================================
  3354. const int KeyPress::spaceKey = XK_space & 0xff;
  3355. const int KeyPress::returnKey = XK_Return & 0xff;
  3356. const int KeyPress::escapeKey = XK_Escape & 0xff;
  3357. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  3358. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  3359. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  3360. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  3361. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  3362. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  3363. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  3364. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  3365. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  3366. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  3367. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  3368. const int KeyPress::tabKey = XK_Tab & 0xff;
  3369. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  3370. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  3371. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  3372. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  3373. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  3374. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  3375. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  3376. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  3377. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  3378. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  3379. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  3380. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  3381. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  3382. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  3383. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  3384. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  3385. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  3386. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  3387. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  3388. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  3389. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  3390. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  3391. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  3392. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  3393. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  3394. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  3395. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  3396. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  3397. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  3398. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  3399. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  3400. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  3401. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  3402. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  3403. const int KeyPress::playKey = ((int) 0xffeeff00) | Keys::extendedKeyModifier;
  3404. const int KeyPress::stopKey = ((int) 0xffeeff01) | Keys::extendedKeyModifier;
  3405. const int KeyPress::fastForwardKey = ((int) 0xffeeff02) | Keys::extendedKeyModifier;
  3406. const int KeyPress::rewindKey = ((int) 0xffeeff03) | Keys::extendedKeyModifier;