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.

3566 lines
125KB

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