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.

3487 lines
123KB

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