The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3524 lines
124KB

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