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.

3119 lines
110KB

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