The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4173 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 *dpy, ::Window window);
  895. typedef void (*tXRRFreeScreenResources) (XRRScreenResources *resources);
  896. typedef XRROutputInfo* (*tXRRGetOutputInfo) (::Display *dpy, XRRScreenResources *resources, RROutput output);
  897. typedef void (*tXRRFreeOutputInfo) (XRROutputInfo *outputInfo);
  898. typedef XRRCrtcInfo* (*tXRRGetCrtcInfo) (::Display *dpy, XRRScreenResources *resources, RRCrtc crtc);
  899. typedef void (*tXRRFreeCrtcInfo) (XRRCrtcInfo *crtcInfo);
  900. typedef RROutput (*tXRRGetOutputPrimary) (::Display *dpy, ::Window 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. ScopedPointer<XRROutputInfo> output;
  992. if ((output = xrandr.getOutputInfo (dpy, screens.get(), screens->outputs[j])).get())
  993. {
  994. if (! output->crtc)
  995. continue;
  996. ScopedPointer<XRRCrtcInfo> crtc;
  997. if ((crtc = xrandr.getCrtcInfo (dpy, screens.get(), output->crtc)).get())
  998. {
  999. ExtendedInfo e;
  1000. e.totalBounds = Rectangle<int> (crtc->x, crtc->y,
  1001. (int) crtc->width, (int) crtc->height);
  1002. e.usableBounds = e.totalBounds.withZeroOrigin(); // Support for usable area is not implemented in JUCE yet
  1003. e.topLeftScaled = e.totalBounds.getTopLeft();
  1004. e.isMain = (mainDisplay == screens->outputs[j]) && (i == 0);
  1005. e.dpi = ((static_cast<double> (crtc->width) * 25.4 * 0.5) / static_cast<double> (output->mm_width))
  1006. + ((static_cast<double> (crtc->height) * 25.4 * 0.5) / static_cast<double> (output->mm_height));
  1007. e.scale = masterScale * getScaleForDisplay (output->name, e);
  1008. infos.add (e);
  1009. }
  1010. }
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. if (infos.size() == 0)
  1017. #endif
  1018. #if JUCE_USE_XINERAMA
  1019. {
  1020. Array<XineramaScreenInfo> screens = XineramaQueryDisplays (dpy);
  1021. int numMonitors = screens.size();
  1022. for (int index = 0; index < numMonitors; ++index)
  1023. {
  1024. for (int j = numMonitors; --j >= 0;)
  1025. {
  1026. if (screens[j].screen_number == index)
  1027. {
  1028. ExtendedInfo e;
  1029. e.totalBounds = Rectangle<int> (screens[j].x_org,
  1030. screens[j].y_org,
  1031. screens[j].width,
  1032. screens[j].height);
  1033. e.usableBounds = e.totalBounds.withZeroOrigin(); // Support for usable area is not implemented in JUCE yet
  1034. e.topLeftScaled = e.totalBounds.getTopLeft(); // this will be overwritten by updatePositions later
  1035. e.isMain = (index == 0);
  1036. e.scale = masterScale;
  1037. e.dpi = getDisplayDPI (0); // (all screens share the same DPI)
  1038. infos.add (e);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. if (infos.size() == 0)
  1044. #endif
  1045. {
  1046. Atom hints = Atoms::getIfExists ("_NET_WORKAREA");
  1047. if (hints != None)
  1048. {
  1049. const int numMonitors = ScreenCount (dpy);
  1050. for (int i = 0; i < numMonitors; ++i)
  1051. {
  1052. GetXProperty prop (RootWindow (dpy, i), hints, 0, 4, false, XA_CARDINAL);
  1053. if (prop.success && prop.actualType == XA_CARDINAL && prop.actualFormat == 32 && prop.numItems == 4)
  1054. {
  1055. const long* const position = (const long*) prop.data;
  1056. ExtendedInfo e;
  1057. e.totalBounds = Rectangle<int> ((int) position[0], (int) position[1],
  1058. (int) position[2], (int) position[3]);
  1059. e.usableBounds = e.totalBounds.withZeroOrigin(); // Support for usable area is not implemented in JUCE yet
  1060. e.topLeftScaled = e.totalBounds.getTopLeft(); // this will be overwritten by updatePositions later
  1061. e.isMain = (infos.size() == 0);
  1062. e.scale = masterScale;
  1063. e.dpi = getDisplayDPI (i);
  1064. infos.add (e);
  1065. }
  1066. }
  1067. }
  1068. if (infos.size() == 0)
  1069. {
  1070. ExtendedInfo e;
  1071. e.totalBounds = Rectangle<int> (DisplayWidth (dpy, DefaultScreen (dpy)),
  1072. DisplayHeight (dpy, DefaultScreen (dpy)));
  1073. e.usableBounds = e.totalBounds; // Support for usable area is not implemented in JUCE yet
  1074. e.topLeftScaled = e.totalBounds.getTopLeft(); // this will be overwritten by updatePositions later
  1075. e.isMain = true;
  1076. e.scale = masterScale;
  1077. e.dpi = getDisplayDPI (0);
  1078. infos.add (e);
  1079. }
  1080. }
  1081. }
  1082. //==============================================================================
  1083. struct SortByCoordinate
  1084. {
  1085. bool sortByYCoordinate;
  1086. SortByCoordinate (bool byYCoordinate)
  1087. : sortByYCoordinate (byYCoordinate)
  1088. {
  1089. }
  1090. int compareElements (const ExtendedInfo* a, const ExtendedInfo* b)
  1091. {
  1092. int coordinateA, coordinateB;
  1093. if (sortByYCoordinate)
  1094. {
  1095. coordinateA = a->totalBounds.getY();
  1096. coordinateB = b->totalBounds.getY();
  1097. }
  1098. else
  1099. {
  1100. coordinateA = a->totalBounds.getX();
  1101. coordinateB = b->totalBounds.getX();
  1102. }
  1103. return coordinateA - coordinateB;
  1104. }
  1105. };
  1106. //==============================================================================
  1107. void updateScaledDisplayCoordinate(bool updateYCoordinates)
  1108. {
  1109. if (infos.size() < 2)
  1110. return;
  1111. Array<ExtendedInfo*> copy;
  1112. {
  1113. SortByCoordinate sorter (updateYCoordinates);
  1114. for (int i = 0; i < infos.size(); ++i)
  1115. copy.addSorted (sorter, &infos.getReference (i));
  1116. }
  1117. for (int i = 1; i < copy.size(); ++i)
  1118. {
  1119. ExtendedInfo& current = *copy[i];
  1120. // Is this screen's position aligned to any other previous display?
  1121. for (int j = i - 1; j >= 0; --j)
  1122. {
  1123. ExtendedInfo& other = *copy[j];
  1124. int prevCoordinate = updateYCoordinates ? other.totalBounds.getBottom() : other.totalBounds.getRight();
  1125. int curCoordinate = updateYCoordinates ? current.totalBounds.getY() : current.totalBounds.getX();
  1126. if (prevCoordinate == curCoordinate)
  1127. {
  1128. // both displays are aligned! As "other" comes before "current" in the array, it must already
  1129. // have a valid topLeftScaled which we can use
  1130. Point<int> topLeftScaled = other.topLeftScaled;
  1131. topLeftScaled += Point<int> (other.totalBounds.getWidth(), other.totalBounds.getHeight()) / other.scale;
  1132. if (updateYCoordinates)
  1133. current.topLeftScaled.setY (topLeftScaled.getY());
  1134. else
  1135. current.topLeftScaled.setX (topLeftScaled.getX());
  1136. break;
  1137. }
  1138. }
  1139. }
  1140. }
  1141. void updatePositions()
  1142. {
  1143. updateScaledDisplayCoordinate (false);
  1144. updateScaledDisplayCoordinate (true);
  1145. }
  1146. };
  1147. DisplayGeometry* DisplayGeometry::instance = nullptr;
  1148. #if JUCE_USE_XRANDR
  1149. DisplayGeometry::XRandrWrapper* DisplayGeometry::XRandrWrapper::instance = nullptr;
  1150. void ContainerDeletePolicy<XRRScreenResources>::destroy (XRRScreenResources* ptr)
  1151. {
  1152. if (ptr != nullptr)
  1153. DisplayGeometry::XRandrWrapper::getInstance().freeScreenResources (ptr);
  1154. }
  1155. void ContainerDeletePolicy<XRROutputInfo>::destroy (XRROutputInfo* ptr)
  1156. {
  1157. if (ptr != nullptr)
  1158. DisplayGeometry::XRandrWrapper::getInstance().freeOutputInfo (ptr);
  1159. }
  1160. void ContainerDeletePolicy<XRRCrtcInfo>::destroy (XRRCrtcInfo* ptr)
  1161. {
  1162. if (ptr != nullptr)
  1163. DisplayGeometry::XRandrWrapper::getInstance().freeCrtcInfo (ptr);
  1164. }
  1165. #endif
  1166. //==============================================================================
  1167. namespace PixmapHelpers
  1168. {
  1169. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  1170. {
  1171. ScopedXLock xlock;
  1172. const unsigned int width = (unsigned int) image.getWidth();
  1173. const unsigned int height = (unsigned int) image.getHeight();
  1174. HeapBlock<uint32> colour (width * height);
  1175. int index = 0;
  1176. for (int y = 0; y < (int) height; ++y)
  1177. for (int x = 0; x < (int) width; ++x)
  1178. colour[index++] = image.getPixelAt (x, y).getARGB();
  1179. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  1180. 0, reinterpret_cast<char*> (colour.getData()),
  1181. width, height, 32, 0);
  1182. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  1183. width, height, 24);
  1184. GC gc = XCreateGC (display, pixmap, 0, 0);
  1185. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  1186. XFreeGC (display, gc);
  1187. return pixmap;
  1188. }
  1189. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  1190. {
  1191. ScopedXLock xlock;
  1192. const unsigned int width = (unsigned int) image.getWidth();
  1193. const unsigned int height = (unsigned int) image.getHeight();
  1194. const unsigned int stride = (width + 7) >> 3;
  1195. HeapBlock<char> mask;
  1196. mask.calloc (stride * height);
  1197. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  1198. for (unsigned int y = 0; y < height; ++y)
  1199. {
  1200. for (unsigned int x = 0; x < width; ++x)
  1201. {
  1202. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  1203. const unsigned int offset = y * stride + (x >> 3);
  1204. if (image.getPixelAt ((int) x, (int) y).getAlpha() >= 128)
  1205. mask[offset] |= bit;
  1206. }
  1207. }
  1208. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  1209. mask.getData(), width, height, 1, 0, 1);
  1210. }
  1211. }
  1212. static void* createDraggingHandCursor()
  1213. {
  1214. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  1215. 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,
  1216. 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 };
  1217. const int dragHandDataSize = 99;
  1218. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7).create();
  1219. }
  1220. //==============================================================================
  1221. static int numAlwaysOnTopPeers = 0;
  1222. bool juce_areThereAnyAlwaysOnTopWindows()
  1223. {
  1224. return numAlwaysOnTopPeers > 0;
  1225. }
  1226. //==============================================================================
  1227. class LinuxComponentPeer : public ComponentPeer
  1228. {
  1229. public:
  1230. LinuxComponentPeer (Component& comp, const int windowStyleFlags, Window parentToAddTo)
  1231. : ComponentPeer (comp, windowStyleFlags),
  1232. windowH (0), parentWindow (0),
  1233. fullScreen (false), mapped (false),
  1234. visual (nullptr), depth (0),
  1235. isAlwaysOnTop (comp.isAlwaysOnTop()),
  1236. currentScaleFactor (1.0)
  1237. {
  1238. // it's dangerous to create a window on a thread other than the message thread..
  1239. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  1240. dispatchWindowMessage = windowMessageReceive;
  1241. repainter = new LinuxRepaintManager (*this);
  1242. if (isAlwaysOnTop)
  1243. ++numAlwaysOnTopPeers;
  1244. createWindow (parentToAddTo);
  1245. setTitle (component.getName());
  1246. }
  1247. ~LinuxComponentPeer()
  1248. {
  1249. // it's dangerous to delete a window on a thread other than the message thread..
  1250. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  1251. deleteIconPixmaps();
  1252. destroyWindow();
  1253. windowH = 0;
  1254. if (isAlwaysOnTop)
  1255. --numAlwaysOnTopPeers;
  1256. }
  1257. // (this callback is hooked up in the messaging code)
  1258. static void windowMessageReceive (XEvent& event)
  1259. {
  1260. if (event.xany.window != None)
  1261. {
  1262. if (LinuxComponentPeer* const peer = getPeerFor (event.xany.window))
  1263. peer->handleWindowMessage (event);
  1264. }
  1265. else if (event.xany.type == KeymapNotify)
  1266. {
  1267. const XKeymapEvent& keymapEvent = (const XKeymapEvent&) event.xkeymap;
  1268. memcpy (Keys::keyStates, keymapEvent.key_vector, 32);
  1269. }
  1270. }
  1271. //==============================================================================
  1272. void* getNativeHandle() const override
  1273. {
  1274. return (void*) windowH;
  1275. }
  1276. static LinuxComponentPeer* getPeerFor (Window windowHandle) noexcept
  1277. {
  1278. XPointer peer = nullptr;
  1279. if (display != nullptr)
  1280. {
  1281. ScopedXLock xlock;
  1282. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  1283. if (peer != nullptr && ! ComponentPeer::isValidPeer (reinterpret_cast<LinuxComponentPeer*> (peer)))
  1284. peer = nullptr;
  1285. }
  1286. return reinterpret_cast<LinuxComponentPeer*> (peer);
  1287. }
  1288. void setVisible (bool shouldBeVisible) override
  1289. {
  1290. ScopedXLock xlock;
  1291. if (shouldBeVisible)
  1292. XMapWindow (display, windowH);
  1293. else
  1294. XUnmapWindow (display, windowH);
  1295. }
  1296. void setTitle (const String& title) override
  1297. {
  1298. XTextProperty nameProperty;
  1299. char* strings[] = { const_cast<char*> (title.toRawUTF8()) };
  1300. ScopedXLock xlock;
  1301. if (XStringListToTextProperty (strings, 1, &nameProperty))
  1302. {
  1303. XSetWMName (display, windowH, &nameProperty);
  1304. XSetWMIconName (display, windowH, &nameProperty);
  1305. XFree (nameProperty.value);
  1306. }
  1307. }
  1308. void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
  1309. {
  1310. if (fullScreen && ! isNowFullScreen)
  1311. {
  1312. // When transitioning back from fullscreen, we might need to remove
  1313. // the FULLSCREEN window property
  1314. Atom fs = Atoms::getIfExists ("_NET_WM_STATE_FULLSCREEN");
  1315. if (fs != None)
  1316. {
  1317. Window root = RootWindow (display, DefaultScreen (display));
  1318. XClientMessageEvent clientMsg;
  1319. clientMsg.display = display;
  1320. clientMsg.window = windowH;
  1321. clientMsg.type = ClientMessage;
  1322. clientMsg.format = 32;
  1323. clientMsg.message_type = Atoms::get().windowState;
  1324. clientMsg.data.l[0] = 0; // Remove
  1325. clientMsg.data.l[1] = (long) fs;
  1326. clientMsg.data.l[2] = 0;
  1327. clientMsg.data.l[3] = 1; // Normal Source
  1328. ScopedXLock xlock;
  1329. XSendEvent (display, root, false,
  1330. SubstructureRedirectMask | SubstructureNotifyMask,
  1331. (XEvent*) &clientMsg);
  1332. }
  1333. }
  1334. fullScreen = isNowFullScreen;
  1335. if (windowH != 0)
  1336. {
  1337. bounds = newBounds.withSize (jmax (1, newBounds.getWidth()),
  1338. jmax (1, newBounds.getHeight()));
  1339. currentScaleFactor = DisplayGeometry::getInstance().findDisplayForRect (bounds, true).scale;
  1340. Rectangle<int> physicalBounds =
  1341. DisplayGeometry::scaledToPhysical (bounds);
  1342. WeakReference<Component> deletionChecker (&component);
  1343. ScopedXLock xlock;
  1344. XSizeHints* const hints = XAllocSizeHints();
  1345. hints->flags = USSize | USPosition;
  1346. hints->x = physicalBounds.getX();
  1347. hints->y = physicalBounds.getY();
  1348. hints->width = physicalBounds.getWidth();
  1349. hints->height = physicalBounds.getHeight();
  1350. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  1351. {
  1352. hints->min_width = hints->max_width = hints->width;
  1353. hints->min_height = hints->max_height = hints->height;
  1354. hints->flags |= PMinSize | PMaxSize;
  1355. }
  1356. XSetWMNormalHints (display, windowH, hints);
  1357. XFree (hints);
  1358. XMoveResizeWindow (display, windowH,
  1359. physicalBounds.getX() - windowBorder.getLeft(),
  1360. physicalBounds.getY() - windowBorder.getTop(),
  1361. (unsigned int) physicalBounds.getWidth(),
  1362. (unsigned int) physicalBounds.getHeight());
  1363. if (deletionChecker != nullptr)
  1364. {
  1365. updateBorderSize();
  1366. handleMovedOrResized();
  1367. }
  1368. }
  1369. }
  1370. Rectangle<int> getBounds() const override { return bounds; }
  1371. Point<float> localToGlobal (Point<float> relativePosition) override
  1372. {
  1373. return relativePosition + bounds.getPosition().toFloat();
  1374. }
  1375. Point<float> globalToLocal (Point<float> screenPosition) override
  1376. {
  1377. return screenPosition - bounds.getPosition().toFloat();
  1378. }
  1379. void setAlpha (float /* newAlpha */) override
  1380. {
  1381. //xxx todo!
  1382. }
  1383. StringArray getAvailableRenderingEngines() override
  1384. {
  1385. return StringArray ("Software Renderer");
  1386. }
  1387. void setMinimised (bool shouldBeMinimised) override
  1388. {
  1389. if (shouldBeMinimised)
  1390. {
  1391. Window root = RootWindow (display, DefaultScreen (display));
  1392. XClientMessageEvent clientMsg;
  1393. clientMsg.display = display;
  1394. clientMsg.window = windowH;
  1395. clientMsg.type = ClientMessage;
  1396. clientMsg.format = 32;
  1397. clientMsg.message_type = Atoms::get().changeState;
  1398. clientMsg.data.l[0] = IconicState;
  1399. ScopedXLock xlock;
  1400. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  1401. }
  1402. else
  1403. {
  1404. setVisible (true);
  1405. }
  1406. }
  1407. bool isMinimised() const override
  1408. {
  1409. ScopedXLock xlock;
  1410. const Atoms& atoms = Atoms::get();
  1411. GetXProperty prop (windowH, atoms.state, 0, 64, false, atoms.state);
  1412. return prop.success
  1413. && prop.actualType == atoms.state
  1414. && prop.actualFormat == 32
  1415. && prop.numItems > 0
  1416. && ((unsigned long*) prop.data)[0] == IconicState;
  1417. }
  1418. void setFullScreen (const bool shouldBeFullScreen) override
  1419. {
  1420. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  1421. setMinimised (false);
  1422. if (fullScreen != shouldBeFullScreen)
  1423. {
  1424. if (shouldBeFullScreen)
  1425. r = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  1426. if (! r.isEmpty())
  1427. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  1428. component.repaint();
  1429. }
  1430. }
  1431. bool isFullScreen() const override
  1432. {
  1433. return fullScreen;
  1434. }
  1435. bool isChildWindowOf (Window possibleParent) const
  1436. {
  1437. Window* windowList = nullptr;
  1438. uint32 windowListSize = 0;
  1439. Window parent, root;
  1440. ScopedXLock xlock;
  1441. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  1442. {
  1443. if (windowList != nullptr)
  1444. XFree (windowList);
  1445. return parent == possibleParent;
  1446. }
  1447. return false;
  1448. }
  1449. bool isFrontWindow() const
  1450. {
  1451. Window* windowList = nullptr;
  1452. uint32 windowListSize = 0;
  1453. bool result = false;
  1454. ScopedXLock xlock;
  1455. Window parent, root = RootWindow (display, DefaultScreen (display));
  1456. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  1457. {
  1458. for (int i = (int) windowListSize; --i >= 0;)
  1459. {
  1460. if (LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]))
  1461. {
  1462. result = (peer == this);
  1463. break;
  1464. }
  1465. }
  1466. }
  1467. if (windowList != nullptr)
  1468. XFree (windowList);
  1469. return result;
  1470. }
  1471. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  1472. {
  1473. if (! bounds.withZeroOrigin().contains (localPos))
  1474. return false;
  1475. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1476. {
  1477. Component* const c = Desktop::getInstance().getComponent (i);
  1478. if (c == &component)
  1479. break;
  1480. if (ComponentPeer* peer = c->getPeer())
  1481. if (peer->contains (localPos + bounds.getPosition() - peer->getBounds().getPosition(), true))
  1482. return false;
  1483. }
  1484. if (trueIfInAChildWindow)
  1485. return true;
  1486. ::Window root, child;
  1487. int wx, wy;
  1488. unsigned int ww, wh, bw, bitDepth;
  1489. ScopedXLock xlock;
  1490. localPos *= currentScaleFactor;
  1491. return XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth)
  1492. && XTranslateCoordinates (display, windowH, windowH, localPos.getX(), localPos.getY(), &wx, &wy, &child)
  1493. && child == None;
  1494. }
  1495. BorderSize<int> getFrameSize() const override
  1496. {
  1497. return BorderSize<int>();
  1498. }
  1499. bool setAlwaysOnTop (bool /* alwaysOnTop */) override
  1500. {
  1501. return false;
  1502. }
  1503. void toFront (bool makeActive) override
  1504. {
  1505. if (makeActive)
  1506. {
  1507. setVisible (true);
  1508. grabFocus();
  1509. }
  1510. {
  1511. ScopedXLock xlock;
  1512. XEvent ev;
  1513. ev.xclient.type = ClientMessage;
  1514. ev.xclient.serial = 0;
  1515. ev.xclient.send_event = True;
  1516. ev.xclient.message_type = Atoms::get().activeWin;
  1517. ev.xclient.window = windowH;
  1518. ev.xclient.format = 32;
  1519. ev.xclient.data.l[0] = 2;
  1520. ev.xclient.data.l[1] = getUserTime();
  1521. ev.xclient.data.l[2] = 0;
  1522. ev.xclient.data.l[3] = 0;
  1523. ev.xclient.data.l[4] = 0;
  1524. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  1525. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  1526. XWindowAttributes attr;
  1527. XGetWindowAttributes (display, windowH, &attr);
  1528. if (component.isAlwaysOnTop())
  1529. XRaiseWindow (display, windowH);
  1530. XSync (display, False);
  1531. }
  1532. handleBroughtToFront();
  1533. }
  1534. void toBehind (ComponentPeer* other) override
  1535. {
  1536. if (LinuxComponentPeer* const otherPeer = dynamic_cast<LinuxComponentPeer*> (other))
  1537. {
  1538. setMinimised (false);
  1539. Window newStack[] = { otherPeer->windowH, windowH };
  1540. ScopedXLock xlock;
  1541. XRestackWindows (display, newStack, 2);
  1542. }
  1543. else
  1544. jassertfalse; // wrong type of window?
  1545. }
  1546. bool isFocused() const override
  1547. {
  1548. int revert = 0;
  1549. Window focusedWindow = 0;
  1550. ScopedXLock xlock;
  1551. XGetInputFocus (display, &focusedWindow, &revert);
  1552. return focusedWindow == windowH;
  1553. }
  1554. void grabFocus() override
  1555. {
  1556. XWindowAttributes atts;
  1557. ScopedXLock xlock;
  1558. if (windowH != 0
  1559. && XGetWindowAttributes (display, windowH, &atts)
  1560. && atts.map_state == IsViewable
  1561. && ! isFocused())
  1562. {
  1563. XSetInputFocus (display, windowH, RevertToParent, (::Time) getUserTime());
  1564. isActiveApplication = true;
  1565. }
  1566. }
  1567. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1568. void repaint (const Rectangle<int>& area) override
  1569. {
  1570. repainter->repaint (area.getIntersection (bounds.withZeroOrigin()));
  1571. }
  1572. void performAnyPendingRepaintsNow() override
  1573. {
  1574. repainter->performAnyPendingRepaintsNow();
  1575. }
  1576. void setIcon (const Image& newIcon) override
  1577. {
  1578. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  1579. HeapBlock<unsigned long> data ((size_t) dataSize);
  1580. int index = 0;
  1581. data[index++] = (unsigned long) newIcon.getWidth();
  1582. data[index++] = (unsigned long) newIcon.getHeight();
  1583. for (int y = 0; y < newIcon.getHeight(); ++y)
  1584. for (int x = 0; x < newIcon.getWidth(); ++x)
  1585. data[index++] = (unsigned long) newIcon.getPixelAt (x, y).getARGB();
  1586. ScopedXLock xlock;
  1587. xchangeProperty (windowH, Atoms::getCreating ("_NET_WM_ICON"), XA_CARDINAL, 32, data.getData(), dataSize);
  1588. deleteIconPixmaps();
  1589. XWMHints* wmHints = XGetWMHints (display, windowH);
  1590. if (wmHints == nullptr)
  1591. wmHints = XAllocWMHints();
  1592. wmHints->flags |= IconPixmapHint | IconMaskHint;
  1593. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  1594. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  1595. XSetWMHints (display, windowH, wmHints);
  1596. XFree (wmHints);
  1597. XSync (display, False);
  1598. }
  1599. void deleteIconPixmaps()
  1600. {
  1601. ScopedXLock xlock;
  1602. XWMHints* wmHints = XGetWMHints (display, windowH);
  1603. if (wmHints != nullptr)
  1604. {
  1605. if ((wmHints->flags & IconPixmapHint) != 0)
  1606. {
  1607. wmHints->flags &= ~IconPixmapHint;
  1608. XFreePixmap (display, wmHints->icon_pixmap);
  1609. }
  1610. if ((wmHints->flags & IconMaskHint) != 0)
  1611. {
  1612. wmHints->flags &= ~IconMaskHint;
  1613. XFreePixmap (display, wmHints->icon_mask);
  1614. }
  1615. XSetWMHints (display, windowH, wmHints);
  1616. XFree (wmHints);
  1617. }
  1618. }
  1619. //==============================================================================
  1620. void handleWindowMessage (XEvent& event)
  1621. {
  1622. switch (event.xany.type)
  1623. {
  1624. case KeyPressEventType: handleKeyPressEvent (event.xkey); break;
  1625. case KeyRelease: handleKeyReleaseEvent (event.xkey); break;
  1626. case ButtonPress: handleButtonPressEvent (event.xbutton); break;
  1627. case ButtonRelease: handleButtonReleaseEvent (event.xbutton); break;
  1628. case MotionNotify: handleMotionNotifyEvent (event.xmotion); break;
  1629. case EnterNotify: handleEnterNotifyEvent (event.xcrossing); break;
  1630. case LeaveNotify: handleLeaveNotifyEvent (event.xcrossing); break;
  1631. case FocusIn: handleFocusInEvent(); break;
  1632. case FocusOut: handleFocusOutEvent(); break;
  1633. case Expose: handleExposeEvent (event.xexpose); break;
  1634. case MappingNotify: handleMappingNotify (event.xmapping); break;
  1635. case ClientMessage: handleClientMessageEvent (event.xclient, event); break;
  1636. case SelectionNotify: handleDragAndDropSelection (event); break;
  1637. case ConfigureNotify: handleConfigureNotifyEvent (event.xconfigure); break;
  1638. case ReparentNotify: handleReparentNotifyEvent(); break;
  1639. case GravityNotify: handleGravityNotify(); break;
  1640. case SelectionClear: handleExternalSelectionClear(); break;
  1641. case SelectionRequest: handleExternalSelectionRequest (event); break;
  1642. case CirculateNotify:
  1643. case CreateNotify:
  1644. case DestroyNotify:
  1645. // Think we can ignore these
  1646. break;
  1647. case MapNotify:
  1648. mapped = true;
  1649. handleBroughtToFront();
  1650. break;
  1651. case UnmapNotify:
  1652. mapped = false;
  1653. break;
  1654. default:
  1655. #if JUCE_USE_XSHM
  1656. if (XSHMHelpers::isShmAvailable())
  1657. {
  1658. ScopedXLock xlock;
  1659. if (event.xany.type == XShmGetEventBase (display))
  1660. repainter->notifyPaintCompleted();
  1661. }
  1662. #endif
  1663. break;
  1664. }
  1665. }
  1666. void handleKeyPressEvent (XKeyEvent& keyEvent)
  1667. {
  1668. char utf8 [64] = { 0 };
  1669. juce_wchar unicodeChar = 0;
  1670. int keyCode = 0;
  1671. bool keyDownChange = false;
  1672. KeySym sym;
  1673. {
  1674. ScopedXLock xlock;
  1675. updateKeyStates ((int) keyEvent.keycode, true);
  1676. String oldLocale (::setlocale (LC_ALL, 0));
  1677. ::setlocale (LC_ALL, "");
  1678. XLookupString (&keyEvent, utf8, sizeof (utf8), &sym, 0);
  1679. if (oldLocale.isNotEmpty())
  1680. ::setlocale (LC_ALL, oldLocale.toRawUTF8());
  1681. unicodeChar = *CharPointer_UTF8 (utf8);
  1682. keyCode = (int) unicodeChar;
  1683. if (keyCode < 0x20)
  1684. keyCode = (int) XkbKeycodeToKeysym (display, (::KeyCode) keyEvent.keycode, 0, currentModifiers.isShiftDown() ? 1 : 0);
  1685. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  1686. }
  1687. const ModifierKeys oldMods (currentModifiers);
  1688. bool keyPressed = false;
  1689. if ((sym & 0xff00) == 0xff00 || keyCode == XK_ISO_Left_Tab)
  1690. {
  1691. switch (sym) // Translate keypad
  1692. {
  1693. case XK_KP_Add: keyCode = XK_plus; break;
  1694. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  1695. case XK_KP_Divide: keyCode = XK_slash; break;
  1696. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  1697. case XK_KP_Enter: keyCode = XK_Return; break;
  1698. case XK_KP_Insert: keyCode = XK_Insert; break;
  1699. case XK_Delete:
  1700. case XK_KP_Delete: keyCode = XK_Delete; break;
  1701. case XK_KP_Left: keyCode = XK_Left; break;
  1702. case XK_KP_Right: keyCode = XK_Right; break;
  1703. case XK_KP_Up: keyCode = XK_Up; break;
  1704. case XK_KP_Down: keyCode = XK_Down; break;
  1705. case XK_KP_Home: keyCode = XK_Home; break;
  1706. case XK_KP_End: keyCode = XK_End; break;
  1707. case XK_KP_Page_Down: keyCode = XK_Page_Down; break;
  1708. case XK_KP_Page_Up: keyCode = XK_Page_Up; break;
  1709. case XK_KP_0: keyCode = XK_0; break;
  1710. case XK_KP_1: keyCode = XK_1; break;
  1711. case XK_KP_2: keyCode = XK_2; break;
  1712. case XK_KP_3: keyCode = XK_3; break;
  1713. case XK_KP_4: keyCode = XK_4; break;
  1714. case XK_KP_5: keyCode = XK_5; break;
  1715. case XK_KP_6: keyCode = XK_6; break;
  1716. case XK_KP_7: keyCode = XK_7; break;
  1717. case XK_KP_8: keyCode = XK_8; break;
  1718. case XK_KP_9: keyCode = XK_9; break;
  1719. default: break;
  1720. }
  1721. switch (keyCode)
  1722. {
  1723. case XK_Left:
  1724. case XK_Right:
  1725. case XK_Up:
  1726. case XK_Down:
  1727. case XK_Page_Up:
  1728. case XK_Page_Down:
  1729. case XK_End:
  1730. case XK_Home:
  1731. case XK_Delete:
  1732. case XK_Insert:
  1733. keyPressed = true;
  1734. keyCode = (keyCode & 0xff) | Keys::extendedKeyModifier;
  1735. break;
  1736. case XK_Tab:
  1737. case XK_Return:
  1738. case XK_Escape:
  1739. case XK_BackSpace:
  1740. keyPressed = true;
  1741. keyCode &= 0xff;
  1742. break;
  1743. case XK_ISO_Left_Tab:
  1744. keyPressed = true;
  1745. keyCode = XK_Tab & 0xff;
  1746. break;
  1747. default:
  1748. if (sym >= XK_F1 && sym <= XK_F16)
  1749. {
  1750. keyPressed = true;
  1751. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  1752. }
  1753. break;
  1754. }
  1755. }
  1756. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  1757. keyPressed = true;
  1758. if (oldMods != currentModifiers)
  1759. handleModifierKeysChange();
  1760. if (keyDownChange)
  1761. handleKeyUpOrDown (true);
  1762. if (keyPressed)
  1763. handleKeyPress (keyCode, unicodeChar);
  1764. }
  1765. static bool isKeyReleasePartOfAutoRepeat (const XKeyEvent& keyReleaseEvent)
  1766. {
  1767. if (XPending (display))
  1768. {
  1769. XEvent e;
  1770. XPeekEvent (display, &e);
  1771. // Look for a subsequent key-down event with the same timestamp and keycode
  1772. return e.type == KeyPressEventType
  1773. && e.xkey.keycode == keyReleaseEvent.keycode
  1774. && e.xkey.time == keyReleaseEvent.time;
  1775. }
  1776. return false;
  1777. }
  1778. void handleKeyReleaseEvent (const XKeyEvent& keyEvent)
  1779. {
  1780. if (! isKeyReleasePartOfAutoRepeat (keyEvent))
  1781. {
  1782. updateKeyStates ((int) keyEvent.keycode, false);
  1783. KeySym sym;
  1784. {
  1785. ScopedXLock xlock;
  1786. sym = XkbKeycodeToKeysym (display, (::KeyCode) keyEvent.keycode, 0, 0);
  1787. }
  1788. const ModifierKeys oldMods (currentModifiers);
  1789. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  1790. if (oldMods != currentModifiers)
  1791. handleModifierKeysChange();
  1792. if (keyDownChange)
  1793. handleKeyUpOrDown (false);
  1794. }
  1795. }
  1796. template <typename EventType>
  1797. Point<float> getMousePos (const EventType& e) noexcept
  1798. {
  1799. return Point<float> ((float) e.x, (float) e.y) / currentScaleFactor;
  1800. }
  1801. void handleWheelEvent (const XButtonPressedEvent& buttonPressEvent, const float amount)
  1802. {
  1803. MouseWheelDetails wheel;
  1804. wheel.deltaX = 0.0f;
  1805. wheel.deltaY = amount;
  1806. wheel.isReversed = false;
  1807. wheel.isSmooth = false;
  1808. handleMouseWheel (0, getMousePos (buttonPressEvent), getEventTime (buttonPressEvent), wheel);
  1809. }
  1810. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent, int buttonModifierFlag)
  1811. {
  1812. currentModifiers = currentModifiers.withFlags (buttonModifierFlag);
  1813. toFront (true);
  1814. handleMouseEvent (0, getMousePos (buttonPressEvent), currentModifiers, getEventTime (buttonPressEvent));
  1815. }
  1816. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent)
  1817. {
  1818. updateKeyModifiers ((int) buttonPressEvent.state);
  1819. switch (pointerMap [buttonPressEvent.button - Button1])
  1820. {
  1821. case Keys::WheelUp: handleWheelEvent (buttonPressEvent, 50.0f / 256.0f); break;
  1822. case Keys::WheelDown: handleWheelEvent (buttonPressEvent, -50.0f / 256.0f); break;
  1823. case Keys::LeftButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::leftButtonModifier); break;
  1824. case Keys::RightButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::rightButtonModifier); break;
  1825. case Keys::MiddleButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::middleButtonModifier); break;
  1826. default: break;
  1827. }
  1828. clearLastMousePos();
  1829. }
  1830. void handleButtonReleaseEvent (const XButtonReleasedEvent& buttonRelEvent)
  1831. {
  1832. updateKeyModifiers ((int) buttonRelEvent.state);
  1833. if (parentWindow != 0)
  1834. updateWindowBounds();
  1835. switch (pointerMap [buttonRelEvent.button - Button1])
  1836. {
  1837. case Keys::LeftButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
  1838. case Keys::RightButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
  1839. case Keys::MiddleButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
  1840. default: break;
  1841. }
  1842. if (dragState.dragging)
  1843. handleExternalDragButtonReleaseEvent();
  1844. handleMouseEvent (0, getMousePos (buttonRelEvent), currentModifiers, getEventTime (buttonRelEvent));
  1845. clearLastMousePos();
  1846. }
  1847. void handleMotionNotifyEvent (const XPointerMovedEvent& movedEvent)
  1848. {
  1849. updateKeyModifiers ((int) movedEvent.state);
  1850. lastMousePos = Point<int> (movedEvent.x_root, movedEvent.y_root);
  1851. if (dragState.dragging)
  1852. handleExternalDragMotionNotify();
  1853. handleMouseEvent (0, getMousePos (movedEvent), currentModifiers, getEventTime (movedEvent));
  1854. }
  1855. void handleEnterNotifyEvent (const XEnterWindowEvent& enterEvent)
  1856. {
  1857. if (parentWindow != 0)
  1858. updateWindowBounds();
  1859. clearLastMousePos();
  1860. if (! currentModifiers.isAnyMouseButtonDown())
  1861. {
  1862. updateKeyModifiers ((int) enterEvent.state);
  1863. handleMouseEvent (0, getMousePos (enterEvent), currentModifiers, getEventTime (enterEvent));
  1864. }
  1865. }
  1866. void handleLeaveNotifyEvent (const XLeaveWindowEvent& leaveEvent)
  1867. {
  1868. // Suppress the normal leave if we've got a pointer grab, or if
  1869. // it's a bogus one caused by clicking a mouse button when running
  1870. // in a Window manager
  1871. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent.mode == NotifyNormal)
  1872. || leaveEvent.mode == NotifyUngrab)
  1873. {
  1874. updateKeyModifiers ((int) leaveEvent.state);
  1875. handleMouseEvent (0, getMousePos (leaveEvent), currentModifiers, getEventTime (leaveEvent));
  1876. }
  1877. }
  1878. void handleFocusInEvent()
  1879. {
  1880. isActiveApplication = true;
  1881. if (isFocused())
  1882. handleFocusGain();
  1883. }
  1884. void handleFocusOutEvent()
  1885. {
  1886. isActiveApplication = false;
  1887. if (! isFocused())
  1888. handleFocusLoss();
  1889. }
  1890. void handleExposeEvent (XExposeEvent& exposeEvent)
  1891. {
  1892. // Batch together all pending expose events
  1893. XEvent nextEvent;
  1894. ScopedXLock xlock;
  1895. if (exposeEvent.window != windowH)
  1896. {
  1897. Window child;
  1898. XTranslateCoordinates (display, exposeEvent.window, windowH,
  1899. exposeEvent.x, exposeEvent.y, &exposeEvent.x, &exposeEvent.y,
  1900. &child);
  1901. }
  1902. // exposeEvent is in local window local coordinates so do not convert with
  1903. // physicalToScaled, but rather use currentScaleFactor
  1904. repaint (Rectangle<int> (exposeEvent.x, exposeEvent.y,
  1905. exposeEvent.width, exposeEvent.height) / currentScaleFactor);
  1906. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  1907. {
  1908. XPeekEvent (display, &nextEvent);
  1909. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent.window)
  1910. break;
  1911. XNextEvent (display, &nextEvent);
  1912. const XExposeEvent& nextExposeEvent = (const XExposeEvent&) nextEvent.xexpose;
  1913. repaint (Rectangle<int> (nextExposeEvent.x, nextExposeEvent.y,
  1914. nextExposeEvent.width, nextExposeEvent.height) / currentScaleFactor);
  1915. }
  1916. }
  1917. void handleConfigureNotifyEvent (XConfigureEvent& confEvent)
  1918. {
  1919. updateWindowBounds();
  1920. updateBorderSize();
  1921. handleMovedOrResized();
  1922. // if the native title bar is dragged, need to tell any active menus, etc.
  1923. if ((styleFlags & windowHasTitleBar) != 0
  1924. && component.isCurrentlyBlockedByAnotherModalComponent())
  1925. {
  1926. if (Component* const currentModalComp = Component::getCurrentlyModalComponent())
  1927. currentModalComp->inputAttemptWhenModal();
  1928. }
  1929. if (confEvent.window == windowH
  1930. && confEvent.above != 0
  1931. && isFrontWindow())
  1932. {
  1933. handleBroughtToFront();
  1934. }
  1935. }
  1936. void handleReparentNotifyEvent()
  1937. {
  1938. parentWindow = 0;
  1939. Window wRoot = 0;
  1940. Window* wChild = nullptr;
  1941. unsigned int numChildren;
  1942. {
  1943. ScopedXLock xlock;
  1944. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  1945. }
  1946. if (parentWindow == windowH || parentWindow == wRoot)
  1947. parentWindow = 0;
  1948. handleGravityNotify();
  1949. }
  1950. void handleGravityNotify()
  1951. {
  1952. updateWindowBounds();
  1953. updateBorderSize();
  1954. handleMovedOrResized();
  1955. }
  1956. void handleMappingNotify (XMappingEvent& mappingEvent)
  1957. {
  1958. if (mappingEvent.request != MappingPointer)
  1959. {
  1960. // Deal with modifier/keyboard mapping
  1961. ScopedXLock xlock;
  1962. XRefreshKeyboardMapping (&mappingEvent);
  1963. updateModifierMappings();
  1964. }
  1965. }
  1966. void handleClientMessageEvent (XClientMessageEvent& clientMsg, XEvent& event)
  1967. {
  1968. const Atoms& atoms = Atoms::get();
  1969. if (clientMsg.message_type == atoms.protocols && clientMsg.format == 32)
  1970. {
  1971. const Atom atom = (Atom) clientMsg.data.l[0];
  1972. if (atom == atoms.protocolList [Atoms::PING])
  1973. {
  1974. Window root = RootWindow (display, DefaultScreen (display));
  1975. clientMsg.window = root;
  1976. XSendEvent (display, root, False, NoEventMask, &event);
  1977. XFlush (display);
  1978. }
  1979. else if (atom == atoms.protocolList [Atoms::TAKE_FOCUS])
  1980. {
  1981. if ((getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0)
  1982. {
  1983. XWindowAttributes atts;
  1984. ScopedXLock xlock;
  1985. if (clientMsg.window != 0
  1986. && XGetWindowAttributes (display, clientMsg.window, &atts))
  1987. {
  1988. if (atts.map_state == IsViewable)
  1989. XSetInputFocus (display, clientMsg.window, RevertToParent, (::Time) clientMsg.data.l[1]);
  1990. }
  1991. }
  1992. }
  1993. else if (atom == atoms.protocolList [Atoms::DELETE_WINDOW])
  1994. {
  1995. handleUserClosingWindow();
  1996. }
  1997. }
  1998. else if (clientMsg.message_type == atoms.XdndEnter)
  1999. {
  2000. handleDragAndDropEnter (clientMsg);
  2001. }
  2002. else if (clientMsg.message_type == atoms.XdndLeave)
  2003. {
  2004. handleDragExit (dragInfo);
  2005. resetDragAndDrop();
  2006. }
  2007. else if (clientMsg.message_type == atoms.XdndPosition)
  2008. {
  2009. handleDragAndDropPosition (clientMsg);
  2010. }
  2011. else if (clientMsg.message_type == atoms.XdndDrop)
  2012. {
  2013. handleDragAndDropDrop (clientMsg);
  2014. }
  2015. else if (clientMsg.message_type == atoms.XdndStatus)
  2016. {
  2017. handleExternalDragAndDropStatus (clientMsg);
  2018. }
  2019. else if (clientMsg.message_type == atoms.XdndFinished)
  2020. {
  2021. externalResetDragAndDrop();
  2022. }
  2023. }
  2024. bool externalDragTextInit (const String& text)
  2025. {
  2026. if (dragState.dragging)
  2027. return false;
  2028. return externalDragInit (true, text);
  2029. }
  2030. bool externalDragFileInit (const StringArray& files, bool /*canMoveFiles*/)
  2031. {
  2032. if (dragState.dragging)
  2033. return false;
  2034. StringArray uriList;
  2035. for (int i = 0; i < files.size(); ++i)
  2036. {
  2037. const String& f = files[i];
  2038. if (f.matchesWildcard ("?*://*", false))
  2039. uriList.add (f);
  2040. else
  2041. uriList.add ("file://" + f);
  2042. }
  2043. return externalDragInit (false, uriList.joinIntoString ("\r\n"));
  2044. }
  2045. //==============================================================================
  2046. void showMouseCursor (Cursor cursor) noexcept
  2047. {
  2048. ScopedXLock xlock;
  2049. XDefineCursor (display, windowH, cursor);
  2050. }
  2051. //==============================================================================
  2052. double getCurrentScale() noexcept
  2053. {
  2054. return currentScaleFactor;
  2055. }
  2056. //==============================================================================
  2057. bool dontRepaint;
  2058. static ModifierKeys currentModifiers;
  2059. static bool isActiveApplication;
  2060. private:
  2061. //==============================================================================
  2062. class LinuxRepaintManager : public Timer
  2063. {
  2064. public:
  2065. LinuxRepaintManager (LinuxComponentPeer& p)
  2066. : peer (p), lastTimeImageUsed (0)
  2067. {
  2068. #if JUCE_USE_XSHM
  2069. shmPaintsPending = 0;
  2070. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  2071. if (useARGBImagesForRendering)
  2072. {
  2073. ScopedXLock xlock;
  2074. XShmSegmentInfo segmentinfo;
  2075. XImage* const testImage
  2076. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  2077. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  2078. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  2079. XDestroyImage (testImage);
  2080. }
  2081. #endif
  2082. }
  2083. void timerCallback() override
  2084. {
  2085. #if JUCE_USE_XSHM
  2086. if (shmPaintsPending != 0)
  2087. return;
  2088. #endif
  2089. if (! regionsNeedingRepaint.isEmpty())
  2090. {
  2091. stopTimer();
  2092. performAnyPendingRepaintsNow();
  2093. }
  2094. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  2095. {
  2096. stopTimer();
  2097. image = Image::null;
  2098. }
  2099. }
  2100. void repaint (const Rectangle<int>& area)
  2101. {
  2102. if (! isTimerRunning())
  2103. startTimer (repaintTimerPeriod);
  2104. regionsNeedingRepaint.add (area * peer.currentScaleFactor);
  2105. }
  2106. void performAnyPendingRepaintsNow()
  2107. {
  2108. #if JUCE_USE_XSHM
  2109. if (shmPaintsPending != 0)
  2110. {
  2111. startTimer (repaintTimerPeriod);
  2112. return;
  2113. }
  2114. #endif
  2115. RectangleList<int> originalRepaintRegion (regionsNeedingRepaint);
  2116. regionsNeedingRepaint.clear();
  2117. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  2118. if (! totalArea.isEmpty())
  2119. {
  2120. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  2121. || image.getHeight() < totalArea.getHeight())
  2122. {
  2123. #if JUCE_USE_XSHM
  2124. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  2125. : Image::RGB,
  2126. #else
  2127. image = Image (new XBitmapImage (Image::RGB,
  2128. #endif
  2129. (totalArea.getWidth() + 31) & ~31,
  2130. (totalArea.getHeight() + 31) & ~31,
  2131. false, (unsigned int) peer.depth, peer.visual));
  2132. }
  2133. startTimer (repaintTimerPeriod);
  2134. RectangleList<int> adjustedList (originalRepaintRegion);
  2135. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  2136. if (peer.depth == 32)
  2137. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  2138. image.clear (*i - totalArea.getPosition());
  2139. {
  2140. ScopedPointer<LowLevelGraphicsContext> context (peer.getComponent().getLookAndFeel()
  2141. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList));
  2142. context->addTransform (AffineTransform::scale ((float) peer.currentScaleFactor));
  2143. peer.handlePaint (*context);
  2144. }
  2145. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  2146. {
  2147. XBitmapImage* xbitmap = static_cast<XBitmapImage*> (image.getPixelData());
  2148. #if JUCE_USE_XSHM
  2149. if (xbitmap->isUsingXShm())
  2150. ++shmPaintsPending;
  2151. #endif
  2152. xbitmap->blitToWindow (peer.windowH,
  2153. i->getX(), i->getY(),
  2154. (unsigned int) i->getWidth(),
  2155. (unsigned int) i->getHeight(),
  2156. i->getX() - totalArea.getX(), i->getY() - totalArea.getY());
  2157. }
  2158. }
  2159. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  2160. startTimer (repaintTimerPeriod);
  2161. }
  2162. #if JUCE_USE_XSHM
  2163. void notifyPaintCompleted() noexcept { --shmPaintsPending; }
  2164. #endif
  2165. private:
  2166. enum { repaintTimerPeriod = 1000 / 100 };
  2167. LinuxComponentPeer& peer;
  2168. Image image;
  2169. uint32 lastTimeImageUsed;
  2170. RectangleList<int> regionsNeedingRepaint;
  2171. #if JUCE_USE_XSHM
  2172. bool useARGBImagesForRendering;
  2173. int shmPaintsPending;
  2174. #endif
  2175. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  2176. };
  2177. ScopedPointer<LinuxRepaintManager> repainter;
  2178. friend class LinuxRepaintManager;
  2179. Window windowH, parentWindow;
  2180. Rectangle<int> bounds;
  2181. Image taskbarImage;
  2182. bool fullScreen, mapped;
  2183. Visual* visual;
  2184. int depth;
  2185. BorderSize<int> windowBorder;
  2186. bool isAlwaysOnTop;
  2187. double currentScaleFactor;
  2188. enum { KeyPressEventType = 2 };
  2189. struct MotifWmHints
  2190. {
  2191. unsigned long flags;
  2192. unsigned long functions;
  2193. unsigned long decorations;
  2194. long input_mode;
  2195. unsigned long status;
  2196. };
  2197. static void updateKeyStates (const int keycode, const bool press) noexcept
  2198. {
  2199. const int keybyte = keycode >> 3;
  2200. const int keybit = (1 << (keycode & 7));
  2201. if (press)
  2202. Keys::keyStates [keybyte] |= keybit;
  2203. else
  2204. Keys::keyStates [keybyte] &= ~keybit;
  2205. }
  2206. static void updateKeyModifiers (const int status) noexcept
  2207. {
  2208. int keyMods = 0;
  2209. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  2210. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  2211. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  2212. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  2213. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  2214. Keys::capsLock = ((status & LockMask) != 0);
  2215. }
  2216. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) noexcept
  2217. {
  2218. int modifier = 0;
  2219. bool isModifier = true;
  2220. switch (sym)
  2221. {
  2222. case XK_Shift_L:
  2223. case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
  2224. case XK_Control_L:
  2225. case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
  2226. case XK_Alt_L:
  2227. case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
  2228. case XK_Num_Lock:
  2229. if (press)
  2230. Keys::numLock = ! Keys::numLock;
  2231. break;
  2232. case XK_Caps_Lock:
  2233. if (press)
  2234. Keys::capsLock = ! Keys::capsLock;
  2235. break;
  2236. case XK_Scroll_Lock:
  2237. break;
  2238. default:
  2239. isModifier = false;
  2240. break;
  2241. }
  2242. currentModifiers = press ? currentModifiers.withFlags (modifier)
  2243. : currentModifiers.withoutFlags (modifier);
  2244. return isModifier;
  2245. }
  2246. // Alt and Num lock are not defined by standard X
  2247. // modifier constants: check what they're mapped to
  2248. static void updateModifierMappings() noexcept
  2249. {
  2250. ScopedXLock xlock;
  2251. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  2252. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  2253. Keys::AltMask = 0;
  2254. Keys::NumLockMask = 0;
  2255. if (XModifierKeymap* const mapping = XGetModifierMapping (display))
  2256. {
  2257. for (int i = 0; i < 8; i++)
  2258. {
  2259. if (mapping->modifiermap [i << 1] == altLeftCode)
  2260. Keys::AltMask = 1 << i;
  2261. else if (mapping->modifiermap [i << 1] == numLockCode)
  2262. Keys::NumLockMask = 1 << i;
  2263. }
  2264. XFreeModifiermap (mapping);
  2265. }
  2266. }
  2267. //==============================================================================
  2268. static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
  2269. {
  2270. XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  2271. }
  2272. void removeWindowDecorations (Window wndH)
  2273. {
  2274. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  2275. if (hints != None)
  2276. {
  2277. MotifWmHints motifHints;
  2278. zerostruct (motifHints);
  2279. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  2280. motifHints.decorations = 0;
  2281. ScopedXLock xlock;
  2282. xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
  2283. }
  2284. hints = Atoms::getIfExists ("_WIN_HINTS");
  2285. if (hints != None)
  2286. {
  2287. long gnomeHints = 0;
  2288. ScopedXLock xlock;
  2289. xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
  2290. }
  2291. hints = Atoms::getIfExists ("KWM_WIN_DECORATION");
  2292. if (hints != None)
  2293. {
  2294. long kwmHints = 2; /*KDE_tinyDecoration*/
  2295. ScopedXLock xlock;
  2296. xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
  2297. }
  2298. }
  2299. void addWindowButtons (Window wndH)
  2300. {
  2301. ScopedXLock xlock;
  2302. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  2303. if (hints != None)
  2304. {
  2305. MotifWmHints motifHints;
  2306. zerostruct (motifHints);
  2307. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  2308. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  2309. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  2310. if ((styleFlags & windowHasCloseButton) != 0)
  2311. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  2312. if ((styleFlags & windowHasMinimiseButton) != 0)
  2313. {
  2314. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  2315. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  2316. }
  2317. if ((styleFlags & windowHasMaximiseButton) != 0)
  2318. {
  2319. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  2320. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  2321. }
  2322. if ((styleFlags & windowIsResizable) != 0)
  2323. {
  2324. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  2325. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  2326. }
  2327. xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
  2328. }
  2329. hints = Atoms::getIfExists ("_NET_WM_ALLOWED_ACTIONS");
  2330. if (hints != None)
  2331. {
  2332. Atom netHints [6];
  2333. int num = 0;
  2334. if ((styleFlags & windowIsResizable) != 0)
  2335. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_RESIZE");
  2336. if ((styleFlags & windowHasMaximiseButton) != 0)
  2337. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_FULLSCREEN");
  2338. if ((styleFlags & windowHasMinimiseButton) != 0)
  2339. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_MINIMIZE");
  2340. if ((styleFlags & windowHasCloseButton) != 0)
  2341. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_CLOSE");
  2342. xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
  2343. }
  2344. }
  2345. void setWindowType()
  2346. {
  2347. Atom netHints [2];
  2348. if ((styleFlags & windowIsTemporary) != 0
  2349. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  2350. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_COMBO");
  2351. else
  2352. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_NORMAL");
  2353. netHints[1] = Atoms::getIfExists ("_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  2354. xchangeProperty (windowH, Atoms::get().windowType, XA_ATOM, 32, &netHints, 2);
  2355. int numHints = 0;
  2356. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  2357. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_SKIP_TASKBAR");
  2358. if (component.isAlwaysOnTop())
  2359. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_ABOVE");
  2360. if (numHints > 0)
  2361. xchangeProperty (windowH, Atoms::get().windowState, XA_ATOM, 32, &netHints, numHints);
  2362. }
  2363. void createWindow (Window parentToAddTo)
  2364. {
  2365. ScopedXLock xlock;
  2366. resetDragAndDrop();
  2367. // Get defaults for various properties
  2368. const int screen = DefaultScreen (display);
  2369. Window root = RootWindow (display, screen);
  2370. parentWindow = parentToAddTo;
  2371. // Try to obtain a 32-bit visual or fallback to 24 or 16
  2372. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  2373. if (visual == nullptr)
  2374. {
  2375. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  2376. Process::terminate();
  2377. }
  2378. // Create and install a colormap suitable fr our visual
  2379. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  2380. XInstallColormap (display, colormap);
  2381. // Set up the window attributes
  2382. XSetWindowAttributes swa;
  2383. swa.border_pixel = 0;
  2384. swa.background_pixmap = None;
  2385. swa.colormap = colormap;
  2386. swa.override_redirect = (component.isAlwaysOnTop() && (styleFlags & windowIsTemporary) != 0) ? True : False;
  2387. swa.event_mask = getAllEventsMask();
  2388. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  2389. 0, 0, 1, 1,
  2390. 0, depth, InputOutput, visual,
  2391. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  2392. &swa);
  2393. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  2394. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  2395. GrabModeAsync, GrabModeAsync, None, None);
  2396. // Set the window context to identify the window handle object
  2397. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  2398. {
  2399. // Failed
  2400. jassertfalse;
  2401. Logger::outputDebugString ("Failed to create context information for window.\n");
  2402. XDestroyWindow (display, windowH);
  2403. windowH = 0;
  2404. return;
  2405. }
  2406. // Set window manager hints
  2407. XWMHints* wmHints = XAllocWMHints();
  2408. wmHints->flags = InputHint | StateHint;
  2409. wmHints->input = True; // Locally active input model
  2410. wmHints->initial_state = NormalState;
  2411. XSetWMHints (display, windowH, wmHints);
  2412. XFree (wmHints);
  2413. // Set the window type
  2414. setWindowType();
  2415. // Define decoration
  2416. if ((styleFlags & windowHasTitleBar) == 0)
  2417. removeWindowDecorations (windowH);
  2418. else
  2419. addWindowButtons (windowH);
  2420. setTitle (component.getName());
  2421. const Atoms& atoms = Atoms::get();
  2422. // Associate the PID, allowing to be shut down when something goes wrong
  2423. unsigned long pid = (unsigned long) getpid();
  2424. xchangeProperty (windowH, atoms.pid, XA_CARDINAL, 32, &pid, 1);
  2425. // Set window manager protocols
  2426. xchangeProperty (windowH, atoms.protocols, XA_ATOM, 32, atoms.protocolList, 2);
  2427. // Set drag and drop flags
  2428. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32, atoms.allowedMimeTypes, numElementsInArray (atoms.allowedMimeTypes));
  2429. xchangeProperty (windowH, atoms.XdndActionList, XA_ATOM, 32, atoms.allowedActions, numElementsInArray (atoms.allowedActions));
  2430. xchangeProperty (windowH, atoms.XdndActionDescription, XA_STRING, 8, "", 0);
  2431. xchangeProperty (windowH, atoms.XdndAware, XA_ATOM, 32, &Atoms::DndVersion, 1);
  2432. initialisePointerMap();
  2433. updateModifierMappings();
  2434. }
  2435. void destroyWindow()
  2436. {
  2437. ScopedXLock xlock;
  2438. XPointer handlePointer;
  2439. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  2440. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  2441. XDestroyWindow (display, windowH);
  2442. // Wait for it to complete and then remove any events for this
  2443. // window from the event queue.
  2444. XSync (display, false);
  2445. XEvent event;
  2446. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  2447. {}
  2448. }
  2449. static int getAllEventsMask() noexcept
  2450. {
  2451. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  2452. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  2453. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  2454. }
  2455. template <typename EventType>
  2456. static int64 getEventTime (const EventType& t)
  2457. {
  2458. return getEventTime (t.time);
  2459. }
  2460. static int64 getEventTime (::Time t)
  2461. {
  2462. static int64 eventTimeOffset = 0x12345678;
  2463. const int64 thisMessageTime = (int64) t;
  2464. if (eventTimeOffset == 0x12345678)
  2465. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  2466. return eventTimeOffset + thisMessageTime;
  2467. }
  2468. long getUserTime() const
  2469. {
  2470. GetXProperty prop (windowH, Atoms::get().userTime, 0, 65536, false, XA_CARDINAL);
  2471. return prop.success ? *(long*) prop.data : 0;
  2472. }
  2473. void updateBorderSize()
  2474. {
  2475. if ((styleFlags & windowHasTitleBar) == 0)
  2476. {
  2477. windowBorder = BorderSize<int> (0);
  2478. }
  2479. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  2480. {
  2481. ScopedXLock xlock;
  2482. Atom hints = Atoms::getIfExists ("_NET_FRAME_EXTENTS");
  2483. if (hints != None)
  2484. {
  2485. GetXProperty prop (windowH, hints, 0, 4, false, XA_CARDINAL);
  2486. if (prop.success && prop.actualFormat == 32)
  2487. {
  2488. const unsigned long* const sizes = (const unsigned long*) prop.data;
  2489. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  2490. (int) sizes[3], (int) sizes[1]);
  2491. }
  2492. }
  2493. }
  2494. }
  2495. void updateWindowBounds()
  2496. {
  2497. jassert (windowH != 0);
  2498. if (windowH != 0)
  2499. {
  2500. Window root, child;
  2501. int wx = 0, wy = 0;
  2502. unsigned int ww = 0, wh = 0, bw, bitDepth;
  2503. ScopedXLock xlock;
  2504. if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &bitDepth))
  2505. if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  2506. wx = wy = 0;
  2507. Rectangle<int> physicalBounds (wx, wy, (int) ww, (int) wh);
  2508. currentScaleFactor =
  2509. DisplayGeometry::getInstance().findDisplayForRect (physicalBounds, false).scale;
  2510. bounds = DisplayGeometry::physicalToScaled (physicalBounds);
  2511. }
  2512. }
  2513. //==============================================================================
  2514. struct DragState
  2515. {
  2516. DragState() noexcept
  2517. : isText (false), dragging (false), expectingStatus (false),
  2518. canDrop (false), targetWindow (None), xdndVersion (-1)
  2519. {
  2520. }
  2521. bool isText;
  2522. bool dragging; // currently performing outgoing external dnd as Xdnd source, have grabbed mouse
  2523. bool expectingStatus; // XdndPosition sent, waiting for XdndStatus
  2524. bool canDrop; // target window signals it will accept the drop
  2525. Window targetWindow; // potential drop target
  2526. int xdndVersion; // negotiated version with target
  2527. Rectangle<int> silentRect;
  2528. String textOrFiles;
  2529. const Atom* getMimeTypes() const noexcept { return isText ? Atoms::get().externalAllowedTextMimeTypes
  2530. : Atoms::get().externalAllowedFileMimeTypes; }
  2531. int getNumMimeTypes() const noexcept { return isText ? numElementsInArray (Atoms::get().externalAllowedTextMimeTypes)
  2532. : numElementsInArray (Atoms::get().externalAllowedFileMimeTypes); }
  2533. bool matchesTarget (Atom targetType) const
  2534. {
  2535. for (int i = getNumMimeTypes(); --i >= 0;)
  2536. if (getMimeTypes()[i] == targetType)
  2537. return true;
  2538. return false;
  2539. }
  2540. };
  2541. //==============================================================================
  2542. void resetDragAndDrop()
  2543. {
  2544. dragInfo.clear();
  2545. dragInfo.position = Point<int> (-1, -1);
  2546. dragAndDropCurrentMimeType = 0;
  2547. dragAndDropSourceWindow = 0;
  2548. srcMimeTypeAtomList.clear();
  2549. finishAfterDropDataReceived = false;
  2550. }
  2551. void resetExternalDragState()
  2552. {
  2553. dragState = DragState();
  2554. }
  2555. void sendDragAndDropMessage (XClientMessageEvent& msg)
  2556. {
  2557. msg.type = ClientMessage;
  2558. msg.display = display;
  2559. msg.window = dragAndDropSourceWindow;
  2560. msg.format = 32;
  2561. msg.data.l[0] = (long) windowH;
  2562. ScopedXLock xlock;
  2563. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  2564. }
  2565. bool sendExternalDragAndDropMessage (XClientMessageEvent& msg, const Window targetWindow)
  2566. {
  2567. msg.type = ClientMessage;
  2568. msg.display = display;
  2569. msg.window = targetWindow;
  2570. msg.format = 32;
  2571. msg.data.l[0] = (long) windowH;
  2572. ScopedXLock xlock;
  2573. return XSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
  2574. }
  2575. void sendExternalDragAndDropDrop (const Window targetWindow)
  2576. {
  2577. XClientMessageEvent msg;
  2578. zerostruct (msg);
  2579. msg.message_type = Atoms::get().XdndDrop;
  2580. msg.data.l[2] = CurrentTime;
  2581. sendExternalDragAndDropMessage (msg, targetWindow);
  2582. }
  2583. void sendExternalDragAndDropEnter (const Window targetWindow)
  2584. {
  2585. XClientMessageEvent msg;
  2586. zerostruct (msg);
  2587. msg.message_type = Atoms::get().XdndEnter;
  2588. const Atom* mimeTypes = dragState.getMimeTypes();
  2589. const int numMimeTypes = dragState.getNumMimeTypes();
  2590. msg.data.l[1] = (dragState.xdndVersion << 24) | (numMimeTypes > 3);
  2591. msg.data.l[2] = numMimeTypes > 0 ? (long) mimeTypes[0] : 0;
  2592. msg.data.l[3] = numMimeTypes > 1 ? (long) mimeTypes[1] : 0;
  2593. msg.data.l[4] = numMimeTypes > 2 ? (long) mimeTypes[2] : 0;
  2594. sendExternalDragAndDropMessage (msg, targetWindow);
  2595. }
  2596. void sendExternalDragAndDropPosition (const Window targetWindow)
  2597. {
  2598. XClientMessageEvent msg;
  2599. zerostruct (msg);
  2600. msg.message_type = Atoms::get().XdndPosition;
  2601. Point<int> mousePos (Desktop::getInstance().getMousePosition());
  2602. if (dragState.silentRect.contains (mousePos)) // we've been asked to keep silent
  2603. return;
  2604. mousePos = DisplayGeometry::scaledToPhysical (mousePos);
  2605. msg.data.l[1] = 0;
  2606. msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
  2607. msg.data.l[3] = CurrentTime;
  2608. msg.data.l[4] = (long) Atoms::get().XdndActionCopy; // this is all JUCE currently supports
  2609. dragState.expectingStatus = sendExternalDragAndDropMessage (msg, targetWindow);
  2610. }
  2611. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  2612. {
  2613. XClientMessageEvent msg;
  2614. zerostruct (msg);
  2615. msg.message_type = Atoms::get().XdndStatus;
  2616. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  2617. msg.data.l[4] = (long) dropAction;
  2618. sendDragAndDropMessage (msg);
  2619. }
  2620. void sendExternalDragAndDropLeave (const Window targetWindow)
  2621. {
  2622. XClientMessageEvent msg;
  2623. zerostruct (msg);
  2624. msg.message_type = Atoms::get().XdndLeave;
  2625. sendExternalDragAndDropMessage (msg, targetWindow);
  2626. }
  2627. void sendDragAndDropFinish()
  2628. {
  2629. XClientMessageEvent msg;
  2630. zerostruct (msg);
  2631. msg.message_type = Atoms::get().XdndFinished;
  2632. sendDragAndDropMessage (msg);
  2633. }
  2634. void handleExternalSelectionClear()
  2635. {
  2636. if (dragState.dragging)
  2637. externalResetDragAndDrop();
  2638. }
  2639. void handleExternalSelectionRequest (const XEvent& evt)
  2640. {
  2641. Atom targetType = evt.xselectionrequest.target;
  2642. XEvent s;
  2643. s.xselection.type = SelectionNotify;
  2644. s.xselection.requestor = evt.xselectionrequest.requestor;
  2645. s.xselection.selection = evt.xselectionrequest.selection;
  2646. s.xselection.target = targetType;
  2647. s.xselection.property = None;
  2648. s.xselection.time = evt.xselectionrequest.time;
  2649. if (dragState.matchesTarget (targetType))
  2650. {
  2651. s.xselection.property = evt.xselectionrequest.property;
  2652. xchangeProperty (evt.xselectionrequest.requestor,
  2653. evt.xselectionrequest.property,
  2654. targetType, 8,
  2655. dragState.textOrFiles.toRawUTF8(),
  2656. (int) dragState.textOrFiles.getNumBytesAsUTF8());
  2657. }
  2658. XSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
  2659. }
  2660. void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
  2661. {
  2662. if (dragState.expectingStatus)
  2663. {
  2664. dragState.expectingStatus = false;
  2665. dragState.canDrop = false;
  2666. dragState.silentRect = Rectangle<int>();
  2667. if ((clientMsg.data.l[1] & 1) != 0
  2668. && ((Atom) clientMsg.data.l[4] == Atoms::get().XdndActionCopy
  2669. || (Atom) clientMsg.data.l[4] == Atoms::get().XdndActionPrivate))
  2670. {
  2671. if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
  2672. dragState.silentRect.setBounds ((int) clientMsg.data.l[2] >> 16,
  2673. (int) clientMsg.data.l[2] & 0xffff,
  2674. (int) clientMsg.data.l[3] >> 16,
  2675. (int) clientMsg.data.l[3] & 0xffff);
  2676. dragState.canDrop = true;
  2677. }
  2678. }
  2679. }
  2680. void handleExternalDragButtonReleaseEvent()
  2681. {
  2682. if (dragState.dragging)
  2683. XUngrabPointer (display, CurrentTime);
  2684. if (dragState.canDrop)
  2685. {
  2686. sendExternalDragAndDropDrop (dragState.targetWindow);
  2687. }
  2688. else
  2689. {
  2690. sendExternalDragAndDropLeave (dragState.targetWindow);
  2691. externalResetDragAndDrop();
  2692. }
  2693. }
  2694. void handleExternalDragMotionNotify()
  2695. {
  2696. Window targetWindow = externalFindDragTargetWindow (RootWindow (display, DefaultScreen (display)));
  2697. if (dragState.targetWindow != targetWindow)
  2698. {
  2699. if (dragState.targetWindow != None)
  2700. sendExternalDragAndDropLeave (dragState.targetWindow);
  2701. dragState.canDrop = false;
  2702. dragState.silentRect = Rectangle<int>();
  2703. if (targetWindow == None)
  2704. return;
  2705. GetXProperty prop (targetWindow, Atoms::get().XdndAware,
  2706. 0, 2, false, AnyPropertyType);
  2707. if (prop.success
  2708. && prop.data != None
  2709. && prop.actualFormat == 32
  2710. && prop.numItems == 1)
  2711. {
  2712. dragState.xdndVersion = jmin ((int) prop.data[0], (int) Atoms::DndVersion);
  2713. }
  2714. else
  2715. {
  2716. dragState.xdndVersion = -1;
  2717. return;
  2718. }
  2719. sendExternalDragAndDropEnter (targetWindow);
  2720. dragState.targetWindow = targetWindow;
  2721. }
  2722. if (! dragState.expectingStatus)
  2723. sendExternalDragAndDropPosition (targetWindow);
  2724. }
  2725. void handleDragAndDropPosition (const XClientMessageEvent& clientMsg)
  2726. {
  2727. if (dragAndDropSourceWindow == 0)
  2728. return;
  2729. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2730. Point<int> dropPos ((int) clientMsg.data.l[2] >> 16,
  2731. (int) clientMsg.data.l[2] & 0xffff);
  2732. dropPos -= bounds.getPosition();
  2733. const Atoms& atoms = Atoms::get();
  2734. Atom targetAction = atoms.XdndActionCopy;
  2735. for (int i = numElementsInArray (atoms.allowedActions); --i >= 0;)
  2736. {
  2737. if ((Atom) clientMsg.data.l[4] == atoms.allowedActions[i])
  2738. {
  2739. targetAction = atoms.allowedActions[i];
  2740. break;
  2741. }
  2742. }
  2743. sendDragAndDropStatus (true, targetAction);
  2744. if (dragInfo.position != dropPos)
  2745. {
  2746. dragInfo.position = dropPos;
  2747. if (dragInfo.isEmpty())
  2748. updateDraggedFileList (clientMsg);
  2749. if (! dragInfo.isEmpty())
  2750. handleDragMove (dragInfo);
  2751. }
  2752. }
  2753. void handleDragAndDropDrop (const XClientMessageEvent& clientMsg)
  2754. {
  2755. if (dragInfo.isEmpty())
  2756. {
  2757. // no data, transaction finished in handleDragAndDropSelection()
  2758. finishAfterDropDataReceived = true;
  2759. updateDraggedFileList (clientMsg);
  2760. }
  2761. else
  2762. {
  2763. handleDragAndDropDataReceived(); // data was already received
  2764. }
  2765. }
  2766. void handleDragAndDropDataReceived()
  2767. {
  2768. DragInfo dragInfoCopy (dragInfo);
  2769. sendDragAndDropFinish();
  2770. resetDragAndDrop();
  2771. if (! dragInfoCopy.isEmpty())
  2772. handleDragDrop (dragInfoCopy);
  2773. }
  2774. void handleDragAndDropEnter (const XClientMessageEvent& clientMsg)
  2775. {
  2776. dragInfo.clear();
  2777. srcMimeTypeAtomList.clear();
  2778. dragAndDropCurrentMimeType = 0;
  2779. const unsigned long dndCurrentVersion = static_cast<unsigned long> (clientMsg.data.l[1] & 0xff000000) >> 24;
  2780. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  2781. {
  2782. dragAndDropSourceWindow = 0;
  2783. return;
  2784. }
  2785. dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
  2786. if ((clientMsg.data.l[1] & 1) != 0)
  2787. {
  2788. ScopedXLock xlock;
  2789. GetXProperty prop (dragAndDropSourceWindow, Atoms::get().XdndTypeList, 0, 0x8000000L, false, XA_ATOM);
  2790. if (prop.success
  2791. && prop.actualType == XA_ATOM
  2792. && prop.actualFormat == 32
  2793. && prop.numItems != 0)
  2794. {
  2795. const unsigned long* const types = (const unsigned long*) prop.data;
  2796. for (unsigned long i = 0; i < prop.numItems; ++i)
  2797. if (types[i] != None)
  2798. srcMimeTypeAtomList.add (types[i]);
  2799. }
  2800. }
  2801. if (srcMimeTypeAtomList.size() == 0)
  2802. {
  2803. for (int i = 2; i < 5; ++i)
  2804. if (clientMsg.data.l[i] != None)
  2805. srcMimeTypeAtomList.add ((unsigned long) clientMsg.data.l[i]);
  2806. if (srcMimeTypeAtomList.size() == 0)
  2807. {
  2808. dragAndDropSourceWindow = 0;
  2809. return;
  2810. }
  2811. }
  2812. const Atoms& atoms = Atoms::get();
  2813. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  2814. for (int j = 0; j < numElementsInArray (atoms.allowedMimeTypes); ++j)
  2815. if (srcMimeTypeAtomList[i] == atoms.allowedMimeTypes[j])
  2816. dragAndDropCurrentMimeType = atoms.allowedMimeTypes[j];
  2817. handleDragAndDropPosition (clientMsg);
  2818. }
  2819. void handleDragAndDropSelection (const XEvent& evt)
  2820. {
  2821. dragInfo.clear();
  2822. if (evt.xselection.property != None)
  2823. {
  2824. StringArray lines;
  2825. {
  2826. MemoryBlock dropData;
  2827. for (;;)
  2828. {
  2829. GetXProperty prop (evt.xany.window, evt.xselection.property,
  2830. dropData.getSize() / 4, 65536, false, AnyPropertyType);
  2831. if (! prop.success)
  2832. break;
  2833. dropData.append (prop.data, prop.numItems * (size_t) prop.actualFormat / 8);
  2834. if (prop.bytesLeft <= 0)
  2835. break;
  2836. }
  2837. lines.addLines (dropData.toString());
  2838. }
  2839. if (Atoms::isMimeTypeFile (dragAndDropCurrentMimeType))
  2840. {
  2841. for (int i = 0; i < lines.size(); ++i)
  2842. dragInfo.files.add (URL::removeEscapeChars (lines[i].replace ("file://", String::empty, true)));
  2843. dragInfo.files.trim();
  2844. dragInfo.files.removeEmptyStrings();
  2845. }
  2846. else
  2847. {
  2848. dragInfo.text = lines.joinIntoString ("\n");
  2849. }
  2850. if (finishAfterDropDataReceived)
  2851. handleDragAndDropDataReceived();
  2852. }
  2853. }
  2854. void updateDraggedFileList (const XClientMessageEvent& clientMsg)
  2855. {
  2856. jassert (dragInfo.isEmpty());
  2857. if (dragAndDropSourceWindow != None
  2858. && dragAndDropCurrentMimeType != None)
  2859. {
  2860. ScopedXLock xlock;
  2861. XConvertSelection (display,
  2862. Atoms::get().XdndSelection,
  2863. dragAndDropCurrentMimeType,
  2864. Atoms::getCreating ("JXSelectionWindowProperty"),
  2865. windowH,
  2866. (::Time) clientMsg.data.l[2]);
  2867. }
  2868. }
  2869. static bool isWindowDnDAware (Window w)
  2870. {
  2871. int numProperties = 0;
  2872. Atom* const atoms = XListProperties (display, w, &numProperties);
  2873. bool dndAwarePropFound = false;
  2874. for (int i = 0; i < numProperties; ++i)
  2875. if (atoms[i] == Atoms::get().XdndAware)
  2876. dndAwarePropFound = true;
  2877. if (atoms != nullptr)
  2878. XFree (atoms);
  2879. return dndAwarePropFound;
  2880. }
  2881. Window externalFindDragTargetWindow (Window targetWindow)
  2882. {
  2883. if (targetWindow == None)
  2884. return None;
  2885. if (isWindowDnDAware (targetWindow))
  2886. return targetWindow;
  2887. Window child, phonyWin;
  2888. int phony;
  2889. unsigned int uphony;
  2890. XQueryPointer (display, targetWindow, &phonyWin, &child,
  2891. &phony, &phony, &phony, &phony, &uphony);
  2892. return externalFindDragTargetWindow (child);
  2893. }
  2894. bool externalDragInit (bool isText, const String& textOrFiles)
  2895. {
  2896. ScopedXLock xlock;
  2897. resetExternalDragState();
  2898. dragState.isText = isText;
  2899. dragState.textOrFiles = textOrFiles;
  2900. dragState.targetWindow = windowH;
  2901. const int pointerGrabMask = Button1MotionMask | ButtonReleaseMask;
  2902. if (XGrabPointer (display, windowH, True, pointerGrabMask,
  2903. GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
  2904. {
  2905. // No other method of changing the pointer seems to work, this call is needed from this very context
  2906. XChangeActivePointerGrab (display, pointerGrabMask, (Cursor) createDraggingHandCursor(), CurrentTime);
  2907. const Atoms& atoms = Atoms::get();
  2908. XSetSelectionOwner (display, atoms.XdndSelection, windowH, CurrentTime);
  2909. // save the available types to XdndTypeList
  2910. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32,
  2911. dragState.getMimeTypes(),
  2912. dragState.getNumMimeTypes());
  2913. dragState.dragging = true;
  2914. handleExternalDragMotionNotify();
  2915. return true;
  2916. }
  2917. return false;
  2918. }
  2919. void externalResetDragAndDrop()
  2920. {
  2921. if (dragState.dragging)
  2922. {
  2923. ScopedXLock xlock;
  2924. XUngrabPointer (display, CurrentTime);
  2925. }
  2926. resetExternalDragState();
  2927. }
  2928. DragState dragState;
  2929. DragInfo dragInfo;
  2930. Atom dragAndDropCurrentMimeType;
  2931. Window dragAndDropSourceWindow;
  2932. bool finishAfterDropDataReceived;
  2933. Array<Atom> srcMimeTypeAtomList;
  2934. int pointerMap[5];
  2935. void initialisePointerMap()
  2936. {
  2937. const int numButtons = XGetPointerMapping (display, 0, 0);
  2938. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2939. if (numButtons == 2)
  2940. {
  2941. pointerMap[0] = Keys::LeftButton;
  2942. pointerMap[1] = Keys::RightButton;
  2943. }
  2944. else if (numButtons >= 3)
  2945. {
  2946. pointerMap[0] = Keys::LeftButton;
  2947. pointerMap[1] = Keys::MiddleButton;
  2948. pointerMap[2] = Keys::RightButton;
  2949. if (numButtons >= 5)
  2950. {
  2951. pointerMap[3] = Keys::WheelUp;
  2952. pointerMap[4] = Keys::WheelDown;
  2953. }
  2954. }
  2955. }
  2956. static Point<int> lastMousePos;
  2957. static void clearLastMousePos() noexcept
  2958. {
  2959. lastMousePos = Point<int> (0x100000, 0x100000);
  2960. }
  2961. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  2962. };
  2963. ModifierKeys LinuxComponentPeer::currentModifiers;
  2964. bool LinuxComponentPeer::isActiveApplication = false;
  2965. Point<int> LinuxComponentPeer::lastMousePos;
  2966. //==============================================================================
  2967. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess()
  2968. {
  2969. return LinuxComponentPeer::isActiveApplication;
  2970. }
  2971. // N/A on Linux as far as I know.
  2972. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2973. JUCE_API void JUCE_CALLTYPE Process::hide() {}
  2974. //==============================================================================
  2975. void ModifierKeys::updateCurrentModifiers() noexcept
  2976. {
  2977. currentModifiers = LinuxComponentPeer::currentModifiers;
  2978. }
  2979. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2980. {
  2981. if (display != nullptr)
  2982. {
  2983. Window root, child;
  2984. int x, y, winx, winy;
  2985. unsigned int mask;
  2986. int mouseMods = 0;
  2987. ScopedXLock xlock;
  2988. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  2989. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  2990. {
  2991. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  2992. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  2993. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  2994. }
  2995. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2996. }
  2997. return LinuxComponentPeer::currentModifiers;
  2998. }
  2999. //==============================================================================
  3000. void Desktop::setKioskComponent (Component* comp, bool enableOrDisable, bool /* allowMenusAndBars */)
  3001. {
  3002. if (enableOrDisable)
  3003. comp->setBounds (getDisplays().getMainDisplay().totalArea);
  3004. }
  3005. //==============================================================================
  3006. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  3007. {
  3008. return new LinuxComponentPeer (*this, styleFlags, (Window) nativeWindowToAttachTo);
  3009. }
  3010. //==============================================================================
  3011. void Desktop::Displays::findDisplays (float masterScale)
  3012. {
  3013. DisplayGeometry& geometry = DisplayGeometry::getOrCreateInstance (display, masterScale);
  3014. for (int i = 0; i < geometry.infos.size(); ++i)
  3015. {
  3016. const DisplayGeometry::ExtendedInfo& info = geometry.infos.getReference (i);
  3017. Desktop::Displays::Display d;
  3018. d.isMain = info.isMain;
  3019. d.scale = masterScale * info.scale;
  3020. d.dpi = info.dpi;
  3021. d.totalArea = DisplayGeometry::physicalToScaled (info.totalBounds);
  3022. d.userArea = (info.usableBounds / d.scale) + info.topLeftScaled;
  3023. displays.add (d);
  3024. }
  3025. }
  3026. //==============================================================================
  3027. bool MouseInputSource::SourceList::addSource()
  3028. {
  3029. if (sources.size() == 0)
  3030. {
  3031. addSource (0, true);
  3032. return true;
  3033. }
  3034. return false;
  3035. }
  3036. bool Desktop::canUseSemiTransparentWindows() noexcept
  3037. {
  3038. #if JUCE_USE_XRENDER
  3039. if (XRender::hasCompositingWindowManager())
  3040. {
  3041. int matchedDepth = 0, desiredDepth = 32;
  3042. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  3043. && matchedDepth == desiredDepth;
  3044. }
  3045. #endif
  3046. return false;
  3047. }
  3048. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3049. {
  3050. if (display == nullptr)
  3051. return Point<float>();
  3052. Window root, child;
  3053. int x, y, winx, winy;
  3054. unsigned int mask;
  3055. ScopedXLock xlock;
  3056. if (XQueryPointer (display,
  3057. RootWindow (display, DefaultScreen (display)),
  3058. &root, &child,
  3059. &x, &y, &winx, &winy, &mask) == False)
  3060. {
  3061. // Pointer not on the default screen
  3062. x = y = -1;
  3063. }
  3064. return DisplayGeometry::physicalToScaled (Point<float> ((float) x, (float) y));
  3065. }
  3066. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3067. {
  3068. if (display != nullptr)
  3069. {
  3070. ScopedXLock xlock;
  3071. Window root = RootWindow (display, DefaultScreen (display));
  3072. newPosition = DisplayGeometry::scaledToPhysical (newPosition);
  3073. XWarpPointer (display, None, root, 0, 0, 0, 0, roundToInt (newPosition.getX()), roundToInt (newPosition.getY()));
  3074. }
  3075. }
  3076. double Desktop::getDefaultMasterScale()
  3077. {
  3078. return 1.0;
  3079. }
  3080. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  3081. {
  3082. return upright;
  3083. }
  3084. //==============================================================================
  3085. static bool screenSaverAllowed = true;
  3086. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3087. {
  3088. if (screenSaverAllowed != isEnabled)
  3089. {
  3090. screenSaverAllowed = isEnabled;
  3091. if (display != nullptr)
  3092. {
  3093. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  3094. static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
  3095. if (xScreenSaverSuspend == nullptr)
  3096. if (void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW))
  3097. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  3098. ScopedXLock xlock;
  3099. if (xScreenSaverSuspend != nullptr)
  3100. xScreenSaverSuspend (display, ! isEnabled);
  3101. }
  3102. }
  3103. }
  3104. bool Desktop::isScreenSaverEnabled()
  3105. {
  3106. return screenSaverAllowed;
  3107. }
  3108. //==============================================================================
  3109. void* CustomMouseCursorInfo::create() const
  3110. {
  3111. if (display == nullptr)
  3112. return nullptr;
  3113. ScopedXLock xlock;
  3114. const unsigned int imageW = (unsigned int) image.getWidth();
  3115. const unsigned int imageH = (unsigned int) image.getHeight();
  3116. int hotspotX = hotspot.x;
  3117. int hotspotY = hotspot.y;
  3118. #if JUCE_USE_XCURSOR
  3119. {
  3120. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  3121. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  3122. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  3123. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  3124. static tXcursorSupportsARGB xcursorSupportsARGB = nullptr;
  3125. static tXcursorImageCreate xcursorImageCreate = nullptr;
  3126. static tXcursorImageDestroy xcursorImageDestroy = nullptr;
  3127. static tXcursorImageLoadCursor xcursorImageLoadCursor = nullptr;
  3128. static bool hasBeenLoaded = false;
  3129. if (! hasBeenLoaded)
  3130. {
  3131. hasBeenLoaded = true;
  3132. if (void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW))
  3133. {
  3134. xcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  3135. xcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  3136. xcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  3137. xcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  3138. if (xcursorSupportsARGB == nullptr || xcursorImageCreate == nullptr
  3139. || xcursorImageLoadCursor == nullptr || xcursorImageDestroy == nullptr
  3140. || ! xcursorSupportsARGB (display))
  3141. xcursorSupportsARGB = nullptr;
  3142. }
  3143. }
  3144. if (xcursorSupportsARGB != nullptr)
  3145. {
  3146. if (XcursorImage* xcImage = xcursorImageCreate ((int) imageW, (int) imageH))
  3147. {
  3148. xcImage->xhot = (XcursorDim) hotspotX;
  3149. xcImage->yhot = (XcursorDim) hotspotY;
  3150. XcursorPixel* dest = xcImage->pixels;
  3151. for (int y = 0; y < (int) imageH; ++y)
  3152. for (int x = 0; x < (int) imageW; ++x)
  3153. *dest++ = image.getPixelAt (x, y).getARGB();
  3154. void* result = (void*) xcursorImageLoadCursor (display, xcImage);
  3155. xcursorImageDestroy (xcImage);
  3156. if (result != nullptr)
  3157. return result;
  3158. }
  3159. }
  3160. }
  3161. #endif
  3162. Window root = RootWindow (display, DefaultScreen (display));
  3163. unsigned int cursorW, cursorH;
  3164. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  3165. return nullptr;
  3166. Image im (Image::ARGB, (int) cursorW, (int) cursorH, true);
  3167. {
  3168. Graphics g (im);
  3169. if (imageW > cursorW || imageH > cursorH)
  3170. {
  3171. hotspotX = (hotspotX * (int) cursorW) / (int) imageW;
  3172. hotspotY = (hotspotY * (int) cursorH) / (int) imageH;
  3173. g.drawImageWithin (image, 0, 0, (int) imageW, (int) imageH,
  3174. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  3175. false);
  3176. }
  3177. else
  3178. {
  3179. g.drawImageAt (image, 0, 0);
  3180. }
  3181. }
  3182. const unsigned int stride = (cursorW + 7) >> 3;
  3183. HeapBlock<char> maskPlane, sourcePlane;
  3184. maskPlane.calloc (stride * cursorH);
  3185. sourcePlane.calloc (stride * cursorH);
  3186. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  3187. for (int y = (int) cursorH; --y >= 0;)
  3188. {
  3189. for (int x = (int) cursorW; --x >= 0;)
  3190. {
  3191. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  3192. const unsigned int offset = (unsigned int) y * stride + ((unsigned int) x >> 3);
  3193. const Colour c (im.getPixelAt (x, y));
  3194. if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
  3195. if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
  3196. }
  3197. }
  3198. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3199. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  3200. XColor white, black;
  3201. black.red = black.green = black.blue = 0;
  3202. white.red = white.green = white.blue = 0xffff;
  3203. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black,
  3204. (unsigned int) hotspotX, (unsigned int) hotspotY);
  3205. XFreePixmap (display, sourcePixmap);
  3206. XFreePixmap (display, maskPixmap);
  3207. return result;
  3208. }
  3209. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  3210. {
  3211. if (cursorHandle != nullptr && display != nullptr)
  3212. {
  3213. ScopedXLock xlock;
  3214. XFreeCursor (display, (Cursor) cursorHandle);
  3215. }
  3216. }
  3217. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  3218. {
  3219. if (display == nullptr)
  3220. return None;
  3221. unsigned int shape;
  3222. switch (type)
  3223. {
  3224. case NormalCursor:
  3225. case ParentCursor: return None; // Use parent cursor
  3226. case NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), 0, 0).create();
  3227. case WaitCursor: shape = XC_watch; break;
  3228. case IBeamCursor: shape = XC_xterm; break;
  3229. case PointingHandCursor: shape = XC_hand2; break;
  3230. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  3231. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  3232. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  3233. case TopEdgeResizeCursor: shape = XC_top_side; break;
  3234. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  3235. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  3236. case RightEdgeResizeCursor: shape = XC_right_side; break;
  3237. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  3238. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  3239. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  3240. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  3241. case CrosshairCursor: shape = XC_crosshair; break;
  3242. case DraggingHandCursor: return createDraggingHandCursor();
  3243. case CopyingCursor:
  3244. {
  3245. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3246. 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,
  3247. 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,
  3248. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3249. const int copyCursorSize = 119;
  3250. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
  3251. }
  3252. default:
  3253. jassertfalse;
  3254. return None;
  3255. }
  3256. ScopedXLock xlock;
  3257. return (void*) XCreateFontCursor (display, shape);
  3258. }
  3259. void MouseCursor::showInWindow (ComponentPeer* peer) const
  3260. {
  3261. if (LinuxComponentPeer* const lp = dynamic_cast<LinuxComponentPeer*> (peer))
  3262. lp->showMouseCursor ((Cursor) getHandle());
  3263. }
  3264. void MouseCursor::showInAllWindows() const
  3265. {
  3266. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  3267. showInWindow (ComponentPeer::getPeer (i));
  3268. }
  3269. //==============================================================================
  3270. Image juce_createIconForFile (const File& /* file */)
  3271. {
  3272. return Image::null;
  3273. }
  3274. //==============================================================================
  3275. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  3276. {
  3277. if (files.size() == 0)
  3278. return false;
  3279. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  3280. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  3281. if (LinuxComponentPeer* const lp = dynamic_cast<LinuxComponentPeer*> (sourceComp->getPeer()))
  3282. return lp->externalDragFileInit (files, canMoveFiles);
  3283. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3284. jassertfalse;
  3285. return false;
  3286. }
  3287. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  3288. {
  3289. if (text.isEmpty())
  3290. return false;
  3291. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  3292. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  3293. if (LinuxComponentPeer* const lp = dynamic_cast<LinuxComponentPeer*> (sourceComp->getPeer()))
  3294. return lp->externalDragTextInit (text);
  3295. // This method must be called in response to a component's mouseDown or mouseDrag event!
  3296. jassertfalse;
  3297. return false;
  3298. }
  3299. //==============================================================================
  3300. void LookAndFeel::playAlertSound()
  3301. {
  3302. std::cout << "\a" << std::flush;
  3303. }
  3304. //==============================================================================
  3305. Rectangle<int> juce_LinuxScaledToPhysicalBounds(ComponentPeer* peer, const Rectangle<int>& bounds)
  3306. {
  3307. Rectangle<int> retval = bounds;
  3308. if (LinuxComponentPeer* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
  3309. retval *= linuxPeer->getCurrentScale();
  3310. return retval;
  3311. }
  3312. //==============================================================================
  3313. #if JUCE_MODAL_LOOPS_PERMITTED
  3314. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3315. const String& title, const String& message,
  3316. Component* /* associatedComponent */)
  3317. {
  3318. AlertWindow::showMessageBox (iconType, title, message);
  3319. }
  3320. #endif
  3321. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3322. const String& title, const String& message,
  3323. Component* associatedComponent,
  3324. ModalComponentManager::Callback* callback)
  3325. {
  3326. AlertWindow::showMessageBoxAsync (iconType, title, message, String::empty, associatedComponent, callback);
  3327. }
  3328. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3329. const String& title, const String& message,
  3330. Component* associatedComponent,
  3331. ModalComponentManager::Callback* callback)
  3332. {
  3333. return AlertWindow::showOkCancelBox (iconType, title, message, String::empty, String::empty,
  3334. associatedComponent, callback);
  3335. }
  3336. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3337. const String& title, const String& message,
  3338. Component* associatedComponent,
  3339. ModalComponentManager::Callback* callback)
  3340. {
  3341. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  3342. String::empty, String::empty, String::empty,
  3343. associatedComponent, callback);
  3344. }
  3345. //==============================================================================
  3346. const int KeyPress::spaceKey = XK_space & 0xff;
  3347. const int KeyPress::returnKey = XK_Return & 0xff;
  3348. const int KeyPress::escapeKey = XK_Escape & 0xff;
  3349. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  3350. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  3351. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  3352. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  3353. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  3354. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  3355. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  3356. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  3357. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  3358. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  3359. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  3360. const int KeyPress::tabKey = XK_Tab & 0xff;
  3361. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  3362. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  3363. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  3364. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  3365. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  3366. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  3367. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  3368. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  3369. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  3370. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  3371. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  3372. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  3373. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  3374. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  3375. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  3376. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  3377. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  3378. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  3379. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  3380. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  3381. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  3382. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  3383. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  3384. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  3385. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  3386. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  3387. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  3388. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  3389. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  3390. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  3391. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  3392. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  3393. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  3394. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  3395. const int KeyPress::playKey = ((int) 0xffeeff00) | Keys::extendedKeyModifier;
  3396. const int KeyPress::stopKey = ((int) 0xffeeff01) | Keys::extendedKeyModifier;
  3397. const int KeyPress::fastForwardKey = ((int) 0xffeeff02) | Keys::extendedKeyModifier;
  3398. const int KeyPress::rewindKey = ((int) 0xffeeff03) | Keys::extendedKeyModifier;