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.

3573 lines
125KB

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