The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3142 lines
111KB

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