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.

3490 lines
123KB

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