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.

3113 lines
110KB

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