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.

3471 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. class LinuxComponentPeer : public ComponentPeer
  657. {
  658. public:
  659. LinuxComponentPeer (Component& comp, const int windowStyleFlags, Window parentToAddTo)
  660. : ComponentPeer (comp, windowStyleFlags),
  661. windowH (0), parentWindow (0),
  662. fullScreen (false), mapped (false),
  663. visual (nullptr), depth (0)
  664. {
  665. // it's dangerous to create a window on a thread other than the message thread..
  666. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  667. dispatchWindowMessage = windowMessageReceive;
  668. repainter = new LinuxRepaintManager (*this);
  669. createWindow (parentToAddTo);
  670. setTitle (component.getName());
  671. }
  672. ~LinuxComponentPeer()
  673. {
  674. // it's dangerous to delete a window on a thread other than the message thread..
  675. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  676. deleteIconPixmaps();
  677. destroyWindow();
  678. windowH = 0;
  679. }
  680. // (this callback is hooked up in the messaging code)
  681. static void windowMessageReceive (XEvent& event)
  682. {
  683. if (event.xany.window != None)
  684. {
  685. if (LinuxComponentPeer* const peer = getPeerFor (event.xany.window))
  686. peer->handleWindowMessage (event);
  687. }
  688. else if (event.xany.type == KeymapNotify)
  689. {
  690. const XKeymapEvent& keymapEvent = (const XKeymapEvent&) event.xkeymap;
  691. memcpy (Keys::keyStates, keymapEvent.key_vector, 32);
  692. }
  693. }
  694. //==============================================================================
  695. void* getNativeHandle() const
  696. {
  697. return (void*) windowH;
  698. }
  699. static LinuxComponentPeer* getPeerFor (Window windowHandle) noexcept
  700. {
  701. XPointer peer = nullptr;
  702. ScopedXLock xlock;
  703. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  704. if (peer != nullptr && ! ComponentPeer::isValidPeer (reinterpret_cast <LinuxComponentPeer*> (peer)))
  705. peer = nullptr;
  706. return reinterpret_cast <LinuxComponentPeer*> (peer);
  707. }
  708. void setVisible (bool shouldBeVisible)
  709. {
  710. ScopedXLock xlock;
  711. if (shouldBeVisible)
  712. XMapWindow (display, windowH);
  713. else
  714. XUnmapWindow (display, windowH);
  715. }
  716. void setTitle (const String& title)
  717. {
  718. XTextProperty nameProperty;
  719. char* strings[] = { const_cast <char*> (title.toUTF8().getAddress()) };
  720. ScopedXLock xlock;
  721. if (XStringListToTextProperty (strings, 1, &nameProperty))
  722. {
  723. XSetWMName (display, windowH, &nameProperty);
  724. XSetWMIconName (display, windowH, &nameProperty);
  725. XFree (nameProperty.value);
  726. }
  727. }
  728. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  729. {
  730. if (fullScreen && ! isNowFullScreen)
  731. {
  732. // When transitioning back from fullscreen, we might need to remove
  733. // the FULLSCREEN window property
  734. Atom fs = Atoms::getIfExists ("_NET_WM_STATE_FULLSCREEN");
  735. if (fs != None)
  736. {
  737. Window root = RootWindow (display, DefaultScreen (display));
  738. XClientMessageEvent clientMsg;
  739. clientMsg.display = display;
  740. clientMsg.window = windowH;
  741. clientMsg.type = ClientMessage;
  742. clientMsg.format = 32;
  743. clientMsg.message_type = Atoms::get().WindowState;
  744. clientMsg.data.l[0] = 0; // Remove
  745. clientMsg.data.l[1] = fs;
  746. clientMsg.data.l[2] = 0;
  747. clientMsg.data.l[3] = 1; // Normal Source
  748. ScopedXLock xlock;
  749. XSendEvent (display, root, false,
  750. SubstructureRedirectMask | SubstructureNotifyMask,
  751. (XEvent*) &clientMsg);
  752. }
  753. }
  754. fullScreen = isNowFullScreen;
  755. if (windowH != 0)
  756. {
  757. bounds.setBounds (x, y, jmax (1, w), jmax (1, h));
  758. WeakReference<Component> deletionChecker (&component);
  759. ScopedXLock xlock;
  760. XSizeHints* const hints = XAllocSizeHints();
  761. hints->flags = USSize | USPosition;
  762. hints->x = bounds.getX();
  763. hints->y = bounds.getY();
  764. hints->width = bounds.getWidth();
  765. hints->height = bounds.getHeight();
  766. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  767. {
  768. hints->min_width = hints->max_width = hints->width;
  769. hints->min_height = hints->max_height = hints->height;
  770. hints->flags |= PMinSize | PMaxSize;
  771. }
  772. XSetWMNormalHints (display, windowH, hints);
  773. XFree (hints);
  774. XMoveResizeWindow (display, windowH,
  775. bounds.getX() - windowBorder.getLeft(),
  776. bounds.getY() - windowBorder.getTop(),
  777. bounds.getWidth(),
  778. bounds.getHeight());
  779. if (deletionChecker != nullptr)
  780. {
  781. updateBorderSize();
  782. handleMovedOrResized();
  783. }
  784. }
  785. }
  786. void setPosition (int x, int y) { setBounds (x, y, bounds.getWidth(), bounds.getHeight(), false); }
  787. void setSize (int w, int h) { setBounds (bounds.getX(), bounds.getY(), w, h, false); }
  788. Rectangle<int> getBounds() const { return bounds; }
  789. Point<int> getScreenPosition() const { return bounds.getPosition(); }
  790. Point<int> localToGlobal (const Point<int>& relativePosition)
  791. {
  792. return relativePosition + getScreenPosition();
  793. }
  794. Point<int> globalToLocal (const Point<int>& screenPosition)
  795. {
  796. return screenPosition - getScreenPosition();
  797. }
  798. void setAlpha (float /* newAlpha */)
  799. {
  800. //xxx todo!
  801. }
  802. void setMinimised (bool shouldBeMinimised)
  803. {
  804. if (shouldBeMinimised)
  805. {
  806. Window root = RootWindow (display, DefaultScreen (display));
  807. XClientMessageEvent clientMsg;
  808. clientMsg.display = display;
  809. clientMsg.window = windowH;
  810. clientMsg.type = ClientMessage;
  811. clientMsg.format = 32;
  812. clientMsg.message_type = Atoms::get().ChangeState;
  813. clientMsg.data.l[0] = IconicState;
  814. ScopedXLock xlock;
  815. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  816. }
  817. else
  818. {
  819. setVisible (true);
  820. }
  821. }
  822. bool isMinimised() const
  823. {
  824. ScopedXLock xlock;
  825. const Atoms& atoms = Atoms::get();
  826. GetXProperty prop (windowH, atoms.State, 0, 64, false, atoms.State);
  827. return prop.success
  828. && prop.actualType == atoms.State
  829. && prop.actualFormat == 32
  830. && prop.numItems > 0
  831. && ((unsigned long*) prop.data)[0] == IconicState;
  832. }
  833. void setFullScreen (const bool shouldBeFullScreen)
  834. {
  835. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  836. setMinimised (false);
  837. if (fullScreen != shouldBeFullScreen)
  838. {
  839. if (shouldBeFullScreen)
  840. r = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  841. if (! r.isEmpty())
  842. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  843. component.repaint();
  844. }
  845. }
  846. bool isFullScreen() const
  847. {
  848. return fullScreen;
  849. }
  850. bool isChildWindowOf (Window possibleParent) const
  851. {
  852. Window* windowList = nullptr;
  853. uint32 windowListSize = 0;
  854. Window parent, root;
  855. ScopedXLock xlock;
  856. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  857. {
  858. if (windowList != nullptr)
  859. XFree (windowList);
  860. return parent == possibleParent;
  861. }
  862. return false;
  863. }
  864. bool isFrontWindow() const
  865. {
  866. Window* windowList = nullptr;
  867. uint32 windowListSize = 0;
  868. bool result = false;
  869. ScopedXLock xlock;
  870. Window parent, root = RootWindow (display, DefaultScreen (display));
  871. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  872. {
  873. for (int i = windowListSize; --i >= 0;)
  874. {
  875. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  876. if (peer != 0)
  877. {
  878. result = (peer == this);
  879. break;
  880. }
  881. }
  882. }
  883. if (windowList != nullptr)
  884. XFree (windowList);
  885. return result;
  886. }
  887. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  888. {
  889. if (! bounds.withZeroOrigin().contains (position))
  890. return false;
  891. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  892. {
  893. Component* const c = Desktop::getInstance().getComponent (i);
  894. if (c == &component)
  895. break;
  896. if (c->contains (position + bounds.getPosition() - c->getScreenPosition()))
  897. return false;
  898. }
  899. if (trueIfInAChildWindow)
  900. return true;
  901. ::Window root, child;
  902. int wx, wy;
  903. unsigned int ww, wh, bw, depth;
  904. ScopedXLock xlock;
  905. return XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &depth)
  906. && XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child)
  907. && child == None;
  908. }
  909. BorderSize<int> getFrameSize() const
  910. {
  911. return BorderSize<int>();
  912. }
  913. bool setAlwaysOnTop (bool /* alwaysOnTop */)
  914. {
  915. return false;
  916. }
  917. void toFront (bool makeActive)
  918. {
  919. if (makeActive)
  920. {
  921. setVisible (true);
  922. grabFocus();
  923. }
  924. {
  925. ScopedXLock xlock;
  926. XEvent ev;
  927. ev.xclient.type = ClientMessage;
  928. ev.xclient.serial = 0;
  929. ev.xclient.send_event = True;
  930. ev.xclient.message_type = Atoms::get().ActiveWin;
  931. ev.xclient.window = windowH;
  932. ev.xclient.format = 32;
  933. ev.xclient.data.l[0] = 2;
  934. ev.xclient.data.l[1] = getUserTime();
  935. ev.xclient.data.l[2] = 0;
  936. ev.xclient.data.l[3] = 0;
  937. ev.xclient.data.l[4] = 0;
  938. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  939. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  940. XWindowAttributes attr;
  941. XGetWindowAttributes (display, windowH, &attr);
  942. if (component.isAlwaysOnTop())
  943. XRaiseWindow (display, windowH);
  944. XSync (display, False);
  945. }
  946. handleBroughtToFront();
  947. }
  948. void toBehind (ComponentPeer* other)
  949. {
  950. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  951. jassert (otherPeer != nullptr); // wrong type of window?
  952. if (otherPeer != nullptr)
  953. {
  954. setMinimised (false);
  955. Window newStack[] = { otherPeer->windowH, windowH };
  956. ScopedXLock xlock;
  957. XRestackWindows (display, newStack, 2);
  958. }
  959. }
  960. bool isFocused() const
  961. {
  962. int revert = 0;
  963. Window focusedWindow = 0;
  964. ScopedXLock xlock;
  965. XGetInputFocus (display, &focusedWindow, &revert);
  966. return focusedWindow == windowH;
  967. }
  968. void grabFocus()
  969. {
  970. XWindowAttributes atts;
  971. ScopedXLock xlock;
  972. if (windowH != 0
  973. && XGetWindowAttributes (display, windowH, &atts)
  974. && atts.map_state == IsViewable
  975. && ! isFocused())
  976. {
  977. XSetInputFocus (display, windowH, RevertToParent, getUserTime());
  978. isActiveApplication = true;
  979. }
  980. }
  981. void textInputRequired (const Point<int>&)
  982. {
  983. }
  984. void repaint (const Rectangle<int>& area)
  985. {
  986. repainter->repaint (area.getIntersection (component.getLocalBounds()));
  987. }
  988. void performAnyPendingRepaintsNow()
  989. {
  990. repainter->performAnyPendingRepaintsNow();
  991. }
  992. void setIcon (const Image& newIcon)
  993. {
  994. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  995. HeapBlock <unsigned long> data (dataSize);
  996. int index = 0;
  997. data[index++] = (unsigned long) newIcon.getWidth();
  998. data[index++] = (unsigned long) newIcon.getHeight();
  999. for (int y = 0; y < newIcon.getHeight(); ++y)
  1000. for (int x = 0; x < newIcon.getWidth(); ++x)
  1001. data[index++] = (unsigned long) newIcon.getPixelAt (x, y).getARGB();
  1002. ScopedXLock xlock;
  1003. xchangeProperty (windowH, Atoms::getCreating ("_NET_WM_ICON"), XA_CARDINAL, 32, data.getData(), dataSize);
  1004. deleteIconPixmaps();
  1005. XWMHints* wmHints = XGetWMHints (display, windowH);
  1006. if (wmHints == nullptr)
  1007. wmHints = XAllocWMHints();
  1008. wmHints->flags |= IconPixmapHint | IconMaskHint;
  1009. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  1010. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  1011. XSetWMHints (display, windowH, wmHints);
  1012. XFree (wmHints);
  1013. XSync (display, False);
  1014. }
  1015. void deleteIconPixmaps()
  1016. {
  1017. ScopedXLock xlock;
  1018. XWMHints* wmHints = XGetWMHints (display, windowH);
  1019. if (wmHints != nullptr)
  1020. {
  1021. if ((wmHints->flags & IconPixmapHint) != 0)
  1022. {
  1023. wmHints->flags &= ~IconPixmapHint;
  1024. XFreePixmap (display, wmHints->icon_pixmap);
  1025. }
  1026. if ((wmHints->flags & IconMaskHint) != 0)
  1027. {
  1028. wmHints->flags &= ~IconMaskHint;
  1029. XFreePixmap (display, wmHints->icon_mask);
  1030. }
  1031. XSetWMHints (display, windowH, wmHints);
  1032. XFree (wmHints);
  1033. }
  1034. }
  1035. //==============================================================================
  1036. void handleWindowMessage (XEvent& event)
  1037. {
  1038. switch (event.xany.type)
  1039. {
  1040. case KeyPressEventType: handleKeyPressEvent (event.xkey); break;
  1041. case KeyRelease: handleKeyReleaseEvent (event.xkey); break;
  1042. case ButtonPress: handleButtonPressEvent (event.xbutton); break;
  1043. case ButtonRelease: handleButtonReleaseEvent (event.xbutton); break;
  1044. case MotionNotify: handleMotionNotifyEvent (event.xmotion); break;
  1045. case EnterNotify: handleEnterNotifyEvent (event.xcrossing); break;
  1046. case LeaveNotify: handleLeaveNotifyEvent (event.xcrossing); break;
  1047. case FocusIn: handleFocusInEvent(); break;
  1048. case FocusOut: handleFocusOutEvent(); break;
  1049. case Expose: handleExposeEvent (event.xexpose); break;
  1050. case MappingNotify: handleMappingNotify (event.xmapping); break;
  1051. case ClientMessage: handleClientMessageEvent (event.xclient, event); break;
  1052. case SelectionNotify: handleDragAndDropSelection (event); break;
  1053. case ConfigureNotify: handleConfigureNotifyEvent (event.xconfigure); break;
  1054. case ReparentNotify: handleReparentNotifyEvent(); break;
  1055. case GravityNotify: handleGravityNotify(); break;
  1056. case SelectionClear: handleExternalSelectionClear(); break;
  1057. case SelectionRequest: handleExternalSelectionRequest (event); break;
  1058. case CirculateNotify:
  1059. case CreateNotify:
  1060. case DestroyNotify:
  1061. // Think we can ignore these
  1062. break;
  1063. case MapNotify:
  1064. mapped = true;
  1065. handleBroughtToFront();
  1066. break;
  1067. case UnmapNotify:
  1068. mapped = false;
  1069. break;
  1070. default:
  1071. #if JUCE_USE_XSHM
  1072. {
  1073. ScopedXLock xlock;
  1074. if (event.xany.type == XShmGetEventBase (display))
  1075. repainter->notifyPaintCompleted();
  1076. }
  1077. #endif
  1078. break;
  1079. }
  1080. }
  1081. void handleKeyPressEvent (XKeyEvent& keyEvent)
  1082. {
  1083. char utf8 [64] = { 0 };
  1084. juce_wchar unicodeChar = 0;
  1085. int keyCode = 0;
  1086. bool keyDownChange = false;
  1087. KeySym sym;
  1088. {
  1089. ScopedXLock xlock;
  1090. updateKeyStates (keyEvent.keycode, true);
  1091. const char* oldLocale = ::setlocale (LC_ALL, 0);
  1092. ::setlocale (LC_ALL, "");
  1093. XLookupString (&keyEvent, utf8, sizeof (utf8), &sym, 0);
  1094. ::setlocale (LC_ALL, oldLocale);
  1095. unicodeChar = *CharPointer_UTF8 (utf8);
  1096. keyCode = (int) unicodeChar;
  1097. if (keyCode < 0x20)
  1098. keyCode = XkbKeycodeToKeysym (display, keyEvent.keycode, 0, currentModifiers.isShiftDown() ? 1 : 0);
  1099. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  1100. }
  1101. const ModifierKeys oldMods (currentModifiers);
  1102. bool keyPressed = false;
  1103. if ((sym & 0xff00) == 0xff00)
  1104. {
  1105. switch (sym) // Translate keypad
  1106. {
  1107. case XK_KP_Divide: keyCode = XK_slash; break;
  1108. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  1109. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  1110. case XK_KP_Add: keyCode = XK_plus; break;
  1111. case XK_KP_Enter: keyCode = XK_Return; break;
  1112. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  1113. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  1114. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  1115. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  1116. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  1117. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  1118. case XK_KP_5: keyCode = XK_5; break;
  1119. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  1120. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  1121. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  1122. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  1123. default: break;
  1124. }
  1125. switch (sym)
  1126. {
  1127. case XK_Left:
  1128. case XK_Right:
  1129. case XK_Up:
  1130. case XK_Down:
  1131. case XK_Page_Up:
  1132. case XK_Page_Down:
  1133. case XK_End:
  1134. case XK_Home:
  1135. case XK_Delete:
  1136. case XK_Insert:
  1137. keyPressed = true;
  1138. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  1139. break;
  1140. case XK_Tab:
  1141. case XK_Return:
  1142. case XK_Escape:
  1143. case XK_BackSpace:
  1144. keyPressed = true;
  1145. keyCode &= 0xff;
  1146. break;
  1147. default:
  1148. if (sym >= XK_F1 && sym <= XK_F16)
  1149. {
  1150. keyPressed = true;
  1151. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  1152. }
  1153. break;
  1154. }
  1155. }
  1156. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  1157. keyPressed = true;
  1158. if (oldMods != currentModifiers)
  1159. handleModifierKeysChange();
  1160. if (keyDownChange)
  1161. handleKeyUpOrDown (true);
  1162. if (keyPressed)
  1163. handleKeyPress (keyCode, unicodeChar);
  1164. }
  1165. static bool isKeyReleasePartOfAutoRepeat (const XKeyEvent& keyReleaseEvent)
  1166. {
  1167. if (XPending (display))
  1168. {
  1169. XEvent e;
  1170. XPeekEvent (display, &e);
  1171. // Look for a subsequent key-down event with the same timestamp and keycode
  1172. return e.type == KeyPressEventType
  1173. && e.xkey.keycode == keyReleaseEvent.keycode
  1174. && e.xkey.time == keyReleaseEvent.time;
  1175. }
  1176. return false;
  1177. }
  1178. void handleKeyReleaseEvent (const XKeyEvent& keyEvent)
  1179. {
  1180. if (! isKeyReleasePartOfAutoRepeat (keyEvent))
  1181. {
  1182. updateKeyStates (keyEvent.keycode, false);
  1183. KeySym sym;
  1184. {
  1185. ScopedXLock xlock;
  1186. sym = XkbKeycodeToKeysym (display, keyEvent.keycode, 0, 0);
  1187. }
  1188. const ModifierKeys oldMods (currentModifiers);
  1189. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  1190. if (oldMods != currentModifiers)
  1191. handleModifierKeysChange();
  1192. if (keyDownChange)
  1193. handleKeyUpOrDown (false);
  1194. }
  1195. }
  1196. template <typename EventType>
  1197. static Point<int> getMousePos (const EventType& e) noexcept
  1198. {
  1199. return Point<int> (e.x, e.y);
  1200. }
  1201. void handleWheelEvent (const XButtonPressedEvent& buttonPressEvent, const float amount)
  1202. {
  1203. MouseWheelDetails wheel;
  1204. wheel.deltaX = 0.0f;
  1205. wheel.deltaY = amount;
  1206. wheel.isReversed = false;
  1207. wheel.isSmooth = false;
  1208. handleMouseWheel (0, getMousePos (buttonPressEvent), getEventTime (buttonPressEvent), wheel);
  1209. }
  1210. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent, int buttonModifierFlag)
  1211. {
  1212. currentModifiers = currentModifiers.withFlags (buttonModifierFlag);
  1213. toFront (true);
  1214. handleMouseEvent (0, getMousePos (buttonPressEvent), currentModifiers, getEventTime (buttonPressEvent));
  1215. }
  1216. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent)
  1217. {
  1218. updateKeyModifiers (buttonPressEvent.state);
  1219. switch (pointerMap [buttonPressEvent.button - Button1])
  1220. {
  1221. case Keys::WheelUp: handleWheelEvent (buttonPressEvent, 50.0f / 256.0f); break;
  1222. case Keys::WheelDown: handleWheelEvent (buttonPressEvent, -50.0f / 256.0f); break;
  1223. case Keys::LeftButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::leftButtonModifier); break;
  1224. case Keys::RightButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::rightButtonModifier); break;
  1225. case Keys::MiddleButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::middleButtonModifier); break;
  1226. default: break;
  1227. }
  1228. clearLastMousePos();
  1229. }
  1230. void handleButtonReleaseEvent (const XButtonReleasedEvent& buttonRelEvent)
  1231. {
  1232. updateKeyModifiers (buttonRelEvent.state);
  1233. switch (pointerMap [buttonRelEvent.button - Button1])
  1234. {
  1235. case Keys::LeftButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
  1236. case Keys::RightButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
  1237. case Keys::MiddleButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
  1238. default: break;
  1239. }
  1240. if (dragState.dragging)
  1241. handleExternalDragButtonReleaseEvent();
  1242. handleMouseEvent (0, getMousePos (buttonRelEvent), currentModifiers, getEventTime (buttonRelEvent));
  1243. clearLastMousePos();
  1244. if (parentWindow != 0)
  1245. updateBounds();
  1246. }
  1247. void handleMotionNotifyEvent (const XPointerMovedEvent& movedEvent)
  1248. {
  1249. updateKeyModifiers (movedEvent.state);
  1250. lastMousePos = Point<int> (movedEvent.x_root, movedEvent.y_root);
  1251. if (dragState.dragging)
  1252. handleExternalDragMotionNotify();
  1253. handleMouseEvent (0, getMousePos (movedEvent), currentModifiers, getEventTime (movedEvent));
  1254. }
  1255. void handleEnterNotifyEvent (const XEnterWindowEvent& enterEvent)
  1256. {
  1257. if (parentWindow != 0)
  1258. updateBounds();
  1259. clearLastMousePos();
  1260. if (! currentModifiers.isAnyMouseButtonDown())
  1261. {
  1262. updateKeyModifiers (enterEvent.state);
  1263. handleMouseEvent (0, getMousePos (enterEvent), currentModifiers, getEventTime (enterEvent));
  1264. }
  1265. }
  1266. void handleLeaveNotifyEvent (const XLeaveWindowEvent& leaveEvent)
  1267. {
  1268. // Suppress the normal leave if we've got a pointer grab, or if
  1269. // it's a bogus one caused by clicking a mouse button when running
  1270. // in a Window manager
  1271. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent.mode == NotifyNormal)
  1272. || leaveEvent.mode == NotifyUngrab)
  1273. {
  1274. updateKeyModifiers (leaveEvent.state);
  1275. handleMouseEvent (0, getMousePos (leaveEvent), currentModifiers, getEventTime (leaveEvent));
  1276. }
  1277. }
  1278. void handleFocusInEvent()
  1279. {
  1280. isActiveApplication = true;
  1281. if (isFocused())
  1282. handleFocusGain();
  1283. }
  1284. void handleFocusOutEvent()
  1285. {
  1286. isActiveApplication = false;
  1287. if (! isFocused())
  1288. handleFocusLoss();
  1289. }
  1290. void handleExposeEvent (XExposeEvent& exposeEvent)
  1291. {
  1292. // Batch together all pending expose events
  1293. XEvent nextEvent;
  1294. ScopedXLock xlock;
  1295. if (exposeEvent.window != windowH)
  1296. {
  1297. Window child;
  1298. XTranslateCoordinates (display, exposeEvent.window, windowH,
  1299. exposeEvent.x, exposeEvent.y, &exposeEvent.x, &exposeEvent.y,
  1300. &child);
  1301. }
  1302. repaint (Rectangle<int> (exposeEvent.x, exposeEvent.y,
  1303. exposeEvent.width, exposeEvent.height));
  1304. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  1305. {
  1306. XPeekEvent (display, &nextEvent);
  1307. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent.window)
  1308. break;
  1309. XNextEvent (display, &nextEvent);
  1310. const XExposeEvent& nextExposeEvent = (const XExposeEvent&) nextEvent.xexpose;
  1311. repaint (Rectangle<int> (nextExposeEvent.x, nextExposeEvent.y,
  1312. nextExposeEvent.width, nextExposeEvent.height));
  1313. }
  1314. }
  1315. void handleConfigureNotifyEvent (XConfigureEvent& confEvent)
  1316. {
  1317. updateBounds();
  1318. updateBorderSize();
  1319. handleMovedOrResized();
  1320. // if the native title bar is dragged, need to tell any active menus, etc.
  1321. if ((styleFlags & windowHasTitleBar) != 0
  1322. && component.isCurrentlyBlockedByAnotherModalComponent())
  1323. {
  1324. if (Component* const currentModalComp = Component::getCurrentlyModalComponent())
  1325. currentModalComp->inputAttemptWhenModal();
  1326. }
  1327. if (confEvent.window == windowH
  1328. && confEvent.above != 0
  1329. && isFrontWindow())
  1330. {
  1331. handleBroughtToFront();
  1332. }
  1333. }
  1334. void handleReparentNotifyEvent()
  1335. {
  1336. parentWindow = 0;
  1337. Window wRoot = 0;
  1338. Window* wChild = nullptr;
  1339. unsigned int numChildren;
  1340. {
  1341. ScopedXLock xlock;
  1342. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  1343. }
  1344. if (parentWindow == windowH || parentWindow == wRoot)
  1345. parentWindow = 0;
  1346. handleGravityNotify();
  1347. }
  1348. void handleGravityNotify()
  1349. {
  1350. updateBounds();
  1351. updateBorderSize();
  1352. handleMovedOrResized();
  1353. }
  1354. void handleMappingNotify (XMappingEvent& mappingEvent)
  1355. {
  1356. if (mappingEvent.request != MappingPointer)
  1357. {
  1358. // Deal with modifier/keyboard mapping
  1359. ScopedXLock xlock;
  1360. XRefreshKeyboardMapping (&mappingEvent);
  1361. updateModifierMappings();
  1362. }
  1363. }
  1364. void handleClientMessageEvent (XClientMessageEvent& clientMsg, XEvent& event)
  1365. {
  1366. const Atoms& atoms = Atoms::get();
  1367. if (clientMsg.message_type == atoms.Protocols && clientMsg.format == 32)
  1368. {
  1369. const Atom atom = (Atom) clientMsg.data.l[0];
  1370. if (atom == atoms.ProtocolList [Atoms::PING])
  1371. {
  1372. Window root = RootWindow (display, DefaultScreen (display));
  1373. clientMsg.window = root;
  1374. XSendEvent (display, root, False, NoEventMask, &event);
  1375. XFlush (display);
  1376. }
  1377. else if (atom == atoms.ProtocolList [Atoms::TAKE_FOCUS])
  1378. {
  1379. if ((getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0)
  1380. {
  1381. XWindowAttributes atts;
  1382. ScopedXLock xlock;
  1383. if (clientMsg.window != 0
  1384. && XGetWindowAttributes (display, clientMsg.window, &atts))
  1385. {
  1386. if (atts.map_state == IsViewable)
  1387. XSetInputFocus (display, clientMsg.window, RevertToParent, clientMsg.data.l[1]);
  1388. }
  1389. }
  1390. }
  1391. else if (atom == atoms.ProtocolList [Atoms::DELETE_WINDOW])
  1392. {
  1393. handleUserClosingWindow();
  1394. }
  1395. }
  1396. else if (clientMsg.message_type == atoms.XdndEnter)
  1397. {
  1398. handleDragAndDropEnter (clientMsg);
  1399. }
  1400. else if (clientMsg.message_type == atoms.XdndLeave)
  1401. {
  1402. handleDragExit (dragInfo);
  1403. resetDragAndDrop();
  1404. }
  1405. else if (clientMsg.message_type == atoms.XdndPosition)
  1406. {
  1407. handleDragAndDropPosition (clientMsg);
  1408. }
  1409. else if (clientMsg.message_type == atoms.XdndDrop)
  1410. {
  1411. handleDragAndDropDrop (clientMsg);
  1412. }
  1413. else if (clientMsg.message_type == atoms.XdndStatus)
  1414. {
  1415. handleExternalDragAndDropStatus (clientMsg);
  1416. }
  1417. else if (clientMsg.message_type == atoms.XdndFinished)
  1418. {
  1419. externalResetDragAndDrop();
  1420. }
  1421. }
  1422. bool externalDragTextInit (const String& text)
  1423. {
  1424. if (dragState.dragging)
  1425. return false;
  1426. return externalDragInit (true, text);
  1427. }
  1428. bool externalDragFileInit (const StringArray& files, bool /*canMoveFiles*/)
  1429. {
  1430. if (dragState.dragging)
  1431. return false;
  1432. StringArray uriList;
  1433. for (int i = 0; i < files.size(); ++i)
  1434. {
  1435. const String& f = files[i];
  1436. if (f.matchesWildcard ("?*://*", false))
  1437. uriList.add (f);
  1438. else
  1439. uriList.add ("file://" + f);
  1440. }
  1441. return externalDragInit (false, uriList.joinIntoString ("\r\n"));
  1442. }
  1443. //==============================================================================
  1444. void showMouseCursor (Cursor cursor) noexcept
  1445. {
  1446. ScopedXLock xlock;
  1447. XDefineCursor (display, windowH, cursor);
  1448. }
  1449. //==============================================================================
  1450. bool dontRepaint;
  1451. static ModifierKeys currentModifiers;
  1452. static bool isActiveApplication;
  1453. private:
  1454. //==============================================================================
  1455. class LinuxRepaintManager : public Timer
  1456. {
  1457. public:
  1458. LinuxRepaintManager (LinuxComponentPeer& p)
  1459. : peer (p), lastTimeImageUsed (0)
  1460. {
  1461. #if JUCE_USE_XSHM
  1462. shmCompletedDrawing = true;
  1463. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  1464. if (useARGBImagesForRendering)
  1465. {
  1466. ScopedXLock xlock;
  1467. XShmSegmentInfo segmentinfo;
  1468. XImage* const testImage
  1469. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  1470. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  1471. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  1472. XDestroyImage (testImage);
  1473. }
  1474. #endif
  1475. }
  1476. void timerCallback()
  1477. {
  1478. #if JUCE_USE_XSHM
  1479. if (! shmCompletedDrawing)
  1480. return;
  1481. #endif
  1482. if (! regionsNeedingRepaint.isEmpty())
  1483. {
  1484. stopTimer();
  1485. performAnyPendingRepaintsNow();
  1486. }
  1487. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  1488. {
  1489. stopTimer();
  1490. image = Image::null;
  1491. }
  1492. }
  1493. void repaint (const Rectangle<int>& area)
  1494. {
  1495. if (! isTimerRunning())
  1496. startTimer (repaintTimerPeriod);
  1497. regionsNeedingRepaint.add (area);
  1498. }
  1499. void performAnyPendingRepaintsNow()
  1500. {
  1501. #if JUCE_USE_XSHM
  1502. if (! shmCompletedDrawing)
  1503. {
  1504. startTimer (repaintTimerPeriod);
  1505. return;
  1506. }
  1507. #endif
  1508. peer.clearMaskedRegion();
  1509. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  1510. regionsNeedingRepaint.clear();
  1511. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  1512. if (! totalArea.isEmpty())
  1513. {
  1514. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  1515. || image.getHeight() < totalArea.getHeight())
  1516. {
  1517. #if JUCE_USE_XSHM
  1518. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  1519. : Image::RGB,
  1520. #else
  1521. image = Image (new XBitmapImage (Image::RGB,
  1522. #endif
  1523. (totalArea.getWidth() + 31) & ~31,
  1524. (totalArea.getHeight() + 31) & ~31,
  1525. false, peer.depth, peer.visual));
  1526. }
  1527. startTimer (repaintTimerPeriod);
  1528. RectangleList adjustedList (originalRepaintRegion);
  1529. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  1530. if (peer.depth == 32)
  1531. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  1532. image.clear (*i - totalArea.getPosition());
  1533. {
  1534. ScopedPointer<LowLevelGraphicsContext> context (peer.getComponent().getLookAndFeel()
  1535. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList));
  1536. peer.handlePaint (*context);
  1537. }
  1538. if (! peer.maskedRegion.isEmpty())
  1539. originalRepaintRegion.subtract (peer.maskedRegion);
  1540. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  1541. {
  1542. #if JUCE_USE_XSHM
  1543. shmCompletedDrawing = false;
  1544. #endif
  1545. static_cast<XBitmapImage*> (image.getPixelData())
  1546. ->blitToWindow (peer.windowH,
  1547. i->getX(), i->getY(), i->getWidth(), i->getHeight(),
  1548. i->getX() - totalArea.getX(), i->getY() - totalArea.getY());
  1549. }
  1550. }
  1551. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  1552. startTimer (repaintTimerPeriod);
  1553. }
  1554. #if JUCE_USE_XSHM
  1555. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  1556. #endif
  1557. private:
  1558. enum { repaintTimerPeriod = 1000 / 100 };
  1559. LinuxComponentPeer& peer;
  1560. Image image;
  1561. uint32 lastTimeImageUsed;
  1562. RectangleList regionsNeedingRepaint;
  1563. #if JUCE_USE_XSHM
  1564. bool useARGBImagesForRendering, shmCompletedDrawing;
  1565. #endif
  1566. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  1567. };
  1568. ScopedPointer <LinuxRepaintManager> repainter;
  1569. friend class LinuxRepaintManager;
  1570. Window windowH, parentWindow;
  1571. Rectangle<int> bounds;
  1572. Image taskbarImage;
  1573. bool fullScreen, mapped;
  1574. Visual* visual;
  1575. int depth;
  1576. BorderSize<int> windowBorder;
  1577. enum { KeyPressEventType = 2 };
  1578. struct MotifWmHints
  1579. {
  1580. unsigned long flags;
  1581. unsigned long functions;
  1582. unsigned long decorations;
  1583. long input_mode;
  1584. unsigned long status;
  1585. };
  1586. static void updateKeyStates (const int keycode, const bool press) noexcept
  1587. {
  1588. const int keybyte = keycode >> 3;
  1589. const int keybit = (1 << (keycode & 7));
  1590. if (press)
  1591. Keys::keyStates [keybyte] |= keybit;
  1592. else
  1593. Keys::keyStates [keybyte] &= ~keybit;
  1594. }
  1595. static void updateKeyModifiers (const int status) noexcept
  1596. {
  1597. int keyMods = 0;
  1598. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  1599. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  1600. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  1601. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1602. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  1603. Keys::capsLock = ((status & LockMask) != 0);
  1604. }
  1605. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) noexcept
  1606. {
  1607. int modifier = 0;
  1608. bool isModifier = true;
  1609. switch (sym)
  1610. {
  1611. case XK_Shift_L:
  1612. case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
  1613. case XK_Control_L:
  1614. case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
  1615. case XK_Alt_L:
  1616. case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
  1617. case XK_Num_Lock:
  1618. if (press)
  1619. Keys::numLock = ! Keys::numLock;
  1620. break;
  1621. case XK_Caps_Lock:
  1622. if (press)
  1623. Keys::capsLock = ! Keys::capsLock;
  1624. break;
  1625. case XK_Scroll_Lock:
  1626. break;
  1627. default:
  1628. isModifier = false;
  1629. break;
  1630. }
  1631. currentModifiers = press ? currentModifiers.withFlags (modifier)
  1632. : currentModifiers.withoutFlags (modifier);
  1633. return isModifier;
  1634. }
  1635. // Alt and Num lock are not defined by standard X
  1636. // modifier constants: check what they're mapped to
  1637. static void updateModifierMappings() noexcept
  1638. {
  1639. ScopedXLock xlock;
  1640. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  1641. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  1642. Keys::AltMask = 0;
  1643. Keys::NumLockMask = 0;
  1644. if (XModifierKeymap* const mapping = XGetModifierMapping (display))
  1645. {
  1646. for (int i = 0; i < 8; i++)
  1647. {
  1648. if (mapping->modifiermap [i << 1] == altLeftCode)
  1649. Keys::AltMask = 1 << i;
  1650. else if (mapping->modifiermap [i << 1] == numLockCode)
  1651. Keys::NumLockMask = 1 << i;
  1652. }
  1653. XFreeModifiermap (mapping);
  1654. }
  1655. }
  1656. //==============================================================================
  1657. static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
  1658. {
  1659. XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  1660. }
  1661. void removeWindowDecorations (Window wndH)
  1662. {
  1663. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  1664. if (hints != None)
  1665. {
  1666. MotifWmHints motifHints;
  1667. zerostruct (motifHints);
  1668. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  1669. motifHints.decorations = 0;
  1670. ScopedXLock xlock;
  1671. xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
  1672. }
  1673. hints = Atoms::getIfExists ("_WIN_HINTS");
  1674. if (hints != None)
  1675. {
  1676. long gnomeHints = 0;
  1677. ScopedXLock xlock;
  1678. xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
  1679. }
  1680. hints = Atoms::getIfExists ("KWM_WIN_DECORATION");
  1681. if (hints != None)
  1682. {
  1683. long kwmHints = 2; /*KDE_tinyDecoration*/
  1684. ScopedXLock xlock;
  1685. xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
  1686. }
  1687. }
  1688. void addWindowButtons (Window wndH)
  1689. {
  1690. ScopedXLock xlock;
  1691. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  1692. if (hints != None)
  1693. {
  1694. MotifWmHints motifHints;
  1695. zerostruct (motifHints);
  1696. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  1697. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  1698. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  1699. if ((styleFlags & windowHasCloseButton) != 0)
  1700. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  1701. if ((styleFlags & windowHasMinimiseButton) != 0)
  1702. {
  1703. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  1704. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  1705. }
  1706. if ((styleFlags & windowHasMaximiseButton) != 0)
  1707. {
  1708. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  1709. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  1710. }
  1711. if ((styleFlags & windowIsResizable) != 0)
  1712. {
  1713. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  1714. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  1715. }
  1716. xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
  1717. }
  1718. hints = Atoms::getIfExists ("_NET_WM_ALLOWED_ACTIONS");
  1719. if (hints != None)
  1720. {
  1721. Atom netHints [6];
  1722. int num = 0;
  1723. if ((styleFlags & windowIsResizable) != 0)
  1724. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_RESIZE");
  1725. if ((styleFlags & windowHasMaximiseButton) != 0)
  1726. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_FULLSCREEN");
  1727. if ((styleFlags & windowHasMinimiseButton) != 0)
  1728. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_MINIMIZE");
  1729. if ((styleFlags & windowHasCloseButton) != 0)
  1730. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_CLOSE");
  1731. xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
  1732. }
  1733. }
  1734. void setWindowType()
  1735. {
  1736. Atom netHints [2];
  1737. if ((styleFlags & windowIsTemporary) != 0
  1738. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  1739. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_COMBO");
  1740. else
  1741. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_NORMAL");
  1742. netHints[1] = Atoms::getIfExists ("_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  1743. xchangeProperty (windowH, Atoms::get().WindowType, XA_ATOM, 32, &netHints, 2);
  1744. int numHints = 0;
  1745. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1746. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_SKIP_TASKBAR");
  1747. if (component.isAlwaysOnTop())
  1748. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_ABOVE");
  1749. if (numHints > 0)
  1750. xchangeProperty (windowH, Atoms::get().WindowState, XA_ATOM, 32, &netHints, numHints);
  1751. }
  1752. void createWindow (Window parentToAddTo)
  1753. {
  1754. ScopedXLock xlock;
  1755. resetDragAndDrop();
  1756. // Get defaults for various properties
  1757. const int screen = DefaultScreen (display);
  1758. Window root = RootWindow (display, screen);
  1759. // Try to obtain a 32-bit visual or fallback to 24 or 16
  1760. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  1761. if (visual == nullptr)
  1762. {
  1763. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  1764. Process::terminate();
  1765. }
  1766. // Create and install a colormap suitable fr our visual
  1767. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  1768. XInstallColormap (display, colormap);
  1769. // Set up the window attributes
  1770. XSetWindowAttributes swa;
  1771. swa.border_pixel = 0;
  1772. swa.background_pixmap = None;
  1773. swa.colormap = colormap;
  1774. swa.override_redirect = (component.isAlwaysOnTop() && (styleFlags & windowIsTemporary) != 0) ? True : False;
  1775. swa.event_mask = getAllEventsMask();
  1776. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  1777. 0, 0, 1, 1,
  1778. 0, depth, InputOutput, visual,
  1779. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  1780. &swa);
  1781. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  1782. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  1783. GrabModeAsync, GrabModeAsync, None, None);
  1784. // Set the window context to identify the window handle object
  1785. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  1786. {
  1787. // Failed
  1788. jassertfalse;
  1789. Logger::outputDebugString ("Failed to create context information for window.\n");
  1790. XDestroyWindow (display, windowH);
  1791. windowH = 0;
  1792. return;
  1793. }
  1794. // Set window manager hints
  1795. XWMHints* wmHints = XAllocWMHints();
  1796. wmHints->flags = InputHint | StateHint;
  1797. wmHints->input = True; // Locally active input model
  1798. wmHints->initial_state = NormalState;
  1799. XSetWMHints (display, windowH, wmHints);
  1800. XFree (wmHints);
  1801. // Set the window type
  1802. setWindowType();
  1803. // Define decoration
  1804. if ((styleFlags & windowHasTitleBar) == 0)
  1805. removeWindowDecorations (windowH);
  1806. else
  1807. addWindowButtons (windowH);
  1808. setTitle (component.getName());
  1809. const Atoms& atoms = Atoms::get();
  1810. // Associate the PID, allowing to be shut down when something goes wrong
  1811. unsigned long pid = getpid();
  1812. xchangeProperty (windowH, atoms.Pid, XA_CARDINAL, 32, &pid, 1);
  1813. // Set window manager protocols
  1814. xchangeProperty (windowH, atoms.Protocols, XA_ATOM, 32, atoms.ProtocolList, 2);
  1815. // Set drag and drop flags
  1816. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32, atoms.allowedMimeTypes, numElementsInArray (atoms.allowedMimeTypes));
  1817. xchangeProperty (windowH, atoms.XdndActionList, XA_ATOM, 32, atoms.allowedActions, numElementsInArray (atoms.allowedActions));
  1818. xchangeProperty (windowH, atoms.XdndActionDescription, XA_STRING, 8, "", 0);
  1819. xchangeProperty (windowH, atoms.XdndAware, XA_ATOM, 32, &Atoms::DndVersion, 1);
  1820. initialisePointerMap();
  1821. updateModifierMappings();
  1822. }
  1823. void destroyWindow()
  1824. {
  1825. ScopedXLock xlock;
  1826. XPointer handlePointer;
  1827. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  1828. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  1829. XDestroyWindow (display, windowH);
  1830. // Wait for it to complete and then remove any events for this
  1831. // window from the event queue.
  1832. XSync (display, false);
  1833. XEvent event;
  1834. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  1835. {}
  1836. }
  1837. static int getAllEventsMask() noexcept
  1838. {
  1839. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  1840. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  1841. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  1842. }
  1843. template <typename EventType>
  1844. static int64 getEventTime (const EventType& t)
  1845. {
  1846. return getEventTime (t.time);
  1847. }
  1848. static int64 getEventTime (::Time t)
  1849. {
  1850. static int64 eventTimeOffset = 0x12345678;
  1851. const int64 thisMessageTime = t;
  1852. if (eventTimeOffset == 0x12345678)
  1853. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  1854. return eventTimeOffset + thisMessageTime;
  1855. }
  1856. long getUserTime() const
  1857. {
  1858. GetXProperty prop (windowH, Atoms::get().UserTime, 0, 65536, false, XA_CARDINAL);
  1859. return prop.success ? *(long*) prop.data : 0;
  1860. }
  1861. void updateBorderSize()
  1862. {
  1863. if ((styleFlags & windowHasTitleBar) == 0)
  1864. {
  1865. windowBorder = BorderSize<int> (0);
  1866. }
  1867. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  1868. {
  1869. ScopedXLock xlock;
  1870. Atom hints = Atoms::getIfExists ("_NET_FRAME_EXTENTS");
  1871. if (hints != None)
  1872. {
  1873. GetXProperty prop (windowH, hints, 0, 4, false, XA_CARDINAL);
  1874. if (prop.success && prop.actualFormat == 32)
  1875. {
  1876. const unsigned long* const sizes = (const unsigned long*) prop.data;
  1877. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  1878. (int) sizes[3], (int) sizes[1]);
  1879. }
  1880. }
  1881. }
  1882. }
  1883. void updateBounds()
  1884. {
  1885. jassert (windowH != 0);
  1886. if (windowH != 0)
  1887. {
  1888. Window root, child;
  1889. int wx = 0, wy = 0;
  1890. unsigned int ww = 0, wh = 0, bw, depth;
  1891. ScopedXLock xlock;
  1892. if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &depth))
  1893. if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  1894. wx = wy = 0;
  1895. bounds.setBounds (wx, wy, ww, wh);
  1896. }
  1897. }
  1898. //==============================================================================
  1899. struct DragState
  1900. {
  1901. DragState() noexcept
  1902. : isText (false), dragging (false), expectingStatus (false),
  1903. canDrop (false), targetWindow (None), xdndVersion (-1)
  1904. {
  1905. }
  1906. bool isText;
  1907. bool dragging; // currently performing outgoing external dnd as Xdnd source, have grabbed mouse
  1908. bool expectingStatus; // XdndPosition sent, waiting for XdndStatus
  1909. bool canDrop; // target window signals it will accept the drop
  1910. Window targetWindow; // potential drop target
  1911. int xdndVersion; // negotiated version with target
  1912. Rectangle<int> silentRect;
  1913. String textOrFiles;
  1914. const Atom* getMimeTypes() const noexcept { return isText ? Atoms::get().externalAllowedTextMimeTypes
  1915. : Atoms::get().externalAllowedFileMimeTypes; }
  1916. int getNumMimeTypes() const noexcept { return isText ? numElementsInArray (Atoms::get().externalAllowedTextMimeTypes)
  1917. : numElementsInArray (Atoms::get().externalAllowedFileMimeTypes); }
  1918. bool matchesTarget (Atom targetType) const
  1919. {
  1920. for (int i = getNumMimeTypes(); --i >= 0;)
  1921. if (getMimeTypes()[i] == targetType)
  1922. return true;
  1923. return false;
  1924. }
  1925. };
  1926. //==============================================================================
  1927. void resetDragAndDrop()
  1928. {
  1929. dragInfo.clear();
  1930. dragInfo.position = Point<int> (-1, -1);
  1931. dragAndDropCurrentMimeType = 0;
  1932. dragAndDropSourceWindow = 0;
  1933. srcMimeTypeAtomList.clear();
  1934. finishAfterDropDataReceived = false;
  1935. }
  1936. void resetExternalDragState()
  1937. {
  1938. dragState = DragState();
  1939. }
  1940. void sendDragAndDropMessage (XClientMessageEvent& msg)
  1941. {
  1942. msg.type = ClientMessage;
  1943. msg.display = display;
  1944. msg.window = dragAndDropSourceWindow;
  1945. msg.format = 32;
  1946. msg.data.l[0] = windowH;
  1947. ScopedXLock xlock;
  1948. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  1949. }
  1950. bool sendExternalDragAndDropMessage (XClientMessageEvent& msg, const Window targetWindow)
  1951. {
  1952. msg.type = ClientMessage;
  1953. msg.display = display;
  1954. msg.window = targetWindow;
  1955. msg.format = 32;
  1956. msg.data.l[0] = windowH;
  1957. ScopedXLock xlock;
  1958. return XSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
  1959. }
  1960. void sendExternalDragAndDropDrop (const Window targetWindow)
  1961. {
  1962. XClientMessageEvent msg;
  1963. zerostruct (msg);
  1964. msg.message_type = Atoms::get().XdndDrop;
  1965. msg.data.l[2] = CurrentTime;
  1966. sendExternalDragAndDropMessage (msg, targetWindow);
  1967. }
  1968. void sendExternalDragAndDropEnter (const Window targetWindow)
  1969. {
  1970. XClientMessageEvent msg;
  1971. zerostruct (msg);
  1972. msg.message_type = Atoms::get().XdndEnter;
  1973. const Atom* mimeTypes = dragState.getMimeTypes();
  1974. const int numMimeTypes = dragState.getNumMimeTypes();
  1975. msg.data.l[1] = (dragState.xdndVersion << 24) | (numMimeTypes > 3);
  1976. msg.data.l[2] = numMimeTypes > 0 ? mimeTypes[0] : 0;
  1977. msg.data.l[3] = numMimeTypes > 1 ? mimeTypes[1] : 0;
  1978. msg.data.l[4] = numMimeTypes > 2 ? mimeTypes[2] : 0;
  1979. sendExternalDragAndDropMessage (msg, targetWindow);
  1980. }
  1981. void sendExternalDragAndDropPosition (const Window targetWindow)
  1982. {
  1983. XClientMessageEvent msg;
  1984. zerostruct (msg);
  1985. msg.message_type = Atoms::get().XdndPosition;
  1986. const Point<int> mousePos (Desktop::getInstance().getMousePosition());
  1987. if (dragState.silentRect.contains (mousePos)) // we've been asked to keep silent
  1988. return;
  1989. msg.data.l[1] = 0;
  1990. msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
  1991. msg.data.l[3] = CurrentTime;
  1992. msg.data.l[4] = Atoms::get().XdndActionCopy; // this is all JUCE currently supports
  1993. dragState.expectingStatus = sendExternalDragAndDropMessage (msg, targetWindow);
  1994. }
  1995. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  1996. {
  1997. XClientMessageEvent msg;
  1998. zerostruct (msg);
  1999. msg.message_type = Atoms::get().XdndStatus;
  2000. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  2001. msg.data.l[4] = dropAction;
  2002. sendDragAndDropMessage (msg);
  2003. }
  2004. void sendExternalDragAndDropLeave (const Window targetWindow)
  2005. {
  2006. XClientMessageEvent msg;
  2007. zerostruct (msg);
  2008. msg.message_type = Atoms::get().XdndLeave;
  2009. sendExternalDragAndDropMessage (msg, targetWindow);
  2010. }
  2011. void sendDragAndDropFinish()
  2012. {
  2013. XClientMessageEvent msg;
  2014. zerostruct (msg);
  2015. msg.message_type = Atoms::get().XdndFinished;
  2016. sendDragAndDropMessage (msg);
  2017. }
  2018. void handleExternalSelectionClear()
  2019. {
  2020. if (dragState.dragging)
  2021. externalResetDragAndDrop();
  2022. }
  2023. void handleExternalSelectionRequest (const XEvent& evt)
  2024. {
  2025. Atom targetType = evt.xselectionrequest.target;
  2026. XEvent s;
  2027. s.xselection.type = SelectionNotify;
  2028. s.xselection.requestor = evt.xselectionrequest.requestor;
  2029. s.xselection.selection = evt.xselectionrequest.selection;
  2030. s.xselection.target = targetType;
  2031. s.xselection.property = None;
  2032. s.xselection.time = evt.xselectionrequest.time;
  2033. if (dragState.matchesTarget (targetType))
  2034. {
  2035. s.xselection.property = evt.xselectionrequest.property;
  2036. xchangeProperty (evt.xselectionrequest.requestor,
  2037. evt.xselectionrequest.property,
  2038. targetType, 8,
  2039. dragState.textOrFiles.toUTF8().getAddress(),
  2040. dragState.textOrFiles.getNumBytesAsUTF8());
  2041. }
  2042. XSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
  2043. }
  2044. void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
  2045. {
  2046. if (dragState.expectingStatus)
  2047. {
  2048. dragState.expectingStatus = false;
  2049. dragState.canDrop = false;
  2050. dragState.silentRect = Rectangle<int>();
  2051. if ((clientMsg.data.l[1] & 1) != 0
  2052. && ((Atom) clientMsg.data.l[4] == Atoms::get().XdndActionCopy
  2053. || (Atom) clientMsg.data.l[4] == Atoms::get().XdndActionPrivate))
  2054. {
  2055. if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
  2056. dragState.silentRect.setBounds (clientMsg.data.l[2] >> 16,
  2057. clientMsg.data.l[2] & 0xffff,
  2058. clientMsg.data.l[3] >> 16,
  2059. clientMsg.data.l[3] & 0xffff);
  2060. dragState.canDrop = true;
  2061. }
  2062. }
  2063. }
  2064. void handleExternalDragButtonReleaseEvent()
  2065. {
  2066. if (dragState.dragging)
  2067. XUngrabPointer (display, CurrentTime);
  2068. if (dragState.canDrop)
  2069. {
  2070. sendExternalDragAndDropDrop (dragState.targetWindow);
  2071. }
  2072. else
  2073. {
  2074. sendExternalDragAndDropLeave (dragState.targetWindow);
  2075. externalResetDragAndDrop();
  2076. }
  2077. }
  2078. void handleExternalDragMotionNotify()
  2079. {
  2080. Window targetWindow = externalFindDragTargetWindow (RootWindow (display, DefaultScreen (display)));
  2081. if (dragState.targetWindow != targetWindow)
  2082. {
  2083. if (dragState.targetWindow != None)
  2084. sendExternalDragAndDropLeave (dragState.targetWindow);
  2085. dragState.canDrop = false;
  2086. dragState.silentRect = Rectangle<int>();
  2087. if (targetWindow == None)
  2088. return;
  2089. GetXProperty prop (targetWindow, Atoms::get().XdndAware,
  2090. 0, 2, false, AnyPropertyType);
  2091. if (prop.success
  2092. && prop.data != None
  2093. && prop.actualFormat == 32
  2094. && prop.numItems == 1)
  2095. {
  2096. dragState.xdndVersion = jmin ((int) prop.data[0], (int) Atoms::DndVersion);
  2097. }
  2098. else
  2099. {
  2100. dragState.xdndVersion = -1;
  2101. return;
  2102. }
  2103. sendExternalDragAndDropEnter (targetWindow);
  2104. dragState.targetWindow = targetWindow;
  2105. }
  2106. if (! dragState.expectingStatus)
  2107. sendExternalDragAndDropPosition (targetWindow);
  2108. }
  2109. void handleDragAndDropPosition (const XClientMessageEvent& clientMsg)
  2110. {
  2111. if (dragAndDropSourceWindow == 0)
  2112. return;
  2113. dragAndDropSourceWindow = clientMsg.data.l[0];
  2114. Point<int> dropPos ((int) clientMsg.data.l[2] >> 16,
  2115. (int) clientMsg.data.l[2] & 0xffff);
  2116. dropPos -= getScreenPosition();
  2117. const Atoms& atoms = Atoms::get();
  2118. Atom targetAction = atoms.XdndActionCopy;
  2119. for (int i = numElementsInArray (atoms.allowedActions); --i >= 0;)
  2120. {
  2121. if ((Atom) clientMsg.data.l[4] == atoms.allowedActions[i])
  2122. {
  2123. targetAction = atoms.allowedActions[i];
  2124. break;
  2125. }
  2126. }
  2127. sendDragAndDropStatus (true, targetAction);
  2128. if (dragInfo.position != dropPos)
  2129. {
  2130. dragInfo.position = dropPos;
  2131. if (dragInfo.isEmpty())
  2132. updateDraggedFileList (clientMsg);
  2133. if (! dragInfo.isEmpty())
  2134. handleDragMove (dragInfo);
  2135. }
  2136. }
  2137. void handleDragAndDropDrop (const XClientMessageEvent& clientMsg)
  2138. {
  2139. if (dragInfo.isEmpty())
  2140. {
  2141. // no data, transaction finished in handleDragAndDropSelection()
  2142. finishAfterDropDataReceived = true;
  2143. updateDraggedFileList (clientMsg);
  2144. }
  2145. else
  2146. {
  2147. handleDragAndDropDataReceived(); // data was already received
  2148. }
  2149. }
  2150. void handleDragAndDropDataReceived()
  2151. {
  2152. DragInfo dragInfoCopy (dragInfo);
  2153. sendDragAndDropFinish();
  2154. resetDragAndDrop();
  2155. if (! dragInfoCopy.isEmpty())
  2156. handleDragDrop (dragInfoCopy);
  2157. }
  2158. void handleDragAndDropEnter (const XClientMessageEvent& clientMsg)
  2159. {
  2160. dragInfo.clear();
  2161. srcMimeTypeAtomList.clear();
  2162. dragAndDropCurrentMimeType = 0;
  2163. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg.data.l[1] & 0xff000000) >> 24;
  2164. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  2165. {
  2166. dragAndDropSourceWindow = 0;
  2167. return;
  2168. }
  2169. dragAndDropSourceWindow = clientMsg.data.l[0];
  2170. if ((clientMsg.data.l[1] & 1) != 0)
  2171. {
  2172. ScopedXLock xlock;
  2173. GetXProperty prop (dragAndDropSourceWindow, Atoms::get().XdndTypeList, 0, 0x8000000L, false, XA_ATOM);
  2174. if (prop.success
  2175. && prop.actualType == XA_ATOM
  2176. && prop.actualFormat == 32
  2177. && prop.numItems != 0)
  2178. {
  2179. const unsigned long* const types = (const unsigned long*) prop.data;
  2180. for (unsigned long i = 0; i < prop.numItems; ++i)
  2181. if (types[i] != None)
  2182. srcMimeTypeAtomList.add (types[i]);
  2183. }
  2184. }
  2185. if (srcMimeTypeAtomList.size() == 0)
  2186. {
  2187. for (int i = 2; i < 5; ++i)
  2188. if (clientMsg.data.l[i] != None)
  2189. srcMimeTypeAtomList.add (clientMsg.data.l[i]);
  2190. if (srcMimeTypeAtomList.size() == 0)
  2191. {
  2192. dragAndDropSourceWindow = 0;
  2193. return;
  2194. }
  2195. }
  2196. const Atoms& atoms = Atoms::get();
  2197. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  2198. for (int j = 0; j < numElementsInArray (atoms.allowedMimeTypes); ++j)
  2199. if (srcMimeTypeAtomList[i] == atoms.allowedMimeTypes[j])
  2200. dragAndDropCurrentMimeType = atoms.allowedMimeTypes[j];
  2201. handleDragAndDropPosition (clientMsg);
  2202. }
  2203. void handleDragAndDropSelection (const XEvent& evt)
  2204. {
  2205. dragInfo.clear();
  2206. if (evt.xselection.property != None)
  2207. {
  2208. StringArray lines;
  2209. {
  2210. MemoryBlock dropData;
  2211. for (;;)
  2212. {
  2213. GetXProperty prop (evt.xany.window, evt.xselection.property,
  2214. dropData.getSize() / 4, 65536, false, AnyPropertyType);
  2215. if (! prop.success)
  2216. break;
  2217. dropData.append (prop.data, prop.numItems * prop.actualFormat / 8);
  2218. if (prop.bytesLeft <= 0)
  2219. break;
  2220. }
  2221. lines.addLines (dropData.toString());
  2222. }
  2223. if (Atoms::isMimeTypeFile (dragAndDropCurrentMimeType))
  2224. {
  2225. for (int i = 0; i < lines.size(); ++i)
  2226. dragInfo.files.add (URL::removeEscapeChars (lines[i].replace ("file://", String::empty, true)));
  2227. dragInfo.files.trim();
  2228. dragInfo.files.removeEmptyStrings();
  2229. }
  2230. else
  2231. {
  2232. dragInfo.text = lines.joinIntoString ("\n");
  2233. }
  2234. if (finishAfterDropDataReceived)
  2235. handleDragAndDropDataReceived();
  2236. }
  2237. }
  2238. void updateDraggedFileList (const XClientMessageEvent& clientMsg)
  2239. {
  2240. jassert (dragInfo.isEmpty());
  2241. if (dragAndDropSourceWindow != None
  2242. && dragAndDropCurrentMimeType != None)
  2243. {
  2244. ScopedXLock xlock;
  2245. XConvertSelection (display,
  2246. Atoms::get().XdndSelection,
  2247. dragAndDropCurrentMimeType,
  2248. Atoms::getCreating ("JXSelectionWindowProperty"),
  2249. windowH,
  2250. clientMsg.data.l[2]);
  2251. }
  2252. }
  2253. static bool isWindowDnDAware (Window w)
  2254. {
  2255. int numProperties = 0;
  2256. Atom* const atoms = XListProperties (display, w, &numProperties);
  2257. bool dndAwarePropFound = false;
  2258. for (int i = 0; i < numProperties; ++i)
  2259. if (atoms[i] == Atoms::get().XdndAware)
  2260. dndAwarePropFound = true;
  2261. if (atoms != nullptr)
  2262. XFree (atoms);
  2263. return dndAwarePropFound;
  2264. }
  2265. Window externalFindDragTargetWindow (Window targetWindow)
  2266. {
  2267. if (targetWindow == None)
  2268. return None;
  2269. if (isWindowDnDAware (targetWindow))
  2270. return targetWindow;
  2271. Window child, phonyWin;
  2272. int phony;
  2273. unsigned int uphony;
  2274. XQueryPointer (display, targetWindow, &phonyWin, &child,
  2275. &phony, &phony, &phony, &phony, &uphony);
  2276. return externalFindDragTargetWindow (child);
  2277. }
  2278. bool externalDragInit (bool isText, const String& textOrFiles)
  2279. {
  2280. ScopedXLock xlock;
  2281. resetExternalDragState();
  2282. dragState.isText = isText;
  2283. dragState.textOrFiles = textOrFiles;
  2284. dragState.targetWindow = windowH;
  2285. const int pointerGrabMask = Button1MotionMask | ButtonReleaseMask;
  2286. if (XGrabPointer (display, windowH, True, pointerGrabMask,
  2287. GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
  2288. {
  2289. // No other method of changing the pointer seems to work, this call is needed from this very context
  2290. XChangeActivePointerGrab (display, pointerGrabMask, (Cursor) createDraggingHandCursor(), CurrentTime);
  2291. const Atoms& atoms = Atoms::get();
  2292. XSetSelectionOwner (display, atoms.XdndSelection, windowH, CurrentTime);
  2293. // save the available types to XdndTypeList
  2294. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32,
  2295. dragState.getMimeTypes(),
  2296. dragState.getNumMimeTypes());
  2297. dragState.dragging = true;
  2298. handleExternalDragMotionNotify();
  2299. return true;
  2300. }
  2301. return false;
  2302. }
  2303. void externalResetDragAndDrop()
  2304. {
  2305. if (dragState.dragging)
  2306. {
  2307. ScopedXLock xlock;
  2308. XUngrabPointer (display, CurrentTime);
  2309. }
  2310. resetExternalDragState();
  2311. }
  2312. DragState dragState;
  2313. DragInfo dragInfo;
  2314. Atom dragAndDropCurrentMimeType;
  2315. Window dragAndDropSourceWindow;
  2316. bool finishAfterDropDataReceived;
  2317. Array <Atom> srcMimeTypeAtomList;
  2318. int pointerMap[5];
  2319. void initialisePointerMap()
  2320. {
  2321. const int numButtons = XGetPointerMapping (display, 0, 0);
  2322. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2323. if (numButtons == 2)
  2324. {
  2325. pointerMap[0] = Keys::LeftButton;
  2326. pointerMap[1] = Keys::RightButton;
  2327. }
  2328. else if (numButtons >= 3)
  2329. {
  2330. pointerMap[0] = Keys::LeftButton;
  2331. pointerMap[1] = Keys::MiddleButton;
  2332. pointerMap[2] = Keys::RightButton;
  2333. if (numButtons >= 5)
  2334. {
  2335. pointerMap[3] = Keys::WheelUp;
  2336. pointerMap[4] = Keys::WheelDown;
  2337. }
  2338. }
  2339. }
  2340. static Point<int> lastMousePos;
  2341. static void clearLastMousePos() noexcept
  2342. {
  2343. lastMousePos = Point<int> (0x100000, 0x100000);
  2344. }
  2345. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  2346. };
  2347. ModifierKeys LinuxComponentPeer::currentModifiers;
  2348. bool LinuxComponentPeer::isActiveApplication = false;
  2349. Point<int> LinuxComponentPeer::lastMousePos;
  2350. //==============================================================================
  2351. bool Process::isForegroundProcess()
  2352. {
  2353. return LinuxComponentPeer::isActiveApplication;
  2354. }
  2355. void Process::makeForegroundProcess()
  2356. {
  2357. }
  2358. //==============================================================================
  2359. void ModifierKeys::updateCurrentModifiers() noexcept
  2360. {
  2361. currentModifiers = LinuxComponentPeer::currentModifiers;
  2362. }
  2363. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2364. {
  2365. Window root, child;
  2366. int x, y, winx, winy;
  2367. unsigned int mask;
  2368. int mouseMods = 0;
  2369. ScopedXLock xlock;
  2370. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  2371. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  2372. {
  2373. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  2374. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  2375. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  2376. }
  2377. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2378. return LinuxComponentPeer::currentModifiers;
  2379. }
  2380. //==============================================================================
  2381. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /* allowMenusAndBars */)
  2382. {
  2383. if (enableOrDisable)
  2384. kioskModeComponent->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  2385. }
  2386. //==============================================================================
  2387. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  2388. {
  2389. return new LinuxComponentPeer (*this, styleFlags, (Window) nativeWindowToAttachTo);
  2390. }
  2391. //==============================================================================
  2392. void Desktop::Displays::findDisplays()
  2393. {
  2394. if (display == 0)
  2395. return;
  2396. ScopedXLock xlock;
  2397. #if JUCE_USE_XINERAMA
  2398. int major_opcode, first_event, first_error;
  2399. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  2400. {
  2401. typedef Bool (*tXineramaIsActive) (::Display*);
  2402. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (::Display*, int*);
  2403. static tXineramaIsActive xineramaIsActive = nullptr;
  2404. static tXineramaQueryScreens xineramaQueryScreens = nullptr;
  2405. if (xineramaIsActive == nullptr || xineramaQueryScreens == nullptr)
  2406. {
  2407. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  2408. if (h == nullptr)
  2409. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  2410. if (h != nullptr)
  2411. {
  2412. xineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  2413. xineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  2414. }
  2415. }
  2416. if (xineramaIsActive != nullptr
  2417. && xineramaQueryScreens != nullptr
  2418. && xineramaIsActive (display))
  2419. {
  2420. int numMonitors = 0;
  2421. if (XineramaScreenInfo* const screens = xineramaQueryScreens (display, &numMonitors))
  2422. {
  2423. for (int index = 0; index < numMonitors; ++index)
  2424. {
  2425. for (int j = numMonitors; --j >= 0;)
  2426. {
  2427. if (screens[j].screen_number == index)
  2428. {
  2429. Display d;
  2430. d.userArea = d.totalArea = Rectangle<int> (screens[j].x_org,
  2431. screens[j].y_org,
  2432. screens[j].width,
  2433. screens[j].height);
  2434. d.isMain = (index == 0);
  2435. d.scale = 1.0;
  2436. displays.add (d);
  2437. }
  2438. }
  2439. }
  2440. XFree (screens);
  2441. }
  2442. }
  2443. }
  2444. if (displays.size() == 0)
  2445. #endif
  2446. {
  2447. Atom hints = Atoms::getIfExists ("_NET_WORKAREA");
  2448. if (hints != None)
  2449. {
  2450. const int numMonitors = ScreenCount (display);
  2451. for (int i = 0; i < numMonitors; ++i)
  2452. {
  2453. GetXProperty prop (RootWindow (display, i), hints, 0, 4, false, XA_CARDINAL);
  2454. if (prop.success && prop.actualType == XA_CARDINAL && prop.actualFormat == 32 && prop.numItems == 4)
  2455. {
  2456. const long* const position = (const long*) prop.data;
  2457. Display d;
  2458. d.userArea = d.totalArea = Rectangle<int> (position[0], position[1],
  2459. position[2], position[3]);
  2460. d.isMain = (displays.size() == 0);
  2461. d.scale = 1.0;
  2462. displays.add (d);
  2463. }
  2464. }
  2465. }
  2466. if (displays.size() == 0)
  2467. {
  2468. Display d;
  2469. d.userArea = d.totalArea = Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  2470. DisplayHeight (display, DefaultScreen (display)));
  2471. d.isMain = true;
  2472. d.scale = 1.0;
  2473. displays.add (d);
  2474. }
  2475. }
  2476. }
  2477. //==============================================================================
  2478. bool Desktop::addMouseInputSource()
  2479. {
  2480. if (mouseSources.size() == 0)
  2481. {
  2482. mouseSources.add (new MouseInputSource (0, true));
  2483. return true;
  2484. }
  2485. return false;
  2486. }
  2487. bool Desktop::canUseSemiTransparentWindows() noexcept
  2488. {
  2489. int matchedDepth = 0;
  2490. const int desiredDepth = 32;
  2491. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  2492. && (matchedDepth == desiredDepth);
  2493. }
  2494. Point<int> MouseInputSource::getCurrentMousePosition()
  2495. {
  2496. Window root, child;
  2497. int x, y, winx, winy;
  2498. unsigned int mask;
  2499. ScopedXLock xlock;
  2500. if (XQueryPointer (display,
  2501. RootWindow (display, DefaultScreen (display)),
  2502. &root, &child,
  2503. &x, &y, &winx, &winy, &mask) == False)
  2504. {
  2505. // Pointer not on the default screen
  2506. x = y = -1;
  2507. }
  2508. return Point<int> (x, y);
  2509. }
  2510. void Desktop::setMousePosition (const Point<int>& newPosition)
  2511. {
  2512. ScopedXLock xlock;
  2513. Window root = RootWindow (display, DefaultScreen (display));
  2514. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  2515. }
  2516. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  2517. {
  2518. return upright;
  2519. }
  2520. //==============================================================================
  2521. static bool screenSaverAllowed = true;
  2522. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  2523. {
  2524. if (screenSaverAllowed != isEnabled)
  2525. {
  2526. screenSaverAllowed = isEnabled;
  2527. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  2528. static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
  2529. if (xScreenSaverSuspend == nullptr)
  2530. if (void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW))
  2531. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  2532. ScopedXLock xlock;
  2533. if (xScreenSaverSuspend != nullptr)
  2534. xScreenSaverSuspend (display, ! isEnabled);
  2535. }
  2536. }
  2537. bool Desktop::isScreenSaverEnabled()
  2538. {
  2539. return screenSaverAllowed;
  2540. }
  2541. //==============================================================================
  2542. bool juce_areThereAnyAlwaysOnTopWindows()
  2543. {
  2544. return false; // XXX should be implemented
  2545. }
  2546. //==============================================================================
  2547. void* CustomMouseCursorInfo::create() const
  2548. {
  2549. ScopedXLock xlock;
  2550. const unsigned int imageW = image.getWidth();
  2551. const unsigned int imageH = image.getHeight();
  2552. int hotspotX = hotspot.x;
  2553. int hotspotY = hotspot.y;
  2554. #if JUCE_USE_XCURSOR
  2555. {
  2556. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  2557. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  2558. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  2559. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  2560. static tXcursorSupportsARGB xcursorSupportsARGB = nullptr;
  2561. static tXcursorImageCreate xcursorImageCreate = nullptr;
  2562. static tXcursorImageDestroy xcursorImageDestroy = nullptr;
  2563. static tXcursorImageLoadCursor xcursorImageLoadCursor = nullptr;
  2564. static bool hasBeenLoaded = false;
  2565. if (! hasBeenLoaded)
  2566. {
  2567. hasBeenLoaded = true;
  2568. if (void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW))
  2569. {
  2570. xcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  2571. xcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  2572. xcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  2573. xcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  2574. if (xcursorSupportsARGB == nullptr || xcursorImageCreate == nullptr
  2575. || xcursorImageLoadCursor == nullptr || xcursorImageDestroy == nullptr
  2576. || ! xcursorSupportsARGB (display))
  2577. xcursorSupportsARGB = nullptr;
  2578. }
  2579. }
  2580. if (xcursorSupportsARGB != nullptr)
  2581. {
  2582. if (XcursorImage* xcImage = xcursorImageCreate (imageW, imageH))
  2583. {
  2584. xcImage->xhot = hotspotX;
  2585. xcImage->yhot = hotspotY;
  2586. XcursorPixel* dest = xcImage->pixels;
  2587. for (int y = 0; y < (int) imageH; ++y)
  2588. for (int x = 0; x < (int) imageW; ++x)
  2589. *dest++ = image.getPixelAt (x, y).getARGB();
  2590. void* result = (void*) xcursorImageLoadCursor (display, xcImage);
  2591. xcursorImageDestroy (xcImage);
  2592. if (result != nullptr)
  2593. return result;
  2594. }
  2595. }
  2596. }
  2597. #endif
  2598. Window root = RootWindow (display, DefaultScreen (display));
  2599. unsigned int cursorW, cursorH;
  2600. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  2601. return nullptr;
  2602. Image im (Image::ARGB, cursorW, cursorH, true);
  2603. {
  2604. Graphics g (im);
  2605. if (imageW > cursorW || imageH > cursorH)
  2606. {
  2607. hotspotX = (hotspotX * cursorW) / imageW;
  2608. hotspotY = (hotspotY * cursorH) / imageH;
  2609. g.drawImageWithin (image, 0, 0, imageW, imageH,
  2610. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  2611. false);
  2612. }
  2613. else
  2614. {
  2615. g.drawImageAt (image, 0, 0);
  2616. }
  2617. }
  2618. const int stride = (cursorW + 7) >> 3;
  2619. HeapBlock <char> maskPlane, sourcePlane;
  2620. maskPlane.calloc (stride * cursorH);
  2621. sourcePlane.calloc (stride * cursorH);
  2622. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  2623. for (int y = cursorH; --y >= 0;)
  2624. {
  2625. for (int x = cursorW; --x >= 0;)
  2626. {
  2627. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  2628. const int offset = y * stride + (x >> 3);
  2629. const Colour c (im.getPixelAt (x, y));
  2630. if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
  2631. if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
  2632. }
  2633. }
  2634. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2635. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2636. XColor white, black;
  2637. black.red = black.green = black.blue = 0;
  2638. white.red = white.green = white.blue = 0xffff;
  2639. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  2640. XFreePixmap (display, sourcePixmap);
  2641. XFreePixmap (display, maskPixmap);
  2642. return result;
  2643. }
  2644. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  2645. {
  2646. ScopedXLock xlock;
  2647. if (cursorHandle != nullptr)
  2648. XFreeCursor (display, (Cursor) cursorHandle);
  2649. }
  2650. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  2651. {
  2652. unsigned int shape;
  2653. switch (type)
  2654. {
  2655. case NormalCursor:
  2656. case ParentCursor: return None; // Use parent cursor
  2657. case NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), 0, 0).create();
  2658. case WaitCursor: shape = XC_watch; break;
  2659. case IBeamCursor: shape = XC_xterm; break;
  2660. case PointingHandCursor: shape = XC_hand2; break;
  2661. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  2662. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  2663. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  2664. case TopEdgeResizeCursor: shape = XC_top_side; break;
  2665. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  2666. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  2667. case RightEdgeResizeCursor: shape = XC_right_side; break;
  2668. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  2669. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  2670. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  2671. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  2672. case CrosshairCursor: shape = XC_crosshair; break;
  2673. case DraggingHandCursor: return createDraggingHandCursor();
  2674. case CopyingCursor:
  2675. {
  2676. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  2677. 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,
  2678. 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,
  2679. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  2680. const int copyCursorSize = 119;
  2681. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
  2682. }
  2683. default:
  2684. jassertfalse;
  2685. return None;
  2686. }
  2687. ScopedXLock xlock;
  2688. return (void*) XCreateFontCursor (display, shape);
  2689. }
  2690. void MouseCursor::showInWindow (ComponentPeer* peer) const
  2691. {
  2692. if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer))
  2693. lp->showMouseCursor ((Cursor) getHandle());
  2694. }
  2695. void MouseCursor::showInAllWindows() const
  2696. {
  2697. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  2698. showInWindow (ComponentPeer::getPeer (i));
  2699. }
  2700. //==============================================================================
  2701. Image juce_createIconForFile (const File& /* file */)
  2702. {
  2703. return Image::null;
  2704. }
  2705. //==============================================================================
  2706. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  2707. {
  2708. if (files.size() == 0)
  2709. return false;
  2710. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  2711. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  2712. if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (sourceComp->getPeer()))
  2713. return lp->externalDragFileInit (files, canMoveFiles);
  2714. // This method must be called in response to a component's mouseDown or mouseDrag event!
  2715. jassertfalse;
  2716. return false;
  2717. }
  2718. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2719. {
  2720. if (text.isEmpty())
  2721. return false;
  2722. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  2723. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  2724. if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (sourceComp->getPeer()))
  2725. return lp->externalDragTextInit (text);
  2726. // This method must be called in response to a component's mouseDown or mouseDrag event!
  2727. jassertfalse;
  2728. return false;
  2729. }
  2730. //==============================================================================
  2731. void LookAndFeel::playAlertSound()
  2732. {
  2733. std::cout << "\a" << std::flush;
  2734. }
  2735. //==============================================================================
  2736. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  2737. const String& title, const String& message,
  2738. Component* /* associatedComponent */)
  2739. {
  2740. AlertWindow::showMessageBox (iconType, title, message);
  2741. }
  2742. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  2743. const String& title, const String& message,
  2744. Component* associatedComponent,
  2745. ModalComponentManager::Callback* callback)
  2746. {
  2747. AlertWindow::showMessageBoxAsync (iconType, title, message, String::empty, associatedComponent, callback);
  2748. }
  2749. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  2750. const String& title, const String& message,
  2751. Component* associatedComponent,
  2752. ModalComponentManager::Callback* callback)
  2753. {
  2754. return AlertWindow::showOkCancelBox (iconType, title, message, String::empty, String::empty,
  2755. associatedComponent, callback);
  2756. }
  2757. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  2758. const String& title, const String& message,
  2759. Component* associatedComponent,
  2760. ModalComponentManager::Callback* callback)
  2761. {
  2762. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  2763. String::empty, String::empty, String::empty,
  2764. associatedComponent, callback);
  2765. }
  2766. //==============================================================================
  2767. const int KeyPress::spaceKey = XK_space & 0xff;
  2768. const int KeyPress::returnKey = XK_Return & 0xff;
  2769. const int KeyPress::escapeKey = XK_Escape & 0xff;
  2770. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  2771. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  2772. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  2773. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  2774. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  2775. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  2776. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  2777. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  2778. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  2779. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  2780. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  2781. const int KeyPress::tabKey = XK_Tab & 0xff;
  2782. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  2783. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  2784. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  2785. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  2786. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  2787. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  2788. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  2789. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  2790. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  2791. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  2792. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  2793. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  2794. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  2795. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  2796. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  2797. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  2798. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  2799. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  2800. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  2801. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  2802. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  2803. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  2804. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  2805. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  2806. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  2807. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  2808. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  2809. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  2810. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  2811. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  2812. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  2813. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  2814. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  2815. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  2816. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  2817. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  2818. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  2819. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;