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.

3480 lines
122KB

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