Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3526 lines
124KB

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