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.

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