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.

3605 lines
128KB

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