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.

3122 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 Image::SharedImage
  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. : Image::SharedImage (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. Image::ImageType getType() const { return Image::NativeImage; }
  471. LowLevelGraphicsContext* createLowLevelContext()
  472. {
  473. return new JUCE_DEFAULT_SOFTWARE_RENDERER_CLASS (Image (this));
  474. }
  475. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  476. {
  477. bitmap.data = imageData + x * pixelStride + y * lineStride;
  478. bitmap.pixelFormat = format;
  479. bitmap.lineStride = lineStride;
  480. bitmap.pixelStride = pixelStride;
  481. }
  482. SharedImage* clone()
  483. {
  484. jassertfalse;
  485. return nullptr;
  486. }
  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. JUCE_DEFAULT_SOFTWARE_RENDERER_CLASS context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  1443. if (peer->depth == 32)
  1444. {
  1445. RectangleList::Iterator i (originalRepaintRegion);
  1446. while (i.next())
  1447. image.clear (*i.getRectangle() - totalArea.getPosition());
  1448. }
  1449. peer->handlePaint (context);
  1450. if (! peer->maskedRegion.isEmpty())
  1451. originalRepaintRegion.subtract (peer->maskedRegion);
  1452. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  1453. {
  1454. #if JUCE_USE_XSHM
  1455. shmCompletedDrawing = false;
  1456. #endif
  1457. const Rectangle<int>& r = *i.getRectangle();
  1458. static_cast<XBitmapImage*> (image.getSharedImage())
  1459. ->blitToWindow (peer->windowH,
  1460. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  1461. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  1462. }
  1463. }
  1464. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  1465. startTimer (repaintTimerPeriod);
  1466. }
  1467. #if JUCE_USE_XSHM
  1468. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  1469. #endif
  1470. private:
  1471. enum { repaintTimerPeriod = 1000 / 100 };
  1472. LinuxComponentPeer* const peer;
  1473. Image image;
  1474. uint32 lastTimeImageUsed;
  1475. RectangleList regionsNeedingRepaint;
  1476. #if JUCE_USE_XSHM
  1477. bool useARGBImagesForRendering, shmCompletedDrawing;
  1478. #endif
  1479. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  1480. };
  1481. ScopedPointer <LinuxRepaintManager> repainter;
  1482. friend class LinuxRepaintManager;
  1483. Window windowH, parentWindow;
  1484. int wx, wy, ww, wh;
  1485. Image taskbarImage;
  1486. bool fullScreen, mapped;
  1487. Visual* visual;
  1488. int depth;
  1489. BorderSize<int> windowBorder;
  1490. struct MotifWmHints
  1491. {
  1492. unsigned long flags;
  1493. unsigned long functions;
  1494. unsigned long decorations;
  1495. long input_mode;
  1496. unsigned long status;
  1497. };
  1498. static void updateKeyStates (const int keycode, const bool press) noexcept
  1499. {
  1500. const int keybyte = keycode >> 3;
  1501. const int keybit = (1 << (keycode & 7));
  1502. if (press)
  1503. Keys::keyStates [keybyte] |= keybit;
  1504. else
  1505. Keys::keyStates [keybyte] &= ~keybit;
  1506. }
  1507. static void updateKeyModifiers (const int status) noexcept
  1508. {
  1509. int keyMods = 0;
  1510. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  1511. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  1512. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  1513. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1514. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  1515. Keys::capsLock = ((status & LockMask) != 0);
  1516. }
  1517. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) noexcept
  1518. {
  1519. int modifier = 0;
  1520. bool isModifier = true;
  1521. switch (sym)
  1522. {
  1523. case XK_Shift_L:
  1524. case XK_Shift_R:
  1525. modifier = ModifierKeys::shiftModifier;
  1526. break;
  1527. case XK_Control_L:
  1528. case XK_Control_R:
  1529. modifier = ModifierKeys::ctrlModifier;
  1530. break;
  1531. case XK_Alt_L:
  1532. case XK_Alt_R:
  1533. modifier = ModifierKeys::altModifier;
  1534. break;
  1535. case XK_Num_Lock:
  1536. if (press)
  1537. Keys::numLock = ! Keys::numLock;
  1538. break;
  1539. case XK_Caps_Lock:
  1540. if (press)
  1541. Keys::capsLock = ! Keys::capsLock;
  1542. break;
  1543. case XK_Scroll_Lock:
  1544. break;
  1545. default:
  1546. isModifier = false;
  1547. break;
  1548. }
  1549. if (modifier != 0)
  1550. {
  1551. if (press)
  1552. currentModifiers = currentModifiers.withFlags (modifier);
  1553. else
  1554. currentModifiers = currentModifiers.withoutFlags (modifier);
  1555. }
  1556. return isModifier;
  1557. }
  1558. // Alt and Num lock are not defined by standard X
  1559. // modifier constants: check what they're mapped to
  1560. static void updateModifierMappings() noexcept
  1561. {
  1562. ScopedXLock xlock;
  1563. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  1564. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  1565. Keys::AltMask = 0;
  1566. Keys::NumLockMask = 0;
  1567. XModifierKeymap* mapping = XGetModifierMapping (display);
  1568. if (mapping)
  1569. {
  1570. for (int i = 0; i < 8; i++)
  1571. {
  1572. if (mapping->modifiermap [i << 1] == altLeftCode)
  1573. Keys::AltMask = 1 << i;
  1574. else if (mapping->modifiermap [i << 1] == numLockCode)
  1575. Keys::NumLockMask = 1 << i;
  1576. }
  1577. XFreeModifiermap (mapping);
  1578. }
  1579. }
  1580. //==============================================================================
  1581. void removeWindowDecorations (Window wndH)
  1582. {
  1583. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  1584. if (hints != None)
  1585. {
  1586. MotifWmHints motifHints = { 0 };
  1587. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  1588. motifHints.decorations = 0;
  1589. ScopedXLock xlock;
  1590. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  1591. (unsigned char*) &motifHints, 4);
  1592. }
  1593. hints = XInternAtom (display, "_WIN_HINTS", True);
  1594. if (hints != None)
  1595. {
  1596. long gnomeHints = 0;
  1597. ScopedXLock xlock;
  1598. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  1599. (unsigned char*) &gnomeHints, 1);
  1600. }
  1601. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  1602. if (hints != None)
  1603. {
  1604. long kwmHints = 2; /*KDE_tinyDecoration*/
  1605. ScopedXLock xlock;
  1606. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  1607. (unsigned char*) &kwmHints, 1);
  1608. }
  1609. }
  1610. void addWindowButtons (Window wndH)
  1611. {
  1612. ScopedXLock xlock;
  1613. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  1614. if (hints != None)
  1615. {
  1616. MotifWmHints motifHints = { 0 };
  1617. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  1618. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  1619. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  1620. if ((styleFlags & windowHasCloseButton) != 0)
  1621. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  1622. if ((styleFlags & windowHasMinimiseButton) != 0)
  1623. {
  1624. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  1625. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  1626. }
  1627. if ((styleFlags & windowHasMaximiseButton) != 0)
  1628. {
  1629. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  1630. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  1631. }
  1632. if ((styleFlags & windowIsResizable) != 0)
  1633. {
  1634. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  1635. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  1636. }
  1637. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  1638. }
  1639. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  1640. if (hints != None)
  1641. {
  1642. int netHints [6];
  1643. int num = 0;
  1644. if ((styleFlags & windowIsResizable) != 0)
  1645. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  1646. if ((styleFlags & windowHasMaximiseButton) != 0)
  1647. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  1648. if ((styleFlags & windowHasMinimiseButton) != 0)
  1649. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  1650. if ((styleFlags & windowHasCloseButton) != 0)
  1651. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  1652. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  1653. }
  1654. }
  1655. void setWindowType()
  1656. {
  1657. int netHints [2];
  1658. int numHints = 0;
  1659. if ((styleFlags & windowIsTemporary) != 0
  1660. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  1661. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  1662. else
  1663. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  1664. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  1665. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  1666. (unsigned char*) &netHints, numHints);
  1667. numHints = 0;
  1668. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1669. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  1670. if (component->isAlwaysOnTop())
  1671. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  1672. if (numHints > 0)
  1673. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  1674. (unsigned char*) &netHints, numHints);
  1675. }
  1676. void createWindow (Window parentToAddTo)
  1677. {
  1678. ScopedXLock xlock;
  1679. Atoms::initialiseAtoms();
  1680. resetDragAndDrop();
  1681. // Get defaults for various properties
  1682. const int screen = DefaultScreen (display);
  1683. Window root = RootWindow (display, screen);
  1684. // Try to obtain a 32-bit visual or fallback to 24 or 16
  1685. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  1686. if (visual == 0)
  1687. {
  1688. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  1689. Process::terminate();
  1690. }
  1691. // Create and install a colormap suitable fr our visual
  1692. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  1693. XInstallColormap (display, colormap);
  1694. // Set up the window attributes
  1695. XSetWindowAttributes swa;
  1696. swa.border_pixel = 0;
  1697. swa.background_pixmap = None;
  1698. swa.colormap = colormap;
  1699. swa.event_mask = getAllEventsMask();
  1700. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  1701. 0, 0, 1, 1,
  1702. 0, depth, InputOutput, visual,
  1703. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  1704. &swa);
  1705. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  1706. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  1707. GrabModeAsync, GrabModeAsync, None, None);
  1708. // Set the window context to identify the window handle object
  1709. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  1710. {
  1711. // Failed
  1712. jassertfalse;
  1713. Logger::outputDebugString ("Failed to create context information for window.\n");
  1714. XDestroyWindow (display, windowH);
  1715. windowH = 0;
  1716. return;
  1717. }
  1718. // Set window manager hints
  1719. XWMHints* wmHints = XAllocWMHints();
  1720. wmHints->flags = InputHint | StateHint;
  1721. wmHints->input = True; // Locally active input model
  1722. wmHints->initial_state = NormalState;
  1723. XSetWMHints (display, windowH, wmHints);
  1724. XFree (wmHints);
  1725. // Set the window type
  1726. setWindowType();
  1727. // Define decoration
  1728. if ((styleFlags & windowHasTitleBar) == 0)
  1729. removeWindowDecorations (windowH);
  1730. else
  1731. addWindowButtons (windowH);
  1732. setTitle (getComponent()->getName());
  1733. // Associate the PID, allowing to be shut down when something goes wrong
  1734. unsigned long pid = getpid();
  1735. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  1736. (unsigned char*) &pid, 1);
  1737. // Set window manager protocols
  1738. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  1739. (unsigned char*) Atoms::ProtocolList, 2);
  1740. // Set drag and drop flags
  1741. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  1742. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  1743. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  1744. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  1745. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  1746. (const unsigned char*) "", 0);
  1747. unsigned long dndVersion = Atoms::DndVersion;
  1748. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  1749. (const unsigned char*) &dndVersion, 1);
  1750. // Initialise the pointer and keyboard mapping
  1751. // This is not the same as the logical pointer mapping the X server uses:
  1752. // we don't mess with this.
  1753. static bool mappingInitialised = false;
  1754. if (! mappingInitialised)
  1755. {
  1756. mappingInitialised = true;
  1757. const int numButtons = XGetPointerMapping (display, 0, 0);
  1758. if (numButtons == 2)
  1759. {
  1760. pointerMap[0] = Keys::LeftButton;
  1761. pointerMap[1] = Keys::RightButton;
  1762. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  1763. }
  1764. else if (numButtons >= 3)
  1765. {
  1766. pointerMap[0] = Keys::LeftButton;
  1767. pointerMap[1] = Keys::MiddleButton;
  1768. pointerMap[2] = Keys::RightButton;
  1769. if (numButtons >= 5)
  1770. {
  1771. pointerMap[3] = Keys::WheelUp;
  1772. pointerMap[4] = Keys::WheelDown;
  1773. }
  1774. }
  1775. updateModifierMappings();
  1776. }
  1777. }
  1778. void destroyWindow()
  1779. {
  1780. ScopedXLock xlock;
  1781. XPointer handlePointer;
  1782. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  1783. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  1784. XDestroyWindow (display, windowH);
  1785. // Wait for it to complete and then remove any events for this
  1786. // window from the event queue.
  1787. XSync (display, false);
  1788. XEvent event;
  1789. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  1790. {}
  1791. }
  1792. static int getAllEventsMask() noexcept
  1793. {
  1794. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  1795. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  1796. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  1797. }
  1798. static int64 getEventTime (::Time t)
  1799. {
  1800. static int64 eventTimeOffset = 0x12345678;
  1801. const int64 thisMessageTime = t;
  1802. if (eventTimeOffset == 0x12345678)
  1803. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  1804. return eventTimeOffset + thisMessageTime;
  1805. }
  1806. void updateBorderSize()
  1807. {
  1808. if ((styleFlags & windowHasTitleBar) == 0)
  1809. {
  1810. windowBorder = BorderSize<int> (0);
  1811. }
  1812. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  1813. {
  1814. ScopedXLock xlock;
  1815. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  1816. if (hints != None)
  1817. {
  1818. unsigned char* data = nullptr;
  1819. unsigned long nitems, bytesLeft;
  1820. Atom actualType;
  1821. int actualFormat;
  1822. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  1823. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  1824. &data) == Success)
  1825. {
  1826. const unsigned long* const sizes = (const unsigned long*) data;
  1827. if (actualFormat == 32)
  1828. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  1829. (int) sizes[3], (int) sizes[1]);
  1830. XFree (data);
  1831. }
  1832. }
  1833. }
  1834. }
  1835. void updateBounds()
  1836. {
  1837. jassert (windowH != 0);
  1838. if (windowH != 0)
  1839. {
  1840. Window root, child;
  1841. unsigned int bw, depth;
  1842. ScopedXLock xlock;
  1843. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  1844. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  1845. &bw, &depth))
  1846. {
  1847. wx = wy = ww = wh = 0;
  1848. }
  1849. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  1850. {
  1851. wx = wy = 0;
  1852. }
  1853. }
  1854. }
  1855. //==============================================================================
  1856. void resetDragAndDrop()
  1857. {
  1858. dragAndDropFiles.clear();
  1859. lastDropPos = Point<int> (-1, -1);
  1860. dragAndDropCurrentMimeType = 0;
  1861. dragAndDropSourceWindow = 0;
  1862. srcMimeTypeAtomList.clear();
  1863. }
  1864. void sendDragAndDropMessage (XClientMessageEvent& msg)
  1865. {
  1866. msg.type = ClientMessage;
  1867. msg.display = display;
  1868. msg.window = dragAndDropSourceWindow;
  1869. msg.format = 32;
  1870. msg.data.l[0] = windowH;
  1871. ScopedXLock xlock;
  1872. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  1873. }
  1874. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  1875. {
  1876. XClientMessageEvent msg = { 0 };
  1877. msg.message_type = Atoms::XdndStatus;
  1878. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  1879. msg.data.l[4] = dropAction;
  1880. sendDragAndDropMessage (msg);
  1881. }
  1882. void sendDragAndDropLeave()
  1883. {
  1884. XClientMessageEvent msg = { 0 };
  1885. msg.message_type = Atoms::XdndLeave;
  1886. sendDragAndDropMessage (msg);
  1887. }
  1888. void sendDragAndDropFinish()
  1889. {
  1890. XClientMessageEvent msg = { 0 };
  1891. msg.message_type = Atoms::XdndFinished;
  1892. sendDragAndDropMessage (msg);
  1893. }
  1894. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  1895. {
  1896. if ((clientMsg->data.l[1] & 1) == 0)
  1897. {
  1898. sendDragAndDropLeave();
  1899. if (dragAndDropFiles.size() > 0)
  1900. handleFileDragExit (dragAndDropFiles);
  1901. dragAndDropFiles.clear();
  1902. }
  1903. }
  1904. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  1905. {
  1906. if (dragAndDropSourceWindow == 0)
  1907. return;
  1908. dragAndDropSourceWindow = clientMsg->data.l[0];
  1909. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  1910. (int) clientMsg->data.l[2] & 0xffff);
  1911. dropPos -= getScreenPosition();
  1912. if (lastDropPos != dropPos)
  1913. {
  1914. lastDropPos = dropPos;
  1915. dragAndDropTimestamp = clientMsg->data.l[3];
  1916. Atom targetAction = Atoms::XdndActionCopy;
  1917. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  1918. {
  1919. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  1920. {
  1921. targetAction = Atoms::allowedActions[i];
  1922. break;
  1923. }
  1924. }
  1925. sendDragAndDropStatus (true, targetAction);
  1926. if (dragAndDropFiles.size() == 0)
  1927. updateDraggedFileList (clientMsg);
  1928. if (dragAndDropFiles.size() > 0)
  1929. handleFileDragMove (dragAndDropFiles, dropPos);
  1930. }
  1931. }
  1932. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  1933. {
  1934. if (dragAndDropFiles.size() == 0)
  1935. updateDraggedFileList (clientMsg);
  1936. const StringArray files (dragAndDropFiles);
  1937. const Point<int> lastPos (lastDropPos);
  1938. sendDragAndDropFinish();
  1939. resetDragAndDrop();
  1940. if (files.size() > 0)
  1941. handleFileDragDrop (files, lastPos);
  1942. }
  1943. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  1944. {
  1945. dragAndDropFiles.clear();
  1946. srcMimeTypeAtomList.clear();
  1947. dragAndDropCurrentMimeType = 0;
  1948. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  1949. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  1950. {
  1951. dragAndDropSourceWindow = 0;
  1952. return;
  1953. }
  1954. dragAndDropSourceWindow = clientMsg->data.l[0];
  1955. if ((clientMsg->data.l[1] & 1) != 0)
  1956. {
  1957. Atom actual;
  1958. int format;
  1959. unsigned long count = 0, remaining = 0;
  1960. unsigned char* data = 0;
  1961. ScopedXLock xlock;
  1962. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  1963. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  1964. &count, &remaining, &data);
  1965. if (data != 0)
  1966. {
  1967. if (actual == XA_ATOM && format == 32 && count != 0)
  1968. {
  1969. const unsigned long* const types = (const unsigned long*) data;
  1970. for (unsigned int i = 0; i < count; ++i)
  1971. if (types[i] != None)
  1972. srcMimeTypeAtomList.add (types[i]);
  1973. }
  1974. XFree (data);
  1975. }
  1976. }
  1977. if (srcMimeTypeAtomList.size() == 0)
  1978. {
  1979. for (int i = 2; i < 5; ++i)
  1980. if (clientMsg->data.l[i] != None)
  1981. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  1982. if (srcMimeTypeAtomList.size() == 0)
  1983. {
  1984. dragAndDropSourceWindow = 0;
  1985. return;
  1986. }
  1987. }
  1988. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  1989. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  1990. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  1991. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  1992. handleDragAndDropPosition (clientMsg);
  1993. }
  1994. void handleDragAndDropSelection (const XEvent* const evt)
  1995. {
  1996. dragAndDropFiles.clear();
  1997. if (evt->xselection.property != 0)
  1998. {
  1999. StringArray lines;
  2000. {
  2001. MemoryBlock dropData;
  2002. for (;;)
  2003. {
  2004. Atom actual;
  2005. uint8* data = 0;
  2006. unsigned long count = 0, remaining = 0;
  2007. int format = 0;
  2008. ScopedXLock xlock;
  2009. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  2010. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  2011. &format, &count, &remaining, &data) == Success)
  2012. {
  2013. dropData.append (data, count * format / 8);
  2014. XFree (data);
  2015. if (remaining == 0)
  2016. break;
  2017. }
  2018. else
  2019. {
  2020. XFree (data);
  2021. break;
  2022. }
  2023. }
  2024. lines.addLines (dropData.toString());
  2025. }
  2026. for (int i = 0; i < lines.size(); ++i)
  2027. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  2028. dragAndDropFiles.trim();
  2029. dragAndDropFiles.removeEmptyStrings();
  2030. }
  2031. }
  2032. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  2033. {
  2034. dragAndDropFiles.clear();
  2035. if (dragAndDropSourceWindow != None
  2036. && dragAndDropCurrentMimeType != 0)
  2037. {
  2038. dragAndDropTimestamp = clientMsg->data.l[2];
  2039. ScopedXLock xlock;
  2040. XConvertSelection (display,
  2041. Atoms::XdndSelection,
  2042. dragAndDropCurrentMimeType,
  2043. XInternAtom (display, "JXSelectionWindowProperty", 0),
  2044. windowH,
  2045. dragAndDropTimestamp);
  2046. }
  2047. }
  2048. StringArray dragAndDropFiles;
  2049. int dragAndDropTimestamp;
  2050. Point<int> lastDropPos;
  2051. Atom dragAndDropCurrentMimeType;
  2052. Window dragAndDropSourceWindow;
  2053. Array <Atom> srcMimeTypeAtomList;
  2054. static int pointerMap[5];
  2055. static Point<int> lastMousePos;
  2056. static void clearLastMousePos() noexcept
  2057. {
  2058. lastMousePos = Point<int> (0x100000, 0x100000);
  2059. }
  2060. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  2061. };
  2062. ModifierKeys LinuxComponentPeer::currentModifiers;
  2063. bool LinuxComponentPeer::isActiveApplication = false;
  2064. int LinuxComponentPeer::pointerMap[5];
  2065. Point<int> LinuxComponentPeer::lastMousePos;
  2066. //==============================================================================
  2067. bool Process::isForegroundProcess()
  2068. {
  2069. return LinuxComponentPeer::isActiveApplication;
  2070. }
  2071. //==============================================================================
  2072. void ModifierKeys::updateCurrentModifiers() noexcept
  2073. {
  2074. currentModifiers = LinuxComponentPeer::currentModifiers;
  2075. }
  2076. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2077. {
  2078. Window root, child;
  2079. int x, y, winx, winy;
  2080. unsigned int mask;
  2081. int mouseMods = 0;
  2082. ScopedXLock xlock;
  2083. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  2084. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  2085. {
  2086. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  2087. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  2088. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  2089. }
  2090. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2091. return LinuxComponentPeer::currentModifiers;
  2092. }
  2093. //==============================================================================
  2094. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  2095. {
  2096. if (enableOrDisable)
  2097. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  2098. }
  2099. //==============================================================================
  2100. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  2101. {
  2102. return new LinuxComponentPeer (this, styleFlags, (Window) nativeWindowToAttachTo);
  2103. }
  2104. //==============================================================================
  2105. // (this callback is hooked up in the messaging code)
  2106. void juce_windowMessageReceive (XEvent* event)
  2107. {
  2108. if (event->xany.window != None)
  2109. {
  2110. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  2111. if (ComponentPeer::isValidPeer (peer))
  2112. peer->handleWindowMessage (event);
  2113. }
  2114. else
  2115. {
  2116. switch (event->xany.type)
  2117. {
  2118. case KeymapNotify:
  2119. {
  2120. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  2121. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  2122. break;
  2123. }
  2124. default:
  2125. break;
  2126. }
  2127. }
  2128. }
  2129. //==============================================================================
  2130. void Desktop::getCurrentMonitorPositions (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  2131. {
  2132. if (display == 0)
  2133. return;
  2134. #if JUCE_USE_XINERAMA
  2135. int major_opcode, first_event, first_error;
  2136. ScopedXLock xlock;
  2137. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  2138. {
  2139. typedef Bool (*tXineramaIsActive) (Display*);
  2140. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  2141. static tXineramaIsActive xXineramaIsActive = 0;
  2142. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  2143. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  2144. {
  2145. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  2146. if (h == 0)
  2147. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  2148. if (h != 0)
  2149. {
  2150. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  2151. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  2152. }
  2153. }
  2154. if (xXineramaIsActive != 0
  2155. && xXineramaQueryScreens != 0
  2156. && xXineramaIsActive (display))
  2157. {
  2158. int numMonitors = 0;
  2159. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  2160. if (screens != 0)
  2161. {
  2162. for (int i = numMonitors; --i >= 0;)
  2163. {
  2164. int index = screens[i].screen_number;
  2165. if (index >= 0)
  2166. {
  2167. while (monitorCoords.size() < index)
  2168. monitorCoords.add (Rectangle<int>());
  2169. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  2170. screens[i].y_org,
  2171. screens[i].width,
  2172. screens[i].height));
  2173. }
  2174. }
  2175. XFree (screens);
  2176. }
  2177. }
  2178. }
  2179. if (monitorCoords.size() == 0)
  2180. #endif
  2181. {
  2182. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  2183. if (hints != None)
  2184. {
  2185. const int numMonitors = ScreenCount (display);
  2186. for (int i = 0; i < numMonitors; ++i)
  2187. {
  2188. Window root = RootWindow (display, i);
  2189. unsigned long nitems, bytesLeft;
  2190. Atom actualType;
  2191. int actualFormat;
  2192. unsigned char* data = nullptr;
  2193. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  2194. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  2195. &data) == Success)
  2196. {
  2197. const long* const position = (const long*) data;
  2198. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  2199. monitorCoords.add (Rectangle<int> (position[0], position[1],
  2200. position[2], position[3]));
  2201. XFree (data);
  2202. }
  2203. }
  2204. }
  2205. if (monitorCoords.size() == 0)
  2206. {
  2207. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  2208. DisplayHeight (display, DefaultScreen (display))));
  2209. }
  2210. }
  2211. }
  2212. //==============================================================================
  2213. void Desktop::createMouseInputSources()
  2214. {
  2215. mouseSources.add (new MouseInputSource (0, true));
  2216. }
  2217. bool Desktop::canUseSemiTransparentWindows() noexcept
  2218. {
  2219. int matchedDepth = 0;
  2220. const int desiredDepth = 32;
  2221. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  2222. && (matchedDepth == desiredDepth);
  2223. }
  2224. Point<int> MouseInputSource::getCurrentMousePosition()
  2225. {
  2226. Window root, child;
  2227. int x, y, winx, winy;
  2228. unsigned int mask;
  2229. ScopedXLock xlock;
  2230. if (XQueryPointer (display,
  2231. RootWindow (display, DefaultScreen (display)),
  2232. &root, &child,
  2233. &x, &y, &winx, &winy, &mask) == False)
  2234. {
  2235. // Pointer not on the default screen
  2236. x = y = -1;
  2237. }
  2238. return Point<int> (x, y);
  2239. }
  2240. void Desktop::setMousePosition (const Point<int>& newPosition)
  2241. {
  2242. ScopedXLock xlock;
  2243. Window root = RootWindow (display, DefaultScreen (display));
  2244. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  2245. }
  2246. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  2247. {
  2248. return upright;
  2249. }
  2250. //==============================================================================
  2251. static bool screenSaverAllowed = true;
  2252. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  2253. {
  2254. if (screenSaverAllowed != isEnabled)
  2255. {
  2256. screenSaverAllowed = isEnabled;
  2257. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  2258. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  2259. if (xScreenSaverSuspend == 0)
  2260. {
  2261. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  2262. if (h != 0)
  2263. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  2264. }
  2265. ScopedXLock xlock;
  2266. if (xScreenSaverSuspend != 0)
  2267. xScreenSaverSuspend (display, ! isEnabled);
  2268. }
  2269. }
  2270. bool Desktop::isScreenSaverEnabled()
  2271. {
  2272. return screenSaverAllowed;
  2273. }
  2274. //==============================================================================
  2275. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  2276. {
  2277. ScopedXLock xlock;
  2278. const unsigned int imageW = image.getWidth();
  2279. const unsigned int imageH = image.getHeight();
  2280. #if JUCE_USE_XCURSOR
  2281. {
  2282. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  2283. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  2284. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  2285. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  2286. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  2287. static tXcursorImageCreate xXcursorImageCreate = 0;
  2288. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  2289. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  2290. static bool hasBeenLoaded = false;
  2291. if (! hasBeenLoaded)
  2292. {
  2293. hasBeenLoaded = true;
  2294. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  2295. if (h != 0)
  2296. {
  2297. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  2298. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  2299. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  2300. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  2301. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  2302. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  2303. || ! xXcursorSupportsARGB (display))
  2304. xXcursorSupportsARGB = 0;
  2305. }
  2306. }
  2307. if (xXcursorSupportsARGB != 0)
  2308. {
  2309. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  2310. if (xcImage != 0)
  2311. {
  2312. xcImage->xhot = hotspotX;
  2313. xcImage->yhot = hotspotY;
  2314. XcursorPixel* dest = xcImage->pixels;
  2315. for (int y = 0; y < (int) imageH; ++y)
  2316. for (int x = 0; x < (int) imageW; ++x)
  2317. *dest++ = image.getPixelAt (x, y).getARGB();
  2318. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  2319. xXcursorImageDestroy (xcImage);
  2320. if (result != 0)
  2321. return result;
  2322. }
  2323. }
  2324. }
  2325. #endif
  2326. Window root = RootWindow (display, DefaultScreen (display));
  2327. unsigned int cursorW, cursorH;
  2328. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  2329. return nullptr;
  2330. Image im (Image::ARGB, cursorW, cursorH, true);
  2331. {
  2332. Graphics g (im);
  2333. if (imageW > cursorW || imageH > cursorH)
  2334. {
  2335. hotspotX = (hotspotX * cursorW) / imageW;
  2336. hotspotY = (hotspotY * cursorH) / imageH;
  2337. g.drawImageWithin (image, 0, 0, imageW, imageH,
  2338. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  2339. false);
  2340. }
  2341. else
  2342. {
  2343. g.drawImageAt (image, 0, 0);
  2344. }
  2345. }
  2346. const int stride = (cursorW + 7) >> 3;
  2347. HeapBlock <char> maskPlane, sourcePlane;
  2348. maskPlane.calloc (stride * cursorH);
  2349. sourcePlane.calloc (stride * cursorH);
  2350. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  2351. for (int y = cursorH; --y >= 0;)
  2352. {
  2353. for (int x = cursorW; --x >= 0;)
  2354. {
  2355. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  2356. const int offset = y * stride + (x >> 3);
  2357. const Colour c (im.getPixelAt (x, y));
  2358. if (c.getAlpha() >= 128)
  2359. maskPlane[offset] |= mask;
  2360. if (c.getBrightness() >= 0.5f)
  2361. sourcePlane[offset] |= mask;
  2362. }
  2363. }
  2364. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2365. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2366. XColor white, black;
  2367. black.red = black.green = black.blue = 0;
  2368. white.red = white.green = white.blue = 0xffff;
  2369. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  2370. XFreePixmap (display, sourcePixmap);
  2371. XFreePixmap (display, maskPixmap);
  2372. return result;
  2373. }
  2374. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  2375. {
  2376. ScopedXLock xlock;
  2377. if (cursorHandle != 0)
  2378. XFreeCursor (display, (Cursor) cursorHandle);
  2379. }
  2380. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  2381. {
  2382. unsigned int shape;
  2383. switch (type)
  2384. {
  2385. case NormalCursor: return None; // Use parent cursor
  2386. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  2387. case WaitCursor: shape = XC_watch; break;
  2388. case IBeamCursor: shape = XC_xterm; break;
  2389. case PointingHandCursor: shape = XC_hand2; break;
  2390. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  2391. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  2392. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  2393. case TopEdgeResizeCursor: shape = XC_top_side; break;
  2394. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  2395. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  2396. case RightEdgeResizeCursor: shape = XC_right_side; break;
  2397. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  2398. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  2399. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  2400. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  2401. case CrosshairCursor: shape = XC_crosshair; break;
  2402. case DraggingHandCursor:
  2403. {
  2404. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  2405. 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,
  2406. 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 };
  2407. const int dragHandDataSize = 99;
  2408. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  2409. }
  2410. case CopyingCursor:
  2411. {
  2412. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  2413. 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,
  2414. 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,
  2415. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  2416. const int copyCursorSize = 119;
  2417. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  2418. }
  2419. default:
  2420. jassertfalse;
  2421. return None;
  2422. }
  2423. ScopedXLock xlock;
  2424. return (void*) XCreateFontCursor (display, shape);
  2425. }
  2426. void MouseCursor::showInWindow (ComponentPeer* peer) const
  2427. {
  2428. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  2429. if (lp != 0)
  2430. lp->showMouseCursor ((Cursor) getHandle());
  2431. }
  2432. void MouseCursor::showInAllWindows() const
  2433. {
  2434. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  2435. showInWindow (ComponentPeer::getPeer (i));
  2436. }
  2437. //==============================================================================
  2438. Image juce_createIconForFile (const File& file)
  2439. {
  2440. return Image::null;
  2441. }
  2442. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  2443. {
  2444. return createSoftwareImage (format, width, height, clearImage);
  2445. }
  2446. //==============================================================================
  2447. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  2448. {
  2449. jassertfalse; // not implemented!
  2450. return false;
  2451. }
  2452. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2453. {
  2454. jassertfalse; // not implemented!
  2455. return false;
  2456. }
  2457. //==============================================================================
  2458. void LookAndFeel::playAlertSound()
  2459. {
  2460. std::cout << "\a" << std::flush;
  2461. }
  2462. //==============================================================================
  2463. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  2464. const String& title, const String& message,
  2465. Component* associatedComponent)
  2466. {
  2467. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, message);
  2468. }
  2469. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  2470. const String& title, const String& message,
  2471. Component* associatedComponent)
  2472. {
  2473. AlertWindow::showMessageBoxAsync (AlertWindow::NoIcon, title, message);
  2474. }
  2475. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  2476. const String& title, const String& message,
  2477. Component* associatedComponent,
  2478. ModalComponentManager::Callback* callback)
  2479. {
  2480. return AlertWindow::showOkCancelBox (iconType, title, message, String::empty, String::empty,
  2481. associatedComponent, callback);
  2482. }
  2483. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  2484. const String& title, const String& message,
  2485. Component* associatedComponent,
  2486. ModalComponentManager::Callback* callback)
  2487. {
  2488. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  2489. String::empty, String::empty, String::empty,
  2490. associatedComponent, callback);
  2491. }
  2492. //==============================================================================
  2493. const int KeyPress::spaceKey = XK_space & 0xff;
  2494. const int KeyPress::returnKey = XK_Return & 0xff;
  2495. const int KeyPress::escapeKey = XK_Escape & 0xff;
  2496. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  2497. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  2498. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  2499. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  2500. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  2501. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  2502. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  2503. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  2504. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  2505. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  2506. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  2507. const int KeyPress::tabKey = XK_Tab & 0xff;
  2508. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  2509. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  2510. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  2511. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  2512. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  2513. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  2514. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  2515. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  2516. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  2517. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  2518. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  2519. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  2520. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  2521. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  2522. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  2523. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  2524. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  2525. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  2526. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  2527. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  2528. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  2529. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  2530. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  2531. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  2532. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  2533. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  2534. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  2535. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  2536. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  2537. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  2538. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  2539. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  2540. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  2541. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  2542. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  2543. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  2544. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  2545. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;