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.

3142 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* const component, const int windowStyleFlags, Window parentToAddTo)
  613. : ComponentPeer (component, 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. getComponent()->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 == getComponent())
  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 (getComponent()->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. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  1148. getEventTime (buttonPressEvent->time), 0, amount);
  1149. }
  1150. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent, int buttonModifierFlag)
  1151. {
  1152. currentModifiers = currentModifiers.withFlags (buttonModifierFlag);
  1153. toFront (true);
  1154. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  1155. getEventTime (buttonPressEvent->time));
  1156. }
  1157. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  1158. {
  1159. updateKeyModifiers (buttonPressEvent->state);
  1160. switch (pointerMap [buttonPressEvent->button - Button1])
  1161. {
  1162. case Keys::WheelUp: handleWheelEvent (buttonPressEvent, 84.0f); break;
  1163. case Keys::WheelDown: handleWheelEvent (buttonPressEvent, -84.0f); break;
  1164. case Keys::LeftButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::leftButtonModifier); break;
  1165. case Keys::RightButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::rightButtonModifier); break;
  1166. case Keys::MiddleButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::middleButtonModifier); break;
  1167. default: break;
  1168. }
  1169. clearLastMousePos();
  1170. }
  1171. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  1172. {
  1173. updateKeyModifiers (buttonRelEvent->state);
  1174. switch (pointerMap [buttonRelEvent->button - Button1])
  1175. {
  1176. case Keys::LeftButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
  1177. case Keys::RightButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
  1178. case Keys::MiddleButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
  1179. default: break;
  1180. }
  1181. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  1182. getEventTime (buttonRelEvent->time));
  1183. clearLastMousePos();
  1184. }
  1185. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  1186. {
  1187. updateKeyModifiers (movedEvent->state);
  1188. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  1189. if (lastMousePos != mousePos)
  1190. {
  1191. lastMousePos = mousePos;
  1192. if (parentWindow != nullptr && (styleFlags & windowHasTitleBar) == 0)
  1193. {
  1194. Window wRoot = 0, wParent = 0;
  1195. {
  1196. ScopedXLock xlock;
  1197. unsigned int numChildren;
  1198. Window* wChild = nullptr;
  1199. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  1200. }
  1201. if (wParent != 0
  1202. && wParent != windowH
  1203. && wParent != wRoot)
  1204. {
  1205. parentWindow = wParent;
  1206. updateBounds();
  1207. }
  1208. else
  1209. {
  1210. parentWindow = 0;
  1211. }
  1212. }
  1213. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  1214. }
  1215. }
  1216. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  1217. {
  1218. clearLastMousePos();
  1219. if (! currentModifiers.isAnyMouseButtonDown())
  1220. {
  1221. updateKeyModifiers (enterEvent->state);
  1222. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  1223. }
  1224. }
  1225. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  1226. {
  1227. // Suppress the normal leave if we've got a pointer grab, or if
  1228. // it's a bogus one caused by clicking a mouse button when running
  1229. // in a Window manager
  1230. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  1231. || leaveEvent->mode == NotifyUngrab)
  1232. {
  1233. updateKeyModifiers (leaveEvent->state);
  1234. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  1235. }
  1236. }
  1237. void handleFocusInEvent()
  1238. {
  1239. isActiveApplication = true;
  1240. if (isFocused())
  1241. handleFocusGain();
  1242. }
  1243. void handleFocusOutEvent()
  1244. {
  1245. isActiveApplication = false;
  1246. if (! isFocused())
  1247. handleFocusLoss();
  1248. }
  1249. void handleExposeEvent (XExposeEvent* exposeEvent)
  1250. {
  1251. // Batch together all pending expose events
  1252. XEvent nextEvent;
  1253. ScopedXLock xlock;
  1254. if (exposeEvent->window != windowH)
  1255. {
  1256. Window child;
  1257. XTranslateCoordinates (display, exposeEvent->window, windowH,
  1258. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  1259. &child);
  1260. }
  1261. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  1262. exposeEvent->width, exposeEvent->height));
  1263. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  1264. {
  1265. XPeekEvent (display, &nextEvent);
  1266. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  1267. break;
  1268. XNextEvent (display, &nextEvent);
  1269. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  1270. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  1271. nextExposeEvent->width, nextExposeEvent->height));
  1272. }
  1273. }
  1274. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  1275. {
  1276. updateBounds();
  1277. updateBorderSize();
  1278. handleMovedOrResized();
  1279. // if the native title bar is dragged, need to tell any active menus, etc.
  1280. if ((styleFlags & windowHasTitleBar) != 0
  1281. && component->isCurrentlyBlockedByAnotherModalComponent())
  1282. {
  1283. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  1284. if (currentModalComp != 0)
  1285. currentModalComp->inputAttemptWhenModal();
  1286. }
  1287. if (confEvent->window == windowH
  1288. && confEvent->above != 0
  1289. && isFrontWindow())
  1290. {
  1291. handleBroughtToFront();
  1292. }
  1293. }
  1294. void handleReparentNotifyEvent()
  1295. {
  1296. parentWindow = 0;
  1297. Window wRoot = 0;
  1298. Window* wChild = nullptr;
  1299. unsigned int numChildren;
  1300. {
  1301. ScopedXLock xlock;
  1302. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  1303. }
  1304. if (parentWindow == windowH || parentWindow == wRoot)
  1305. parentWindow = 0;
  1306. handleGravityNotify();
  1307. }
  1308. void handleGravityNotify()
  1309. {
  1310. updateBounds();
  1311. updateBorderSize();
  1312. handleMovedOrResized();
  1313. }
  1314. void handleMappingNotify (XMappingEvent* const mappingEvent)
  1315. {
  1316. if (mappingEvent->request != MappingPointer)
  1317. {
  1318. // Deal with modifier/keyboard mapping
  1319. ScopedXLock xlock;
  1320. XRefreshKeyboardMapping (mappingEvent);
  1321. updateModifierMappings();
  1322. }
  1323. }
  1324. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  1325. {
  1326. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  1327. {
  1328. const Atom atom = (Atom) clientMsg->data.l[0];
  1329. if (atom == Atoms::ProtocolList [Atoms::PING])
  1330. {
  1331. Window root = RootWindow (display, DefaultScreen (display));
  1332. clientMsg->window = root;
  1333. XSendEvent (display, root, False, NoEventMask, event);
  1334. XFlush (display);
  1335. }
  1336. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  1337. {
  1338. if ((getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0)
  1339. {
  1340. XWindowAttributes atts;
  1341. ScopedXLock xlock;
  1342. if (clientMsg->window != 0
  1343. && XGetWindowAttributes (display, clientMsg->window, &atts))
  1344. {
  1345. if (atts.map_state == IsViewable)
  1346. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  1347. }
  1348. }
  1349. }
  1350. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  1351. {
  1352. handleUserClosingWindow();
  1353. }
  1354. }
  1355. else if (clientMsg->message_type == Atoms::XdndEnter)
  1356. {
  1357. handleDragAndDropEnter (clientMsg);
  1358. }
  1359. else if (clientMsg->message_type == Atoms::XdndLeave)
  1360. {
  1361. resetDragAndDrop();
  1362. }
  1363. else if (clientMsg->message_type == Atoms::XdndPosition)
  1364. {
  1365. handleDragAndDropPosition (clientMsg);
  1366. }
  1367. else if (clientMsg->message_type == Atoms::XdndDrop)
  1368. {
  1369. handleDragAndDropDrop (clientMsg);
  1370. }
  1371. else if (clientMsg->message_type == Atoms::XdndStatus)
  1372. {
  1373. handleDragAndDropStatus (clientMsg);
  1374. }
  1375. else if (clientMsg->message_type == Atoms::XdndFinished)
  1376. {
  1377. resetDragAndDrop();
  1378. }
  1379. }
  1380. //==============================================================================
  1381. void showMouseCursor (Cursor cursor) noexcept
  1382. {
  1383. ScopedXLock xlock;
  1384. XDefineCursor (display, windowH, cursor);
  1385. }
  1386. //==============================================================================
  1387. bool dontRepaint;
  1388. static ModifierKeys currentModifiers;
  1389. static bool isActiveApplication;
  1390. private:
  1391. //==============================================================================
  1392. class LinuxRepaintManager : public Timer
  1393. {
  1394. public:
  1395. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  1396. : peer (peer_),
  1397. lastTimeImageUsed (0)
  1398. {
  1399. #if JUCE_USE_XSHM
  1400. shmCompletedDrawing = true;
  1401. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  1402. if (useARGBImagesForRendering)
  1403. {
  1404. ScopedXLock xlock;
  1405. XShmSegmentInfo segmentinfo;
  1406. XImage* const testImage
  1407. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  1408. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  1409. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  1410. XDestroyImage (testImage);
  1411. }
  1412. #endif
  1413. }
  1414. void timerCallback()
  1415. {
  1416. #if JUCE_USE_XSHM
  1417. if (! shmCompletedDrawing)
  1418. return;
  1419. #endif
  1420. if (! regionsNeedingRepaint.isEmpty())
  1421. {
  1422. stopTimer();
  1423. performAnyPendingRepaintsNow();
  1424. }
  1425. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  1426. {
  1427. stopTimer();
  1428. image = Image::null;
  1429. }
  1430. }
  1431. void repaint (const Rectangle<int>& area)
  1432. {
  1433. if (! isTimerRunning())
  1434. startTimer (repaintTimerPeriod);
  1435. regionsNeedingRepaint.add (area);
  1436. }
  1437. void performAnyPendingRepaintsNow()
  1438. {
  1439. #if JUCE_USE_XSHM
  1440. if (! shmCompletedDrawing)
  1441. {
  1442. startTimer (repaintTimerPeriod);
  1443. return;
  1444. }
  1445. #endif
  1446. peer->clearMaskedRegion();
  1447. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  1448. regionsNeedingRepaint.clear();
  1449. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  1450. if (! totalArea.isEmpty())
  1451. {
  1452. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  1453. || image.getHeight() < totalArea.getHeight())
  1454. {
  1455. #if JUCE_USE_XSHM
  1456. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  1457. : Image::RGB,
  1458. #else
  1459. image = Image (new XBitmapImage (Image::RGB,
  1460. #endif
  1461. (totalArea.getWidth() + 31) & ~31,
  1462. (totalArea.getHeight() + 31) & ~31,
  1463. false, peer->depth, peer->visual));
  1464. }
  1465. startTimer (repaintTimerPeriod);
  1466. RectangleList adjustedList (originalRepaintRegion);
  1467. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  1468. if (peer->depth == 32)
  1469. {
  1470. RectangleList::Iterator i (originalRepaintRegion);
  1471. while (i.next())
  1472. image.clear (*i.getRectangle() - totalArea.getPosition());
  1473. }
  1474. {
  1475. ScopedPointer<LowLevelGraphicsContext> context (peer->getComponent()->getLookAndFeel()
  1476. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList));
  1477. peer->handlePaint (*context);
  1478. }
  1479. if (! peer->maskedRegion.isEmpty())
  1480. originalRepaintRegion.subtract (peer->maskedRegion);
  1481. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  1482. {
  1483. #if JUCE_USE_XSHM
  1484. shmCompletedDrawing = false;
  1485. #endif
  1486. const Rectangle<int>& r = *i.getRectangle();
  1487. static_cast<XBitmapImage*> (image.getPixelData())
  1488. ->blitToWindow (peer->windowH,
  1489. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  1490. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  1491. }
  1492. }
  1493. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  1494. startTimer (repaintTimerPeriod);
  1495. }
  1496. #if JUCE_USE_XSHM
  1497. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  1498. #endif
  1499. private:
  1500. enum { repaintTimerPeriod = 1000 / 100 };
  1501. LinuxComponentPeer* const peer;
  1502. Image image;
  1503. uint32 lastTimeImageUsed;
  1504. RectangleList regionsNeedingRepaint;
  1505. #if JUCE_USE_XSHM
  1506. bool useARGBImagesForRendering, shmCompletedDrawing;
  1507. #endif
  1508. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  1509. };
  1510. ScopedPointer <LinuxRepaintManager> repainter;
  1511. friend class LinuxRepaintManager;
  1512. Window windowH, parentWindow;
  1513. Rectangle<int> bounds;
  1514. Image taskbarImage;
  1515. bool fullScreen, mapped;
  1516. Visual* visual;
  1517. int depth;
  1518. BorderSize<int> windowBorder;
  1519. enum { KeyPressEventType = 2 };
  1520. struct MotifWmHints
  1521. {
  1522. unsigned long flags;
  1523. unsigned long functions;
  1524. unsigned long decorations;
  1525. long input_mode;
  1526. unsigned long status;
  1527. };
  1528. static void updateKeyStates (const int keycode, const bool press) noexcept
  1529. {
  1530. const int keybyte = keycode >> 3;
  1531. const int keybit = (1 << (keycode & 7));
  1532. if (press)
  1533. Keys::keyStates [keybyte] |= keybit;
  1534. else
  1535. Keys::keyStates [keybyte] &= ~keybit;
  1536. }
  1537. static void updateKeyModifiers (const int status) noexcept
  1538. {
  1539. int keyMods = 0;
  1540. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  1541. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  1542. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  1543. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1544. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  1545. Keys::capsLock = ((status & LockMask) != 0);
  1546. }
  1547. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) noexcept
  1548. {
  1549. int modifier = 0;
  1550. bool isModifier = true;
  1551. switch (sym)
  1552. {
  1553. case XK_Shift_L:
  1554. case XK_Shift_R:
  1555. modifier = ModifierKeys::shiftModifier;
  1556. break;
  1557. case XK_Control_L:
  1558. case XK_Control_R:
  1559. modifier = ModifierKeys::ctrlModifier;
  1560. break;
  1561. case XK_Alt_L:
  1562. case XK_Alt_R:
  1563. modifier = ModifierKeys::altModifier;
  1564. break;
  1565. case XK_Num_Lock:
  1566. if (press)
  1567. Keys::numLock = ! Keys::numLock;
  1568. break;
  1569. case XK_Caps_Lock:
  1570. if (press)
  1571. Keys::capsLock = ! Keys::capsLock;
  1572. break;
  1573. case XK_Scroll_Lock:
  1574. break;
  1575. default:
  1576. isModifier = false;
  1577. break;
  1578. }
  1579. currentModifiers = press ? currentModifiers.withFlags (modifier)
  1580. : currentModifiers.withoutFlags (modifier);
  1581. return isModifier;
  1582. }
  1583. // Alt and Num lock are not defined by standard X
  1584. // modifier constants: check what they're mapped to
  1585. static void updateModifierMappings() noexcept
  1586. {
  1587. ScopedXLock xlock;
  1588. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  1589. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  1590. Keys::AltMask = 0;
  1591. Keys::NumLockMask = 0;
  1592. XModifierKeymap* mapping = XGetModifierMapping (display);
  1593. if (mapping)
  1594. {
  1595. for (int i = 0; i < 8; i++)
  1596. {
  1597. if (mapping->modifiermap [i << 1] == altLeftCode)
  1598. Keys::AltMask = 1 << i;
  1599. else if (mapping->modifiermap [i << 1] == numLockCode)
  1600. Keys::NumLockMask = 1 << i;
  1601. }
  1602. XFreeModifiermap (mapping);
  1603. }
  1604. }
  1605. //==============================================================================
  1606. static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
  1607. {
  1608. XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  1609. }
  1610. void removeWindowDecorations (Window wndH)
  1611. {
  1612. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  1613. if (hints != None)
  1614. {
  1615. MotifWmHints motifHints = { 0 };
  1616. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  1617. motifHints.decorations = 0;
  1618. ScopedXLock xlock;
  1619. xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
  1620. }
  1621. hints = Atoms::getIfExists ("_WIN_HINTS");
  1622. if (hints != None)
  1623. {
  1624. long gnomeHints = 0;
  1625. ScopedXLock xlock;
  1626. xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
  1627. }
  1628. hints = Atoms::getIfExists ("KWM_WIN_DECORATION");
  1629. if (hints != None)
  1630. {
  1631. long kwmHints = 2; /*KDE_tinyDecoration*/
  1632. ScopedXLock xlock;
  1633. xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
  1634. }
  1635. }
  1636. void addWindowButtons (Window wndH)
  1637. {
  1638. ScopedXLock xlock;
  1639. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  1640. if (hints != None)
  1641. {
  1642. MotifWmHints motifHints = { 0 };
  1643. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  1644. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  1645. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  1646. if ((styleFlags & windowHasCloseButton) != 0)
  1647. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  1648. if ((styleFlags & windowHasMinimiseButton) != 0)
  1649. {
  1650. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  1651. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  1652. }
  1653. if ((styleFlags & windowHasMaximiseButton) != 0)
  1654. {
  1655. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  1656. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  1657. }
  1658. if ((styleFlags & windowIsResizable) != 0)
  1659. {
  1660. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  1661. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  1662. }
  1663. xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
  1664. }
  1665. hints = Atoms::getIfExists ("_NET_WM_ALLOWED_ACTIONS");
  1666. if (hints != None)
  1667. {
  1668. Atom netHints [6];
  1669. int num = 0;
  1670. if ((styleFlags & windowIsResizable) != 0)
  1671. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_RESIZE");
  1672. if ((styleFlags & windowHasMaximiseButton) != 0)
  1673. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_FULLSCREEN");
  1674. if ((styleFlags & windowHasMinimiseButton) != 0)
  1675. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_MINIMIZE");
  1676. if ((styleFlags & windowHasCloseButton) != 0)
  1677. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_CLOSE");
  1678. xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
  1679. }
  1680. }
  1681. void setWindowType()
  1682. {
  1683. Atom netHints [2];
  1684. if ((styleFlags & windowIsTemporary) != 0
  1685. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  1686. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_COMBO");
  1687. else
  1688. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_NORMAL");
  1689. netHints[1] = Atoms::getIfExists ("_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  1690. xchangeProperty (windowH, Atoms::WindowType, XA_ATOM, 32, &netHints, 2);
  1691. int numHints = 0;
  1692. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1693. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_SKIP_TASKBAR");
  1694. if (component->isAlwaysOnTop())
  1695. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_ABOVE");
  1696. if (numHints > 0)
  1697. xchangeProperty (windowH, Atoms::WindowState, XA_ATOM, 32, &netHints, numHints);
  1698. }
  1699. void createWindow (Window parentToAddTo)
  1700. {
  1701. ScopedXLock xlock;
  1702. Atoms::initialiseAtoms();
  1703. resetDragAndDrop();
  1704. // Get defaults for various properties
  1705. const int screen = DefaultScreen (display);
  1706. Window root = RootWindow (display, screen);
  1707. // Try to obtain a 32-bit visual or fallback to 24 or 16
  1708. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  1709. if (visual == 0)
  1710. {
  1711. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  1712. Process::terminate();
  1713. }
  1714. // Create and install a colormap suitable fr our visual
  1715. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  1716. XInstallColormap (display, colormap);
  1717. // Set up the window attributes
  1718. XSetWindowAttributes swa;
  1719. swa.border_pixel = 0;
  1720. swa.background_pixmap = None;
  1721. swa.colormap = colormap;
  1722. swa.override_redirect = (getComponent()->isAlwaysOnTop() && (styleFlags & windowIsTemporary) != 0) ? True : False;
  1723. swa.event_mask = getAllEventsMask();
  1724. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  1725. 0, 0, 1, 1,
  1726. 0, depth, InputOutput, visual,
  1727. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  1728. &swa);
  1729. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  1730. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  1731. GrabModeAsync, GrabModeAsync, None, None);
  1732. // Set the window context to identify the window handle object
  1733. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  1734. {
  1735. // Failed
  1736. jassertfalse;
  1737. Logger::outputDebugString ("Failed to create context information for window.\n");
  1738. XDestroyWindow (display, windowH);
  1739. windowH = 0;
  1740. return;
  1741. }
  1742. // Set window manager hints
  1743. XWMHints* wmHints = XAllocWMHints();
  1744. wmHints->flags = InputHint | StateHint;
  1745. wmHints->input = True; // Locally active input model
  1746. wmHints->initial_state = NormalState;
  1747. XSetWMHints (display, windowH, wmHints);
  1748. XFree (wmHints);
  1749. // Set the window type
  1750. setWindowType();
  1751. // Define decoration
  1752. if ((styleFlags & windowHasTitleBar) == 0)
  1753. removeWindowDecorations (windowH);
  1754. else
  1755. addWindowButtons (windowH);
  1756. setTitle (getComponent()->getName());
  1757. // Associate the PID, allowing to be shut down when something goes wrong
  1758. unsigned long pid = getpid();
  1759. xchangeProperty (windowH, Atoms::Pid, XA_CARDINAL, 32, &pid, 1);
  1760. // Set window manager protocols
  1761. xchangeProperty (windowH, Atoms::Protocols, XA_ATOM, 32, Atoms::ProtocolList, 2);
  1762. // Set drag and drop flags
  1763. xchangeProperty (windowH, Atoms::XdndTypeList, XA_ATOM, 32, Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  1764. xchangeProperty (windowH, Atoms::XdndActionList, XA_ATOM, 32, Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  1765. xchangeProperty (windowH, Atoms::XdndActionDescription, XA_STRING, 8, "", 0);
  1766. xchangeProperty (windowH, Atoms::XdndAware, XA_ATOM, 32, &Atoms::DndVersion, 1);
  1767. initialisePointerMap();
  1768. updateModifierMappings();
  1769. }
  1770. void destroyWindow()
  1771. {
  1772. ScopedXLock xlock;
  1773. XPointer handlePointer;
  1774. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  1775. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  1776. XDestroyWindow (display, windowH);
  1777. // Wait for it to complete and then remove any events for this
  1778. // window from the event queue.
  1779. XSync (display, false);
  1780. XEvent event;
  1781. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  1782. {}
  1783. }
  1784. static int getAllEventsMask() noexcept
  1785. {
  1786. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  1787. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  1788. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  1789. }
  1790. static int64 getEventTime (::Time t)
  1791. {
  1792. static int64 eventTimeOffset = 0x12345678;
  1793. const int64 thisMessageTime = t;
  1794. if (eventTimeOffset == 0x12345678)
  1795. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  1796. return eventTimeOffset + thisMessageTime;
  1797. }
  1798. void updateBorderSize()
  1799. {
  1800. if ((styleFlags & windowHasTitleBar) == 0)
  1801. {
  1802. windowBorder = BorderSize<int> (0);
  1803. }
  1804. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  1805. {
  1806. ScopedXLock xlock;
  1807. Atom hints = Atoms::getIfExists ("_NET_FRAME_EXTENTS");
  1808. if (hints != None)
  1809. {
  1810. unsigned char* data = nullptr;
  1811. unsigned long nitems, bytesLeft;
  1812. Atom actualType;
  1813. int actualFormat;
  1814. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  1815. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  1816. &data) == Success)
  1817. {
  1818. const unsigned long* const sizes = (const unsigned long*) data;
  1819. if (actualFormat == 32)
  1820. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  1821. (int) sizes[3], (int) sizes[1]);
  1822. XFree (data);
  1823. }
  1824. }
  1825. }
  1826. }
  1827. void updateBounds()
  1828. {
  1829. jassert (windowH != 0);
  1830. if (windowH != 0)
  1831. {
  1832. Window root, child;
  1833. int wx = 0, wy = 0;
  1834. unsigned int ww = 0, wh = 0, bw, depth;
  1835. ScopedXLock xlock;
  1836. if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &depth))
  1837. if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  1838. wx = wy = 0;
  1839. bounds.setBounds (wx, wy, ww, wh);
  1840. }
  1841. }
  1842. //==============================================================================
  1843. void resetDragAndDrop()
  1844. {
  1845. dragInfo.files.clear();
  1846. dragInfo.text = String::empty;
  1847. dragInfo.position = Point<int> (-1, -1);
  1848. dragAndDropCurrentMimeType = 0;
  1849. dragAndDropSourceWindow = 0;
  1850. srcMimeTypeAtomList.clear();
  1851. }
  1852. void sendDragAndDropMessage (XClientMessageEvent& msg)
  1853. {
  1854. msg.type = ClientMessage;
  1855. msg.display = display;
  1856. msg.window = dragAndDropSourceWindow;
  1857. msg.format = 32;
  1858. msg.data.l[0] = windowH;
  1859. ScopedXLock xlock;
  1860. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  1861. }
  1862. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  1863. {
  1864. XClientMessageEvent msg = { 0 };
  1865. msg.message_type = Atoms::XdndStatus;
  1866. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  1867. msg.data.l[4] = dropAction;
  1868. sendDragAndDropMessage (msg);
  1869. }
  1870. void sendDragAndDropLeave()
  1871. {
  1872. XClientMessageEvent msg = { 0 };
  1873. msg.message_type = Atoms::XdndLeave;
  1874. sendDragAndDropMessage (msg);
  1875. }
  1876. void sendDragAndDropFinish()
  1877. {
  1878. XClientMessageEvent msg = { 0 };
  1879. msg.message_type = Atoms::XdndFinished;
  1880. sendDragAndDropMessage (msg);
  1881. }
  1882. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  1883. {
  1884. if ((clientMsg->data.l[1] & 1) == 0)
  1885. {
  1886. sendDragAndDropLeave();
  1887. if (dragInfo.files.size() > 0)
  1888. handleDragExit (dragInfo);
  1889. dragInfo.files.clear();
  1890. }
  1891. }
  1892. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  1893. {
  1894. if (dragAndDropSourceWindow == 0)
  1895. return;
  1896. dragAndDropSourceWindow = clientMsg->data.l[0];
  1897. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  1898. (int) clientMsg->data.l[2] & 0xffff);
  1899. dropPos -= getScreenPosition();
  1900. if (dragInfo.position != dropPos)
  1901. {
  1902. dragInfo.position = dropPos;
  1903. Atom targetAction = Atoms::XdndActionCopy;
  1904. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  1905. {
  1906. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  1907. {
  1908. targetAction = Atoms::allowedActions[i];
  1909. break;
  1910. }
  1911. }
  1912. sendDragAndDropStatus (true, targetAction);
  1913. if (dragInfo.files.size() == 0)
  1914. updateDraggedFileList (clientMsg);
  1915. if (dragInfo.files.size() > 0)
  1916. handleDragMove (dragInfo);
  1917. }
  1918. }
  1919. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  1920. {
  1921. if (dragInfo.files.size() == 0)
  1922. updateDraggedFileList (clientMsg);
  1923. DragInfo dragInfoCopy (dragInfo);
  1924. sendDragAndDropFinish();
  1925. resetDragAndDrop();
  1926. if (dragInfoCopy.files.size() > 0)
  1927. handleDragDrop (dragInfoCopy);
  1928. }
  1929. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  1930. {
  1931. dragInfo.files.clear();
  1932. srcMimeTypeAtomList.clear();
  1933. dragAndDropCurrentMimeType = 0;
  1934. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  1935. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  1936. {
  1937. dragAndDropSourceWindow = 0;
  1938. return;
  1939. }
  1940. dragAndDropSourceWindow = clientMsg->data.l[0];
  1941. if ((clientMsg->data.l[1] & 1) != 0)
  1942. {
  1943. Atom actual;
  1944. int format;
  1945. unsigned long count = 0, remaining = 0;
  1946. unsigned char* data = 0;
  1947. ScopedXLock xlock;
  1948. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  1949. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  1950. &count, &remaining, &data);
  1951. if (data != 0)
  1952. {
  1953. if (actual == XA_ATOM && format == 32 && count != 0)
  1954. {
  1955. const unsigned long* const types = (const unsigned long*) data;
  1956. for (unsigned int i = 0; i < count; ++i)
  1957. if (types[i] != None)
  1958. srcMimeTypeAtomList.add (types[i]);
  1959. }
  1960. XFree (data);
  1961. }
  1962. }
  1963. if (srcMimeTypeAtomList.size() == 0)
  1964. {
  1965. for (int i = 2; i < 5; ++i)
  1966. if (clientMsg->data.l[i] != None)
  1967. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  1968. if (srcMimeTypeAtomList.size() == 0)
  1969. {
  1970. dragAndDropSourceWindow = 0;
  1971. return;
  1972. }
  1973. }
  1974. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  1975. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  1976. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  1977. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  1978. handleDragAndDropPosition (clientMsg);
  1979. }
  1980. void handleDragAndDropSelection (const XEvent* const evt)
  1981. {
  1982. dragInfo.files.clear();
  1983. if (evt->xselection.property != 0)
  1984. {
  1985. StringArray lines;
  1986. {
  1987. MemoryBlock dropData;
  1988. for (;;)
  1989. {
  1990. Atom actual;
  1991. uint8* data = 0;
  1992. unsigned long count = 0, remaining = 0;
  1993. int format = 0;
  1994. ScopedXLock xlock;
  1995. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  1996. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  1997. &format, &count, &remaining, &data) == Success)
  1998. {
  1999. dropData.append (data, count * format / 8);
  2000. XFree (data);
  2001. if (remaining == 0)
  2002. break;
  2003. }
  2004. else
  2005. {
  2006. XFree (data);
  2007. break;
  2008. }
  2009. }
  2010. lines.addLines (dropData.toString());
  2011. }
  2012. for (int i = 0; i < lines.size(); ++i)
  2013. dragInfo.files.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  2014. dragInfo.files.trim();
  2015. dragInfo.files.removeEmptyStrings();
  2016. }
  2017. }
  2018. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  2019. {
  2020. dragInfo.files.clear();
  2021. if (dragAndDropSourceWindow != None
  2022. && dragAndDropCurrentMimeType != 0)
  2023. {
  2024. ScopedXLock xlock;
  2025. XConvertSelection (display,
  2026. Atoms::XdndSelection,
  2027. dragAndDropCurrentMimeType,
  2028. Atoms::getCreating ("JXSelectionWindowProperty"),
  2029. windowH,
  2030. clientMsg->data.l[2]);
  2031. }
  2032. }
  2033. DragInfo dragInfo;
  2034. Atom dragAndDropCurrentMimeType;
  2035. Window dragAndDropSourceWindow;
  2036. Array <Atom> srcMimeTypeAtomList;
  2037. int pointerMap[5];
  2038. void initialisePointerMap()
  2039. {
  2040. const int numButtons = XGetPointerMapping (display, 0, 0);
  2041. if (numButtons == 2)
  2042. {
  2043. pointerMap[0] = Keys::LeftButton;
  2044. pointerMap[1] = Keys::RightButton;
  2045. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2046. }
  2047. else if (numButtons >= 3)
  2048. {
  2049. pointerMap[0] = Keys::LeftButton;
  2050. pointerMap[1] = Keys::MiddleButton;
  2051. pointerMap[2] = Keys::RightButton;
  2052. if (numButtons >= 5)
  2053. {
  2054. pointerMap[3] = Keys::WheelUp;
  2055. pointerMap[4] = Keys::WheelDown;
  2056. }
  2057. }
  2058. }
  2059. static Point<int> lastMousePos;
  2060. static void clearLastMousePos() noexcept
  2061. {
  2062. lastMousePos = Point<int> (0x100000, 0x100000);
  2063. }
  2064. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  2065. };
  2066. ModifierKeys LinuxComponentPeer::currentModifiers;
  2067. bool LinuxComponentPeer::isActiveApplication = false;
  2068. Point<int> LinuxComponentPeer::lastMousePos;
  2069. //==============================================================================
  2070. bool Process::isForegroundProcess()
  2071. {
  2072. return LinuxComponentPeer::isActiveApplication;
  2073. }
  2074. //==============================================================================
  2075. void ModifierKeys::updateCurrentModifiers() noexcept
  2076. {
  2077. currentModifiers = LinuxComponentPeer::currentModifiers;
  2078. }
  2079. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2080. {
  2081. Window root, child;
  2082. int x, y, winx, winy;
  2083. unsigned int mask;
  2084. int mouseMods = 0;
  2085. ScopedXLock xlock;
  2086. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  2087. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  2088. {
  2089. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  2090. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  2091. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  2092. }
  2093. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2094. return LinuxComponentPeer::currentModifiers;
  2095. }
  2096. //==============================================================================
  2097. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  2098. {
  2099. if (enableOrDisable)
  2100. kioskModeComponent->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  2101. }
  2102. //==============================================================================
  2103. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  2104. {
  2105. return new LinuxComponentPeer (this, styleFlags, (Window) nativeWindowToAttachTo);
  2106. }
  2107. //==============================================================================
  2108. // (this callback is hooked up in the messaging code)
  2109. void juce_windowMessageReceive (XEvent* event)
  2110. {
  2111. if (event->xany.window != None)
  2112. {
  2113. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  2114. if (ComponentPeer::isValidPeer (peer))
  2115. peer->handleWindowMessage (event);
  2116. }
  2117. else
  2118. {
  2119. switch (event->xany.type)
  2120. {
  2121. case KeymapNotify:
  2122. {
  2123. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  2124. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  2125. break;
  2126. }
  2127. default:
  2128. break;
  2129. }
  2130. }
  2131. }
  2132. //==============================================================================
  2133. void Desktop::Displays::findDisplays()
  2134. {
  2135. if (display == 0)
  2136. return;
  2137. #if JUCE_USE_XINERAMA
  2138. int major_opcode, first_event, first_error;
  2139. ScopedXLock xlock;
  2140. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  2141. {
  2142. typedef Bool (*tXineramaIsActive) (::Display*);
  2143. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (::Display*, int*);
  2144. static tXineramaIsActive xXineramaIsActive = 0;
  2145. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  2146. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  2147. {
  2148. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  2149. if (h == 0)
  2150. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  2151. if (h != 0)
  2152. {
  2153. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  2154. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  2155. }
  2156. }
  2157. if (xXineramaIsActive != 0
  2158. && xXineramaQueryScreens != 0
  2159. && xXineramaIsActive (display))
  2160. {
  2161. int numMonitors = 0;
  2162. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  2163. if (screens != nullptr)
  2164. {
  2165. for (int index = 0; index < numMonitors; ++index)
  2166. {
  2167. for (int j = numMonitors; --j >= 0;)
  2168. {
  2169. if (screens[j].screen_number == index)
  2170. {
  2171. Display d;
  2172. d.userArea = d.totalArea = Rectangle<int> (screens[j].x_org,
  2173. screens[j].y_org,
  2174. screens[j].width,
  2175. screens[j].height);
  2176. d.isMain = (index == 0);
  2177. d.scale = 1.0;
  2178. displays.add (d);
  2179. }
  2180. }
  2181. }
  2182. XFree (screens);
  2183. }
  2184. }
  2185. }
  2186. if (displays.size() == 0)
  2187. #endif
  2188. {
  2189. Atom hints = Atoms::getIfExists ("_NET_WORKAREA");
  2190. if (hints != None)
  2191. {
  2192. const int numMonitors = ScreenCount (display);
  2193. for (int i = 0; i < numMonitors; ++i)
  2194. {
  2195. Window root = RootWindow (display, i);
  2196. unsigned long nitems, bytesLeft;
  2197. Atom actualType;
  2198. int actualFormat;
  2199. unsigned char* data = nullptr;
  2200. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  2201. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  2202. &data) == Success)
  2203. {
  2204. const long* const position = (const long*) data;
  2205. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  2206. {
  2207. Display d;
  2208. d.userArea = d.totalArea = Rectangle<int> (position[0], position[1],
  2209. position[2], position[3]);
  2210. d.isMain = (displays.size() == 0);
  2211. d.scale = 1.0;
  2212. displays.add (d);
  2213. }
  2214. XFree (data);
  2215. }
  2216. }
  2217. }
  2218. if (displays.size() == 0)
  2219. {
  2220. Display d;
  2221. d.userArea = d.totalArea = Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  2222. DisplayHeight (display, DefaultScreen (display)));
  2223. d.isMain = true;
  2224. d.scale = 1.0;
  2225. displays.add (d);
  2226. }
  2227. }
  2228. }
  2229. //==============================================================================
  2230. void Desktop::createMouseInputSources()
  2231. {
  2232. mouseSources.add (new MouseInputSource (0, true));
  2233. }
  2234. bool Desktop::canUseSemiTransparentWindows() noexcept
  2235. {
  2236. int matchedDepth = 0;
  2237. const int desiredDepth = 32;
  2238. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  2239. && (matchedDepth == desiredDepth);
  2240. }
  2241. Point<int> MouseInputSource::getCurrentMousePosition()
  2242. {
  2243. Window root, child;
  2244. int x, y, winx, winy;
  2245. unsigned int mask;
  2246. ScopedXLock xlock;
  2247. if (XQueryPointer (display,
  2248. RootWindow (display, DefaultScreen (display)),
  2249. &root, &child,
  2250. &x, &y, &winx, &winy, &mask) == False)
  2251. {
  2252. // Pointer not on the default screen
  2253. x = y = -1;
  2254. }
  2255. return Point<int> (x, y);
  2256. }
  2257. void Desktop::setMousePosition (const Point<int>& newPosition)
  2258. {
  2259. ScopedXLock xlock;
  2260. Window root = RootWindow (display, DefaultScreen (display));
  2261. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  2262. }
  2263. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  2264. {
  2265. return upright;
  2266. }
  2267. //==============================================================================
  2268. static bool screenSaverAllowed = true;
  2269. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  2270. {
  2271. if (screenSaverAllowed != isEnabled)
  2272. {
  2273. screenSaverAllowed = isEnabled;
  2274. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  2275. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  2276. if (xScreenSaverSuspend == 0)
  2277. {
  2278. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  2279. if (h != 0)
  2280. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  2281. }
  2282. ScopedXLock xlock;
  2283. if (xScreenSaverSuspend != 0)
  2284. xScreenSaverSuspend (display, ! isEnabled);
  2285. }
  2286. }
  2287. bool Desktop::isScreenSaverEnabled()
  2288. {
  2289. return screenSaverAllowed;
  2290. }
  2291. //==============================================================================
  2292. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  2293. {
  2294. ScopedXLock xlock;
  2295. const unsigned int imageW = image.getWidth();
  2296. const unsigned int imageH = image.getHeight();
  2297. #if JUCE_USE_XCURSOR
  2298. {
  2299. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  2300. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  2301. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  2302. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  2303. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  2304. static tXcursorImageCreate xXcursorImageCreate = 0;
  2305. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  2306. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  2307. static bool hasBeenLoaded = false;
  2308. if (! hasBeenLoaded)
  2309. {
  2310. hasBeenLoaded = true;
  2311. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  2312. if (h != 0)
  2313. {
  2314. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  2315. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  2316. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  2317. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  2318. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  2319. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  2320. || ! xXcursorSupportsARGB (display))
  2321. xXcursorSupportsARGB = 0;
  2322. }
  2323. }
  2324. if (xXcursorSupportsARGB != 0)
  2325. {
  2326. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  2327. if (xcImage != 0)
  2328. {
  2329. xcImage->xhot = hotspotX;
  2330. xcImage->yhot = hotspotY;
  2331. XcursorPixel* dest = xcImage->pixels;
  2332. for (int y = 0; y < (int) imageH; ++y)
  2333. for (int x = 0; x < (int) imageW; ++x)
  2334. *dest++ = image.getPixelAt (x, y).getARGB();
  2335. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  2336. xXcursorImageDestroy (xcImage);
  2337. if (result != 0)
  2338. return result;
  2339. }
  2340. }
  2341. }
  2342. #endif
  2343. Window root = RootWindow (display, DefaultScreen (display));
  2344. unsigned int cursorW, cursorH;
  2345. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  2346. return nullptr;
  2347. Image im (Image::ARGB, cursorW, cursorH, true);
  2348. {
  2349. Graphics g (im);
  2350. if (imageW > cursorW || imageH > cursorH)
  2351. {
  2352. hotspotX = (hotspotX * cursorW) / imageW;
  2353. hotspotY = (hotspotY * cursorH) / imageH;
  2354. g.drawImageWithin (image, 0, 0, imageW, imageH,
  2355. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  2356. false);
  2357. }
  2358. else
  2359. {
  2360. g.drawImageAt (image, 0, 0);
  2361. }
  2362. }
  2363. const int stride = (cursorW + 7) >> 3;
  2364. HeapBlock <char> maskPlane, sourcePlane;
  2365. maskPlane.calloc (stride * cursorH);
  2366. sourcePlane.calloc (stride * cursorH);
  2367. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  2368. for (int y = cursorH; --y >= 0;)
  2369. {
  2370. for (int x = cursorW; --x >= 0;)
  2371. {
  2372. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  2373. const int offset = y * stride + (x >> 3);
  2374. const Colour c (im.getPixelAt (x, y));
  2375. if (c.getAlpha() >= 128)
  2376. maskPlane[offset] |= mask;
  2377. if (c.getBrightness() >= 0.5f)
  2378. sourcePlane[offset] |= mask;
  2379. }
  2380. }
  2381. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2382. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2383. XColor white, black;
  2384. black.red = black.green = black.blue = 0;
  2385. white.red = white.green = white.blue = 0xffff;
  2386. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  2387. XFreePixmap (display, sourcePixmap);
  2388. XFreePixmap (display, maskPixmap);
  2389. return result;
  2390. }
  2391. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  2392. {
  2393. ScopedXLock xlock;
  2394. if (cursorHandle != 0)
  2395. XFreeCursor (display, (Cursor) cursorHandle);
  2396. }
  2397. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  2398. {
  2399. unsigned int shape;
  2400. switch (type)
  2401. {
  2402. case NormalCursor: return None; // Use parent cursor
  2403. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  2404. case WaitCursor: shape = XC_watch; break;
  2405. case IBeamCursor: shape = XC_xterm; break;
  2406. case PointingHandCursor: shape = XC_hand2; break;
  2407. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  2408. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  2409. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  2410. case TopEdgeResizeCursor: shape = XC_top_side; break;
  2411. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  2412. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  2413. case RightEdgeResizeCursor: shape = XC_right_side; break;
  2414. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  2415. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  2416. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  2417. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  2418. case CrosshairCursor: shape = XC_crosshair; break;
  2419. case DraggingHandCursor:
  2420. {
  2421. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  2422. 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,
  2423. 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 };
  2424. const int dragHandDataSize = 99;
  2425. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  2426. }
  2427. case CopyingCursor:
  2428. {
  2429. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  2430. 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,
  2431. 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,
  2432. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  2433. const int copyCursorSize = 119;
  2434. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  2435. }
  2436. default:
  2437. jassertfalse;
  2438. return None;
  2439. }
  2440. ScopedXLock xlock;
  2441. return (void*) XCreateFontCursor (display, shape);
  2442. }
  2443. void MouseCursor::showInWindow (ComponentPeer* peer) const
  2444. {
  2445. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  2446. if (lp != 0)
  2447. lp->showMouseCursor ((Cursor) getHandle());
  2448. }
  2449. void MouseCursor::showInAllWindows() const
  2450. {
  2451. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  2452. showInWindow (ComponentPeer::getPeer (i));
  2453. }
  2454. //==============================================================================
  2455. Image juce_createIconForFile (const File& file)
  2456. {
  2457. return Image::null;
  2458. }
  2459. ImagePixelData* NativeImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const
  2460. {
  2461. return SoftwareImageType().create (format, width, height, clearImage);
  2462. }
  2463. //==============================================================================
  2464. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  2465. {
  2466. jassertfalse; // not implemented!
  2467. return false;
  2468. }
  2469. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2470. {
  2471. jassertfalse; // not implemented!
  2472. return false;
  2473. }
  2474. //==============================================================================
  2475. void LookAndFeel::playAlertSound()
  2476. {
  2477. std::cout << "\a" << std::flush;
  2478. }
  2479. //==============================================================================
  2480. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  2481. const String& title, const String& message,
  2482. Component* associatedComponent)
  2483. {
  2484. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, message);
  2485. }
  2486. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  2487. const String& title, const String& message,
  2488. Component* associatedComponent)
  2489. {
  2490. AlertWindow::showMessageBoxAsync (AlertWindow::NoIcon, title, message);
  2491. }
  2492. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  2493. const String& title, const String& message,
  2494. Component* associatedComponent,
  2495. ModalComponentManager::Callback* callback)
  2496. {
  2497. return AlertWindow::showOkCancelBox (iconType, title, message, String::empty, String::empty,
  2498. associatedComponent, callback);
  2499. }
  2500. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  2501. const String& title, const String& message,
  2502. Component* associatedComponent,
  2503. ModalComponentManager::Callback* callback)
  2504. {
  2505. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  2506. String::empty, String::empty, String::empty,
  2507. associatedComponent, callback);
  2508. }
  2509. //==============================================================================
  2510. const int KeyPress::spaceKey = XK_space & 0xff;
  2511. const int KeyPress::returnKey = XK_Return & 0xff;
  2512. const int KeyPress::escapeKey = XK_Escape & 0xff;
  2513. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  2514. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  2515. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  2516. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  2517. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  2518. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  2519. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  2520. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  2521. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  2522. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  2523. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  2524. const int KeyPress::tabKey = XK_Tab & 0xff;
  2525. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  2526. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  2527. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  2528. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  2529. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  2530. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  2531. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  2532. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  2533. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  2534. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  2535. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  2536. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  2537. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  2538. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  2539. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  2540. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  2541. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  2542. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  2543. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  2544. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  2545. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  2546. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  2547. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  2548. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  2549. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  2550. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  2551. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  2552. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  2553. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  2554. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  2555. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  2556. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  2557. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  2558. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  2559. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  2560. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  2561. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  2562. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;