The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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