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.

3482 lines
122KB

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