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.

3515 lines
124KB

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