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.

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