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.

3542 lines
125KB

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