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.

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