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.

3148 lines
111KB

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