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. peer.clearMaskedRegion();
  1515. RectangleList<int> originalRepaintRegion (regionsNeedingRepaint);
  1516. regionsNeedingRepaint.clear();
  1517. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  1518. if (! totalArea.isEmpty())
  1519. {
  1520. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  1521. || image.getHeight() < totalArea.getHeight())
  1522. {
  1523. #if JUCE_USE_XSHM
  1524. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  1525. : Image::RGB,
  1526. #else
  1527. image = Image (new XBitmapImage (Image::RGB,
  1528. #endif
  1529. (totalArea.getWidth() + 31) & ~31,
  1530. (totalArea.getHeight() + 31) & ~31,
  1531. false, peer.depth, peer.visual));
  1532. }
  1533. startTimer (repaintTimerPeriod);
  1534. RectangleList<int> adjustedList (originalRepaintRegion);
  1535. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  1536. if (peer.depth == 32)
  1537. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  1538. image.clear (*i - totalArea.getPosition());
  1539. {
  1540. ScopedPointer<LowLevelGraphicsContext> context (peer.getComponent().getLookAndFeel()
  1541. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList));
  1542. peer.handlePaint (*context);
  1543. }
  1544. if (! peer.maskedRegion.isEmpty())
  1545. originalRepaintRegion.subtract (peer.maskedRegion);
  1546. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  1547. {
  1548. #if JUCE_USE_XSHM
  1549. ++shmPaintsPending;
  1550. #endif
  1551. static_cast<XBitmapImage*> (image.getPixelData())
  1552. ->blitToWindow (peer.windowH,
  1553. i->getX(), i->getY(), i->getWidth(), i->getHeight(),
  1554. i->getX() - totalArea.getX(), i->getY() - totalArea.getY());
  1555. }
  1556. }
  1557. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  1558. startTimer (repaintTimerPeriod);
  1559. }
  1560. #if JUCE_USE_XSHM
  1561. void notifyPaintCompleted() noexcept { --shmPaintsPending; }
  1562. #endif
  1563. private:
  1564. enum { repaintTimerPeriod = 1000 / 100 };
  1565. LinuxComponentPeer& peer;
  1566. Image image;
  1567. uint32 lastTimeImageUsed;
  1568. RectangleList<int> regionsNeedingRepaint;
  1569. #if JUCE_USE_XSHM
  1570. bool useARGBImagesForRendering;
  1571. int shmPaintsPending;
  1572. #endif
  1573. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  1574. };
  1575. ScopedPointer <LinuxRepaintManager> repainter;
  1576. friend class LinuxRepaintManager;
  1577. Window windowH, parentWindow;
  1578. Rectangle<int> bounds;
  1579. Image taskbarImage;
  1580. bool fullScreen, mapped;
  1581. Visual* visual;
  1582. int depth;
  1583. BorderSize<int> windowBorder;
  1584. bool isAlwaysOnTop;
  1585. enum { KeyPressEventType = 2 };
  1586. struct MotifWmHints
  1587. {
  1588. unsigned long flags;
  1589. unsigned long functions;
  1590. unsigned long decorations;
  1591. long input_mode;
  1592. unsigned long status;
  1593. };
  1594. static void updateKeyStates (const int keycode, const bool press) noexcept
  1595. {
  1596. const int keybyte = keycode >> 3;
  1597. const int keybit = (1 << (keycode & 7));
  1598. if (press)
  1599. Keys::keyStates [keybyte] |= keybit;
  1600. else
  1601. Keys::keyStates [keybyte] &= ~keybit;
  1602. }
  1603. static void updateKeyModifiers (const int status) noexcept
  1604. {
  1605. int keyMods = 0;
  1606. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  1607. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  1608. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  1609. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1610. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  1611. Keys::capsLock = ((status & LockMask) != 0);
  1612. }
  1613. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) noexcept
  1614. {
  1615. int modifier = 0;
  1616. bool isModifier = true;
  1617. switch (sym)
  1618. {
  1619. case XK_Shift_L:
  1620. case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
  1621. case XK_Control_L:
  1622. case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
  1623. case XK_Alt_L:
  1624. case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
  1625. case XK_Num_Lock:
  1626. if (press)
  1627. Keys::numLock = ! Keys::numLock;
  1628. break;
  1629. case XK_Caps_Lock:
  1630. if (press)
  1631. Keys::capsLock = ! Keys::capsLock;
  1632. break;
  1633. case XK_Scroll_Lock:
  1634. break;
  1635. default:
  1636. isModifier = false;
  1637. break;
  1638. }
  1639. currentModifiers = press ? currentModifiers.withFlags (modifier)
  1640. : currentModifiers.withoutFlags (modifier);
  1641. return isModifier;
  1642. }
  1643. // Alt and Num lock are not defined by standard X
  1644. // modifier constants: check what they're mapped to
  1645. static void updateModifierMappings() noexcept
  1646. {
  1647. ScopedXLock xlock;
  1648. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  1649. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  1650. Keys::AltMask = 0;
  1651. Keys::NumLockMask = 0;
  1652. if (XModifierKeymap* const mapping = XGetModifierMapping (display))
  1653. {
  1654. for (int i = 0; i < 8; i++)
  1655. {
  1656. if (mapping->modifiermap [i << 1] == altLeftCode)
  1657. Keys::AltMask = 1 << i;
  1658. else if (mapping->modifiermap [i << 1] == numLockCode)
  1659. Keys::NumLockMask = 1 << i;
  1660. }
  1661. XFreeModifiermap (mapping);
  1662. }
  1663. }
  1664. //==============================================================================
  1665. static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
  1666. {
  1667. XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  1668. }
  1669. void removeWindowDecorations (Window wndH)
  1670. {
  1671. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  1672. if (hints != None)
  1673. {
  1674. MotifWmHints motifHints;
  1675. zerostruct (motifHints);
  1676. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  1677. motifHints.decorations = 0;
  1678. ScopedXLock xlock;
  1679. xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
  1680. }
  1681. hints = Atoms::getIfExists ("_WIN_HINTS");
  1682. if (hints != None)
  1683. {
  1684. long gnomeHints = 0;
  1685. ScopedXLock xlock;
  1686. xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
  1687. }
  1688. hints = Atoms::getIfExists ("KWM_WIN_DECORATION");
  1689. if (hints != None)
  1690. {
  1691. long kwmHints = 2; /*KDE_tinyDecoration*/
  1692. ScopedXLock xlock;
  1693. xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
  1694. }
  1695. }
  1696. void addWindowButtons (Window wndH)
  1697. {
  1698. ScopedXLock xlock;
  1699. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  1700. if (hints != None)
  1701. {
  1702. MotifWmHints motifHints;
  1703. zerostruct (motifHints);
  1704. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  1705. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  1706. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  1707. if ((styleFlags & windowHasCloseButton) != 0)
  1708. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  1709. if ((styleFlags & windowHasMinimiseButton) != 0)
  1710. {
  1711. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  1712. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  1713. }
  1714. if ((styleFlags & windowHasMaximiseButton) != 0)
  1715. {
  1716. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  1717. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  1718. }
  1719. if ((styleFlags & windowIsResizable) != 0)
  1720. {
  1721. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  1722. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  1723. }
  1724. xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
  1725. }
  1726. hints = Atoms::getIfExists ("_NET_WM_ALLOWED_ACTIONS");
  1727. if (hints != None)
  1728. {
  1729. Atom netHints [6];
  1730. int num = 0;
  1731. if ((styleFlags & windowIsResizable) != 0)
  1732. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_RESIZE");
  1733. if ((styleFlags & windowHasMaximiseButton) != 0)
  1734. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_FULLSCREEN");
  1735. if ((styleFlags & windowHasMinimiseButton) != 0)
  1736. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_MINIMIZE");
  1737. if ((styleFlags & windowHasCloseButton) != 0)
  1738. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_CLOSE");
  1739. xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
  1740. }
  1741. }
  1742. void setWindowType()
  1743. {
  1744. Atom netHints [2];
  1745. if ((styleFlags & windowIsTemporary) != 0
  1746. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  1747. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_COMBO");
  1748. else
  1749. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_NORMAL");
  1750. netHints[1] = Atoms::getIfExists ("_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  1751. xchangeProperty (windowH, Atoms::get().WindowType, XA_ATOM, 32, &netHints, 2);
  1752. int numHints = 0;
  1753. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1754. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_SKIP_TASKBAR");
  1755. if (component.isAlwaysOnTop())
  1756. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_ABOVE");
  1757. if (numHints > 0)
  1758. xchangeProperty (windowH, Atoms::get().WindowState, XA_ATOM, 32, &netHints, numHints);
  1759. }
  1760. void createWindow (Window parentToAddTo)
  1761. {
  1762. ScopedXLock xlock;
  1763. resetDragAndDrop();
  1764. // Get defaults for various properties
  1765. const int screen = DefaultScreen (display);
  1766. Window root = RootWindow (display, screen);
  1767. // Try to obtain a 32-bit visual or fallback to 24 or 16
  1768. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  1769. if (visual == nullptr)
  1770. {
  1771. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  1772. Process::terminate();
  1773. }
  1774. // Create and install a colormap suitable fr our visual
  1775. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  1776. XInstallColormap (display, colormap);
  1777. // Set up the window attributes
  1778. XSetWindowAttributes swa;
  1779. swa.border_pixel = 0;
  1780. swa.background_pixmap = None;
  1781. swa.colormap = colormap;
  1782. swa.override_redirect = (component.isAlwaysOnTop() && (styleFlags & windowIsTemporary) != 0) ? True : False;
  1783. swa.event_mask = getAllEventsMask();
  1784. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  1785. 0, 0, 1, 1,
  1786. 0, depth, InputOutput, visual,
  1787. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  1788. &swa);
  1789. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  1790. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  1791. GrabModeAsync, GrabModeAsync, None, None);
  1792. // Set the window context to identify the window handle object
  1793. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  1794. {
  1795. // Failed
  1796. jassertfalse;
  1797. Logger::outputDebugString ("Failed to create context information for window.\n");
  1798. XDestroyWindow (display, windowH);
  1799. windowH = 0;
  1800. return;
  1801. }
  1802. // Set window manager hints
  1803. XWMHints* wmHints = XAllocWMHints();
  1804. wmHints->flags = InputHint | StateHint;
  1805. wmHints->input = True; // Locally active input model
  1806. wmHints->initial_state = NormalState;
  1807. XSetWMHints (display, windowH, wmHints);
  1808. XFree (wmHints);
  1809. // Set the window type
  1810. setWindowType();
  1811. // Define decoration
  1812. if ((styleFlags & windowHasTitleBar) == 0)
  1813. removeWindowDecorations (windowH);
  1814. else
  1815. addWindowButtons (windowH);
  1816. setTitle (component.getName());
  1817. const Atoms& atoms = Atoms::get();
  1818. // Associate the PID, allowing to be shut down when something goes wrong
  1819. unsigned long pid = getpid();
  1820. xchangeProperty (windowH, atoms.Pid, XA_CARDINAL, 32, &pid, 1);
  1821. // Set window manager protocols
  1822. xchangeProperty (windowH, atoms.Protocols, XA_ATOM, 32, atoms.ProtocolList, 2);
  1823. // Set drag and drop flags
  1824. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32, atoms.allowedMimeTypes, numElementsInArray (atoms.allowedMimeTypes));
  1825. xchangeProperty (windowH, atoms.XdndActionList, XA_ATOM, 32, atoms.allowedActions, numElementsInArray (atoms.allowedActions));
  1826. xchangeProperty (windowH, atoms.XdndActionDescription, XA_STRING, 8, "", 0);
  1827. xchangeProperty (windowH, atoms.XdndAware, XA_ATOM, 32, &Atoms::DndVersion, 1);
  1828. initialisePointerMap();
  1829. updateModifierMappings();
  1830. }
  1831. void destroyWindow()
  1832. {
  1833. ScopedXLock xlock;
  1834. XPointer handlePointer;
  1835. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  1836. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  1837. XDestroyWindow (display, windowH);
  1838. // Wait for it to complete and then remove any events for this
  1839. // window from the event queue.
  1840. XSync (display, false);
  1841. XEvent event;
  1842. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  1843. {}
  1844. }
  1845. static int getAllEventsMask() noexcept
  1846. {
  1847. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  1848. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  1849. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  1850. }
  1851. template <typename EventType>
  1852. static int64 getEventTime (const EventType& t)
  1853. {
  1854. return getEventTime (t.time);
  1855. }
  1856. static int64 getEventTime (::Time t)
  1857. {
  1858. static int64 eventTimeOffset = 0x12345678;
  1859. const int64 thisMessageTime = t;
  1860. if (eventTimeOffset == 0x12345678)
  1861. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  1862. return eventTimeOffset + thisMessageTime;
  1863. }
  1864. long getUserTime() const
  1865. {
  1866. GetXProperty prop (windowH, Atoms::get().UserTime, 0, 65536, false, XA_CARDINAL);
  1867. return prop.success ? *(long*) prop.data : 0;
  1868. }
  1869. void updateBorderSize()
  1870. {
  1871. if ((styleFlags & windowHasTitleBar) == 0)
  1872. {
  1873. windowBorder = BorderSize<int> (0);
  1874. }
  1875. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  1876. {
  1877. ScopedXLock xlock;
  1878. Atom hints = Atoms::getIfExists ("_NET_FRAME_EXTENTS");
  1879. if (hints != None)
  1880. {
  1881. GetXProperty prop (windowH, hints, 0, 4, false, XA_CARDINAL);
  1882. if (prop.success && prop.actualFormat == 32)
  1883. {
  1884. const unsigned long* const sizes = (const unsigned long*) prop.data;
  1885. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  1886. (int) sizes[3], (int) sizes[1]);
  1887. }
  1888. }
  1889. }
  1890. }
  1891. void updateWindowBounds()
  1892. {
  1893. jassert (windowH != 0);
  1894. if (windowH != 0)
  1895. {
  1896. Window root, child;
  1897. int wx = 0, wy = 0;
  1898. unsigned int ww = 0, wh = 0, bw, depth;
  1899. ScopedXLock xlock;
  1900. if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &depth))
  1901. if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  1902. wx = wy = 0;
  1903. bounds.setBounds (wx, wy, ww, wh);
  1904. }
  1905. }
  1906. //==============================================================================
  1907. struct DragState
  1908. {
  1909. DragState() noexcept
  1910. : isText (false), dragging (false), expectingStatus (false),
  1911. canDrop (false), targetWindow (None), xdndVersion (-1)
  1912. {
  1913. }
  1914. bool isText;
  1915. bool dragging; // currently performing outgoing external dnd as Xdnd source, have grabbed mouse
  1916. bool expectingStatus; // XdndPosition sent, waiting for XdndStatus
  1917. bool canDrop; // target window signals it will accept the drop
  1918. Window targetWindow; // potential drop target
  1919. int xdndVersion; // negotiated version with target
  1920. Rectangle<int> silentRect;
  1921. String textOrFiles;
  1922. const Atom* getMimeTypes() const noexcept { return isText ? Atoms::get().externalAllowedTextMimeTypes
  1923. : Atoms::get().externalAllowedFileMimeTypes; }
  1924. int getNumMimeTypes() const noexcept { return isText ? numElementsInArray (Atoms::get().externalAllowedTextMimeTypes)
  1925. : numElementsInArray (Atoms::get().externalAllowedFileMimeTypes); }
  1926. bool matchesTarget (Atom targetType) const
  1927. {
  1928. for (int i = getNumMimeTypes(); --i >= 0;)
  1929. if (getMimeTypes()[i] == targetType)
  1930. return true;
  1931. return false;
  1932. }
  1933. };
  1934. //==============================================================================
  1935. void resetDragAndDrop()
  1936. {
  1937. dragInfo.clear();
  1938. dragInfo.position = Point<int> (-1, -1);
  1939. dragAndDropCurrentMimeType = 0;
  1940. dragAndDropSourceWindow = 0;
  1941. srcMimeTypeAtomList.clear();
  1942. finishAfterDropDataReceived = false;
  1943. }
  1944. void resetExternalDragState()
  1945. {
  1946. dragState = DragState();
  1947. }
  1948. void sendDragAndDropMessage (XClientMessageEvent& msg)
  1949. {
  1950. msg.type = ClientMessage;
  1951. msg.display = display;
  1952. msg.window = dragAndDropSourceWindow;
  1953. msg.format = 32;
  1954. msg.data.l[0] = windowH;
  1955. ScopedXLock xlock;
  1956. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  1957. }
  1958. bool sendExternalDragAndDropMessage (XClientMessageEvent& msg, const Window targetWindow)
  1959. {
  1960. msg.type = ClientMessage;
  1961. msg.display = display;
  1962. msg.window = targetWindow;
  1963. msg.format = 32;
  1964. msg.data.l[0] = windowH;
  1965. ScopedXLock xlock;
  1966. return XSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
  1967. }
  1968. void sendExternalDragAndDropDrop (const Window targetWindow)
  1969. {
  1970. XClientMessageEvent msg;
  1971. zerostruct (msg);
  1972. msg.message_type = Atoms::get().XdndDrop;
  1973. msg.data.l[2] = CurrentTime;
  1974. sendExternalDragAndDropMessage (msg, targetWindow);
  1975. }
  1976. void sendExternalDragAndDropEnter (const Window targetWindow)
  1977. {
  1978. XClientMessageEvent msg;
  1979. zerostruct (msg);
  1980. msg.message_type = Atoms::get().XdndEnter;
  1981. const Atom* mimeTypes = dragState.getMimeTypes();
  1982. const int numMimeTypes = dragState.getNumMimeTypes();
  1983. msg.data.l[1] = (dragState.xdndVersion << 24) | (numMimeTypes > 3);
  1984. msg.data.l[2] = numMimeTypes > 0 ? mimeTypes[0] : 0;
  1985. msg.data.l[3] = numMimeTypes > 1 ? mimeTypes[1] : 0;
  1986. msg.data.l[4] = numMimeTypes > 2 ? mimeTypes[2] : 0;
  1987. sendExternalDragAndDropMessage (msg, targetWindow);
  1988. }
  1989. void sendExternalDragAndDropPosition (const Window targetWindow)
  1990. {
  1991. XClientMessageEvent msg;
  1992. zerostruct (msg);
  1993. msg.message_type = Atoms::get().XdndPosition;
  1994. const Point<int> mousePos (Desktop::getInstance().getMousePosition());
  1995. if (dragState.silentRect.contains (mousePos)) // we've been asked to keep silent
  1996. return;
  1997. msg.data.l[1] = 0;
  1998. msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
  1999. msg.data.l[3] = CurrentTime;
  2000. msg.data.l[4] = Atoms::get().XdndActionCopy; // this is all JUCE currently supports
  2001. dragState.expectingStatus = sendExternalDragAndDropMessage (msg, targetWindow);
  2002. }
  2003. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  2004. {
  2005. XClientMessageEvent msg;
  2006. zerostruct (msg);
  2007. msg.message_type = Atoms::get().XdndStatus;
  2008. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  2009. msg.data.l[4] = dropAction;
  2010. sendDragAndDropMessage (msg);
  2011. }
  2012. void sendExternalDragAndDropLeave (const Window targetWindow)
  2013. {
  2014. XClientMessageEvent msg;
  2015. zerostruct (msg);
  2016. msg.message_type = Atoms::get().XdndLeave;
  2017. sendExternalDragAndDropMessage (msg, targetWindow);
  2018. }
  2019. void sendDragAndDropFinish()
  2020. {
  2021. XClientMessageEvent msg;
  2022. zerostruct (msg);
  2023. msg.message_type = Atoms::get().XdndFinished;
  2024. sendDragAndDropMessage (msg);
  2025. }
  2026. void handleExternalSelectionClear()
  2027. {
  2028. if (dragState.dragging)
  2029. externalResetDragAndDrop();
  2030. }
  2031. void handleExternalSelectionRequest (const XEvent& evt)
  2032. {
  2033. Atom targetType = evt.xselectionrequest.target;
  2034. XEvent s;
  2035. s.xselection.type = SelectionNotify;
  2036. s.xselection.requestor = evt.xselectionrequest.requestor;
  2037. s.xselection.selection = evt.xselectionrequest.selection;
  2038. s.xselection.target = targetType;
  2039. s.xselection.property = None;
  2040. s.xselection.time = evt.xselectionrequest.time;
  2041. if (dragState.matchesTarget (targetType))
  2042. {
  2043. s.xselection.property = evt.xselectionrequest.property;
  2044. xchangeProperty (evt.xselectionrequest.requestor,
  2045. evt.xselectionrequest.property,
  2046. targetType, 8,
  2047. dragState.textOrFiles.toRawUTF8(),
  2048. dragState.textOrFiles.getNumBytesAsUTF8());
  2049. }
  2050. XSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
  2051. }
  2052. void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
  2053. {
  2054. if (dragState.expectingStatus)
  2055. {
  2056. dragState.expectingStatus = false;
  2057. dragState.canDrop = false;
  2058. dragState.silentRect = Rectangle<int>();
  2059. if ((clientMsg.data.l[1] & 1) != 0
  2060. && ((Atom) clientMsg.data.l[4] == Atoms::get().XdndActionCopy
  2061. || (Atom) clientMsg.data.l[4] == Atoms::get().XdndActionPrivate))
  2062. {
  2063. if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
  2064. dragState.silentRect.setBounds (clientMsg.data.l[2] >> 16,
  2065. clientMsg.data.l[2] & 0xffff,
  2066. clientMsg.data.l[3] >> 16,
  2067. clientMsg.data.l[3] & 0xffff);
  2068. dragState.canDrop = true;
  2069. }
  2070. }
  2071. }
  2072. void handleExternalDragButtonReleaseEvent()
  2073. {
  2074. if (dragState.dragging)
  2075. XUngrabPointer (display, CurrentTime);
  2076. if (dragState.canDrop)
  2077. {
  2078. sendExternalDragAndDropDrop (dragState.targetWindow);
  2079. }
  2080. else
  2081. {
  2082. sendExternalDragAndDropLeave (dragState.targetWindow);
  2083. externalResetDragAndDrop();
  2084. }
  2085. }
  2086. void handleExternalDragMotionNotify()
  2087. {
  2088. Window targetWindow = externalFindDragTargetWindow (RootWindow (display, DefaultScreen (display)));
  2089. if (dragState.targetWindow != targetWindow)
  2090. {
  2091. if (dragState.targetWindow != None)
  2092. sendExternalDragAndDropLeave (dragState.targetWindow);
  2093. dragState.canDrop = false;
  2094. dragState.silentRect = Rectangle<int>();
  2095. if (targetWindow == None)
  2096. return;
  2097. GetXProperty prop (targetWindow, Atoms::get().XdndAware,
  2098. 0, 2, false, AnyPropertyType);
  2099. if (prop.success
  2100. && prop.data != None
  2101. && prop.actualFormat == 32
  2102. && prop.numItems == 1)
  2103. {
  2104. dragState.xdndVersion = jmin ((int) prop.data[0], (int) Atoms::DndVersion);
  2105. }
  2106. else
  2107. {
  2108. dragState.xdndVersion = -1;
  2109. return;
  2110. }
  2111. sendExternalDragAndDropEnter (targetWindow);
  2112. dragState.targetWindow = targetWindow;
  2113. }
  2114. if (! dragState.expectingStatus)
  2115. sendExternalDragAndDropPosition (targetWindow);
  2116. }
  2117. void handleDragAndDropPosition (const XClientMessageEvent& clientMsg)
  2118. {
  2119. if (dragAndDropSourceWindow == 0)
  2120. return;
  2121. dragAndDropSourceWindow = clientMsg.data.l[0];
  2122. Point<int> dropPos ((int) clientMsg.data.l[2] >> 16,
  2123. (int) clientMsg.data.l[2] & 0xffff);
  2124. dropPos -= bounds.getPosition();
  2125. const Atoms& atoms = Atoms::get();
  2126. Atom targetAction = atoms.XdndActionCopy;
  2127. for (int i = numElementsInArray (atoms.allowedActions); --i >= 0;)
  2128. {
  2129. if ((Atom) clientMsg.data.l[4] == atoms.allowedActions[i])
  2130. {
  2131. targetAction = atoms.allowedActions[i];
  2132. break;
  2133. }
  2134. }
  2135. sendDragAndDropStatus (true, targetAction);
  2136. if (dragInfo.position != dropPos)
  2137. {
  2138. dragInfo.position = dropPos;
  2139. if (dragInfo.isEmpty())
  2140. updateDraggedFileList (clientMsg);
  2141. if (! dragInfo.isEmpty())
  2142. handleDragMove (dragInfo);
  2143. }
  2144. }
  2145. void handleDragAndDropDrop (const XClientMessageEvent& clientMsg)
  2146. {
  2147. if (dragInfo.isEmpty())
  2148. {
  2149. // no data, transaction finished in handleDragAndDropSelection()
  2150. finishAfterDropDataReceived = true;
  2151. updateDraggedFileList (clientMsg);
  2152. }
  2153. else
  2154. {
  2155. handleDragAndDropDataReceived(); // data was already received
  2156. }
  2157. }
  2158. void handleDragAndDropDataReceived()
  2159. {
  2160. DragInfo dragInfoCopy (dragInfo);
  2161. sendDragAndDropFinish();
  2162. resetDragAndDrop();
  2163. if (! dragInfoCopy.isEmpty())
  2164. handleDragDrop (dragInfoCopy);
  2165. }
  2166. void handleDragAndDropEnter (const XClientMessageEvent& clientMsg)
  2167. {
  2168. dragInfo.clear();
  2169. srcMimeTypeAtomList.clear();
  2170. dragAndDropCurrentMimeType = 0;
  2171. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg.data.l[1] & 0xff000000) >> 24;
  2172. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  2173. {
  2174. dragAndDropSourceWindow = 0;
  2175. return;
  2176. }
  2177. dragAndDropSourceWindow = clientMsg.data.l[0];
  2178. if ((clientMsg.data.l[1] & 1) != 0)
  2179. {
  2180. ScopedXLock xlock;
  2181. GetXProperty prop (dragAndDropSourceWindow, Atoms::get().XdndTypeList, 0, 0x8000000L, false, XA_ATOM);
  2182. if (prop.success
  2183. && prop.actualType == XA_ATOM
  2184. && prop.actualFormat == 32
  2185. && prop.numItems != 0)
  2186. {
  2187. const unsigned long* const types = (const unsigned long*) prop.data;
  2188. for (unsigned long i = 0; i < prop.numItems; ++i)
  2189. if (types[i] != None)
  2190. srcMimeTypeAtomList.add (types[i]);
  2191. }
  2192. }
  2193. if (srcMimeTypeAtomList.size() == 0)
  2194. {
  2195. for (int i = 2; i < 5; ++i)
  2196. if (clientMsg.data.l[i] != None)
  2197. srcMimeTypeAtomList.add (clientMsg.data.l[i]);
  2198. if (srcMimeTypeAtomList.size() == 0)
  2199. {
  2200. dragAndDropSourceWindow = 0;
  2201. return;
  2202. }
  2203. }
  2204. const Atoms& atoms = Atoms::get();
  2205. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  2206. for (int j = 0; j < numElementsInArray (atoms.allowedMimeTypes); ++j)
  2207. if (srcMimeTypeAtomList[i] == atoms.allowedMimeTypes[j])
  2208. dragAndDropCurrentMimeType = atoms.allowedMimeTypes[j];
  2209. handleDragAndDropPosition (clientMsg);
  2210. }
  2211. void handleDragAndDropSelection (const XEvent& evt)
  2212. {
  2213. dragInfo.clear();
  2214. if (evt.xselection.property != None)
  2215. {
  2216. StringArray lines;
  2217. {
  2218. MemoryBlock dropData;
  2219. for (;;)
  2220. {
  2221. GetXProperty prop (evt.xany.window, evt.xselection.property,
  2222. dropData.getSize() / 4, 65536, false, AnyPropertyType);
  2223. if (! prop.success)
  2224. break;
  2225. dropData.append (prop.data, prop.numItems * prop.actualFormat / 8);
  2226. if (prop.bytesLeft <= 0)
  2227. break;
  2228. }
  2229. lines.addLines (dropData.toString());
  2230. }
  2231. if (Atoms::isMimeTypeFile (dragAndDropCurrentMimeType))
  2232. {
  2233. for (int i = 0; i < lines.size(); ++i)
  2234. dragInfo.files.add (URL::removeEscapeChars (lines[i].replace ("file://", String::empty, true)));
  2235. dragInfo.files.trim();
  2236. dragInfo.files.removeEmptyStrings();
  2237. }
  2238. else
  2239. {
  2240. dragInfo.text = lines.joinIntoString ("\n");
  2241. }
  2242. if (finishAfterDropDataReceived)
  2243. handleDragAndDropDataReceived();
  2244. }
  2245. }
  2246. void updateDraggedFileList (const XClientMessageEvent& clientMsg)
  2247. {
  2248. jassert (dragInfo.isEmpty());
  2249. if (dragAndDropSourceWindow != None
  2250. && dragAndDropCurrentMimeType != None)
  2251. {
  2252. ScopedXLock xlock;
  2253. XConvertSelection (display,
  2254. Atoms::get().XdndSelection,
  2255. dragAndDropCurrentMimeType,
  2256. Atoms::getCreating ("JXSelectionWindowProperty"),
  2257. windowH,
  2258. clientMsg.data.l[2]);
  2259. }
  2260. }
  2261. static bool isWindowDnDAware (Window w)
  2262. {
  2263. int numProperties = 0;
  2264. Atom* const atoms = XListProperties (display, w, &numProperties);
  2265. bool dndAwarePropFound = false;
  2266. for (int i = 0; i < numProperties; ++i)
  2267. if (atoms[i] == Atoms::get().XdndAware)
  2268. dndAwarePropFound = true;
  2269. if (atoms != nullptr)
  2270. XFree (atoms);
  2271. return dndAwarePropFound;
  2272. }
  2273. Window externalFindDragTargetWindow (Window targetWindow)
  2274. {
  2275. if (targetWindow == None)
  2276. return None;
  2277. if (isWindowDnDAware (targetWindow))
  2278. return targetWindow;
  2279. Window child, phonyWin;
  2280. int phony;
  2281. unsigned int uphony;
  2282. XQueryPointer (display, targetWindow, &phonyWin, &child,
  2283. &phony, &phony, &phony, &phony, &uphony);
  2284. return externalFindDragTargetWindow (child);
  2285. }
  2286. bool externalDragInit (bool isText, const String& textOrFiles)
  2287. {
  2288. ScopedXLock xlock;
  2289. resetExternalDragState();
  2290. dragState.isText = isText;
  2291. dragState.textOrFiles = textOrFiles;
  2292. dragState.targetWindow = windowH;
  2293. const int pointerGrabMask = Button1MotionMask | ButtonReleaseMask;
  2294. if (XGrabPointer (display, windowH, True, pointerGrabMask,
  2295. GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
  2296. {
  2297. // No other method of changing the pointer seems to work, this call is needed from this very context
  2298. XChangeActivePointerGrab (display, pointerGrabMask, (Cursor) createDraggingHandCursor(), CurrentTime);
  2299. const Atoms& atoms = Atoms::get();
  2300. XSetSelectionOwner (display, atoms.XdndSelection, windowH, CurrentTime);
  2301. // save the available types to XdndTypeList
  2302. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32,
  2303. dragState.getMimeTypes(),
  2304. dragState.getNumMimeTypes());
  2305. dragState.dragging = true;
  2306. handleExternalDragMotionNotify();
  2307. return true;
  2308. }
  2309. return false;
  2310. }
  2311. void externalResetDragAndDrop()
  2312. {
  2313. if (dragState.dragging)
  2314. {
  2315. ScopedXLock xlock;
  2316. XUngrabPointer (display, CurrentTime);
  2317. }
  2318. resetExternalDragState();
  2319. }
  2320. DragState dragState;
  2321. DragInfo dragInfo;
  2322. Atom dragAndDropCurrentMimeType;
  2323. Window dragAndDropSourceWindow;
  2324. bool finishAfterDropDataReceived;
  2325. Array <Atom> srcMimeTypeAtomList;
  2326. int pointerMap[5];
  2327. void initialisePointerMap()
  2328. {
  2329. const int numButtons = XGetPointerMapping (display, 0, 0);
  2330. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2331. if (numButtons == 2)
  2332. {
  2333. pointerMap[0] = Keys::LeftButton;
  2334. pointerMap[1] = Keys::RightButton;
  2335. }
  2336. else if (numButtons >= 3)
  2337. {
  2338. pointerMap[0] = Keys::LeftButton;
  2339. pointerMap[1] = Keys::MiddleButton;
  2340. pointerMap[2] = Keys::RightButton;
  2341. if (numButtons >= 5)
  2342. {
  2343. pointerMap[3] = Keys::WheelUp;
  2344. pointerMap[4] = Keys::WheelDown;
  2345. }
  2346. }
  2347. }
  2348. static Point<int> lastMousePos;
  2349. static void clearLastMousePos() noexcept
  2350. {
  2351. lastMousePos = Point<int> (0x100000, 0x100000);
  2352. }
  2353. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  2354. };
  2355. ModifierKeys LinuxComponentPeer::currentModifiers;
  2356. bool LinuxComponentPeer::isActiveApplication = false;
  2357. Point<int> LinuxComponentPeer::lastMousePos;
  2358. //==============================================================================
  2359. bool Process::isForegroundProcess()
  2360. {
  2361. return LinuxComponentPeer::isActiveApplication;
  2362. }
  2363. void Process::makeForegroundProcess()
  2364. {
  2365. }
  2366. //==============================================================================
  2367. void ModifierKeys::updateCurrentModifiers() noexcept
  2368. {
  2369. currentModifiers = LinuxComponentPeer::currentModifiers;
  2370. }
  2371. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2372. {
  2373. Window root, child;
  2374. int x, y, winx, winy;
  2375. unsigned int mask;
  2376. int mouseMods = 0;
  2377. ScopedXLock xlock;
  2378. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  2379. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  2380. {
  2381. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  2382. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  2383. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  2384. }
  2385. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2386. return LinuxComponentPeer::currentModifiers;
  2387. }
  2388. //==============================================================================
  2389. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /* allowMenusAndBars */)
  2390. {
  2391. if (enableOrDisable)
  2392. kioskModeComponent->setBounds (getDisplays().getMainDisplay().totalArea);
  2393. }
  2394. //==============================================================================
  2395. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  2396. {
  2397. return new LinuxComponentPeer (*this, styleFlags, (Window) nativeWindowToAttachTo);
  2398. }
  2399. //==============================================================================
  2400. static double getDisplayDPI (int index)
  2401. {
  2402. double dpiX = (DisplayWidth (display, index) * 25.4) / DisplayWidthMM (display, index);
  2403. double dpiY = (DisplayHeight (display, index) * 25.4) / DisplayHeightMM (display, index);
  2404. return (dpiX + dpiY) / 2.0;
  2405. }
  2406. void Desktop::Displays::findDisplays (float masterScale)
  2407. {
  2408. if (display == 0)
  2409. return;
  2410. ScopedXLock xlock;
  2411. #if JUCE_USE_XINERAMA
  2412. int major_opcode, first_event, first_error;
  2413. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  2414. {
  2415. typedef Bool (*tXineramaIsActive) (::Display*);
  2416. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (::Display*, int*);
  2417. static tXineramaIsActive xineramaIsActive = nullptr;
  2418. static tXineramaQueryScreens xineramaQueryScreens = nullptr;
  2419. if (xineramaIsActive == nullptr || xineramaQueryScreens == nullptr)
  2420. {
  2421. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  2422. if (h == nullptr)
  2423. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  2424. if (h != nullptr)
  2425. {
  2426. xineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  2427. xineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  2428. }
  2429. }
  2430. if (xineramaIsActive != nullptr
  2431. && xineramaQueryScreens != nullptr
  2432. && xineramaIsActive (display))
  2433. {
  2434. int numMonitors = 0;
  2435. if (XineramaScreenInfo* const screens = xineramaQueryScreens (display, &numMonitors))
  2436. {
  2437. for (int index = 0; index < numMonitors; ++index)
  2438. {
  2439. for (int j = numMonitors; --j >= 0;)
  2440. {
  2441. if (screens[j].screen_number == index)
  2442. {
  2443. Display d;
  2444. d.userArea = d.totalArea = Rectangle<int> (screens[j].x_org,
  2445. screens[j].y_org,
  2446. screens[j].width,
  2447. screens[j].height) * masterScale;
  2448. d.isMain = (index == 0);
  2449. d.scale = masterScale;
  2450. d.dpi = getDisplayDPI (index);
  2451. displays.add (d);
  2452. }
  2453. }
  2454. }
  2455. XFree (screens);
  2456. }
  2457. }
  2458. }
  2459. if (displays.size() == 0)
  2460. #endif
  2461. {
  2462. Atom hints = Atoms::getIfExists ("_NET_WORKAREA");
  2463. if (hints != None)
  2464. {
  2465. const int numMonitors = ScreenCount (display);
  2466. for (int i = 0; i < numMonitors; ++i)
  2467. {
  2468. GetXProperty prop (RootWindow (display, i), hints, 0, 4, false, XA_CARDINAL);
  2469. if (prop.success && prop.actualType == XA_CARDINAL && prop.actualFormat == 32 && prop.numItems == 4)
  2470. {
  2471. const long* const position = (const long*) prop.data;
  2472. Display d;
  2473. d.userArea = d.totalArea = Rectangle<int> (position[0], position[1],
  2474. position[2], position[3]) / masterScale;
  2475. d.isMain = (displays.size() == 0);
  2476. d.scale = masterScale;
  2477. d.dpi = getDisplayDPI (i);
  2478. displays.add (d);
  2479. }
  2480. }
  2481. }
  2482. if (displays.size() == 0)
  2483. {
  2484. Display d;
  2485. d.userArea = d.totalArea = Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  2486. DisplayHeight (display, DefaultScreen (display))) * masterScale;
  2487. d.isMain = true;
  2488. d.scale = masterScale;
  2489. d.dpi = getDisplayDPI (0);
  2490. displays.add (d);
  2491. }
  2492. }
  2493. }
  2494. //==============================================================================
  2495. bool Desktop::addMouseInputSource()
  2496. {
  2497. if (mouseSources.size() == 0)
  2498. {
  2499. mouseSources.add (new MouseInputSource (0, true));
  2500. return true;
  2501. }
  2502. return false;
  2503. }
  2504. bool Desktop::canUseSemiTransparentWindows() noexcept
  2505. {
  2506. int matchedDepth = 0;
  2507. const int desiredDepth = 32;
  2508. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  2509. && (matchedDepth == desiredDepth);
  2510. }
  2511. Point<int> MouseInputSource::getCurrentRawMousePosition()
  2512. {
  2513. Window root, child;
  2514. int x, y, winx, winy;
  2515. unsigned int mask;
  2516. ScopedXLock xlock;
  2517. if (XQueryPointer (display,
  2518. RootWindow (display, DefaultScreen (display)),
  2519. &root, &child,
  2520. &x, &y, &winx, &winy, &mask) == False)
  2521. {
  2522. // Pointer not on the default screen
  2523. x = y = -1;
  2524. }
  2525. return Point<int> (x, y);
  2526. }
  2527. void MouseInputSource::setRawMousePosition (Point<int> newPosition)
  2528. {
  2529. ScopedXLock xlock;
  2530. Window root = RootWindow (display, DefaultScreen (display));
  2531. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  2532. }
  2533. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  2534. {
  2535. return upright;
  2536. }
  2537. //==============================================================================
  2538. static bool screenSaverAllowed = true;
  2539. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  2540. {
  2541. if (screenSaverAllowed != isEnabled)
  2542. {
  2543. screenSaverAllowed = isEnabled;
  2544. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  2545. static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
  2546. if (xScreenSaverSuspend == nullptr)
  2547. if (void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW))
  2548. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  2549. ScopedXLock xlock;
  2550. if (xScreenSaverSuspend != nullptr)
  2551. xScreenSaverSuspend (display, ! isEnabled);
  2552. }
  2553. }
  2554. bool Desktop::isScreenSaverEnabled()
  2555. {
  2556. return screenSaverAllowed;
  2557. }
  2558. //==============================================================================
  2559. void* CustomMouseCursorInfo::create() const
  2560. {
  2561. ScopedXLock xlock;
  2562. const unsigned int imageW = image.getWidth();
  2563. const unsigned int imageH = image.getHeight();
  2564. int hotspotX = hotspot.x;
  2565. int hotspotY = hotspot.y;
  2566. #if JUCE_USE_XCURSOR
  2567. {
  2568. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  2569. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  2570. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  2571. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  2572. static tXcursorSupportsARGB xcursorSupportsARGB = nullptr;
  2573. static tXcursorImageCreate xcursorImageCreate = nullptr;
  2574. static tXcursorImageDestroy xcursorImageDestroy = nullptr;
  2575. static tXcursorImageLoadCursor xcursorImageLoadCursor = nullptr;
  2576. static bool hasBeenLoaded = false;
  2577. if (! hasBeenLoaded)
  2578. {
  2579. hasBeenLoaded = true;
  2580. if (void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW))
  2581. {
  2582. xcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  2583. xcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  2584. xcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  2585. xcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  2586. if (xcursorSupportsARGB == nullptr || xcursorImageCreate == nullptr
  2587. || xcursorImageLoadCursor == nullptr || xcursorImageDestroy == nullptr
  2588. || ! xcursorSupportsARGB (display))
  2589. xcursorSupportsARGB = nullptr;
  2590. }
  2591. }
  2592. if (xcursorSupportsARGB != nullptr)
  2593. {
  2594. if (XcursorImage* xcImage = xcursorImageCreate (imageW, imageH))
  2595. {
  2596. xcImage->xhot = hotspotX;
  2597. xcImage->yhot = hotspotY;
  2598. XcursorPixel* dest = xcImage->pixels;
  2599. for (int y = 0; y < (int) imageH; ++y)
  2600. for (int x = 0; x < (int) imageW; ++x)
  2601. *dest++ = image.getPixelAt (x, y).getARGB();
  2602. void* result = (void*) xcursorImageLoadCursor (display, xcImage);
  2603. xcursorImageDestroy (xcImage);
  2604. if (result != nullptr)
  2605. return result;
  2606. }
  2607. }
  2608. }
  2609. #endif
  2610. Window root = RootWindow (display, DefaultScreen (display));
  2611. unsigned int cursorW, cursorH;
  2612. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  2613. return nullptr;
  2614. Image im (Image::ARGB, cursorW, cursorH, true);
  2615. {
  2616. Graphics g (im);
  2617. if (imageW > cursorW || imageH > cursorH)
  2618. {
  2619. hotspotX = (hotspotX * cursorW) / imageW;
  2620. hotspotY = (hotspotY * cursorH) / imageH;
  2621. g.drawImageWithin (image, 0, 0, imageW, imageH,
  2622. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  2623. false);
  2624. }
  2625. else
  2626. {
  2627. g.drawImageAt (image, 0, 0);
  2628. }
  2629. }
  2630. const int stride = (cursorW + 7) >> 3;
  2631. HeapBlock <char> maskPlane, sourcePlane;
  2632. maskPlane.calloc (stride * cursorH);
  2633. sourcePlane.calloc (stride * cursorH);
  2634. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  2635. for (int y = cursorH; --y >= 0;)
  2636. {
  2637. for (int x = cursorW; --x >= 0;)
  2638. {
  2639. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  2640. const int offset = y * stride + (x >> 3);
  2641. const Colour c (im.getPixelAt (x, y));
  2642. if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
  2643. if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
  2644. }
  2645. }
  2646. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2647. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2648. XColor white, black;
  2649. black.red = black.green = black.blue = 0;
  2650. white.red = white.green = white.blue = 0xffff;
  2651. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  2652. XFreePixmap (display, sourcePixmap);
  2653. XFreePixmap (display, maskPixmap);
  2654. return result;
  2655. }
  2656. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  2657. {
  2658. ScopedXLock xlock;
  2659. if (cursorHandle != nullptr)
  2660. XFreeCursor (display, (Cursor) cursorHandle);
  2661. }
  2662. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  2663. {
  2664. unsigned int shape;
  2665. switch (type)
  2666. {
  2667. case NormalCursor:
  2668. case ParentCursor: return None; // Use parent cursor
  2669. case NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), 0, 0).create();
  2670. case WaitCursor: shape = XC_watch; break;
  2671. case IBeamCursor: shape = XC_xterm; break;
  2672. case PointingHandCursor: shape = XC_hand2; break;
  2673. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  2674. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  2675. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  2676. case TopEdgeResizeCursor: shape = XC_top_side; break;
  2677. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  2678. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  2679. case RightEdgeResizeCursor: shape = XC_right_side; break;
  2680. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  2681. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  2682. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  2683. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  2684. case CrosshairCursor: shape = XC_crosshair; break;
  2685. case DraggingHandCursor: return createDraggingHandCursor();
  2686. case CopyingCursor:
  2687. {
  2688. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  2689. 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,
  2690. 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,
  2691. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  2692. const int copyCursorSize = 119;
  2693. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
  2694. }
  2695. default:
  2696. jassertfalse;
  2697. return None;
  2698. }
  2699. ScopedXLock xlock;
  2700. return (void*) XCreateFontCursor (display, shape);
  2701. }
  2702. void MouseCursor::showInWindow (ComponentPeer* peer) const
  2703. {
  2704. if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer))
  2705. lp->showMouseCursor ((Cursor) getHandle());
  2706. }
  2707. void MouseCursor::showInAllWindows() const
  2708. {
  2709. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  2710. showInWindow (ComponentPeer::getPeer (i));
  2711. }
  2712. //==============================================================================
  2713. Image juce_createIconForFile (const File& /* file */)
  2714. {
  2715. return Image::null;
  2716. }
  2717. //==============================================================================
  2718. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  2719. {
  2720. if (files.size() == 0)
  2721. return false;
  2722. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  2723. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  2724. if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (sourceComp->getPeer()))
  2725. return lp->externalDragFileInit (files, canMoveFiles);
  2726. // This method must be called in response to a component's mouseDown or mouseDrag event!
  2727. jassertfalse;
  2728. return false;
  2729. }
  2730. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2731. {
  2732. if (text.isEmpty())
  2733. return false;
  2734. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  2735. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  2736. if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (sourceComp->getPeer()))
  2737. return lp->externalDragTextInit (text);
  2738. // This method must be called in response to a component's mouseDown or mouseDrag event!
  2739. jassertfalse;
  2740. return false;
  2741. }
  2742. //==============================================================================
  2743. void LookAndFeel::playAlertSound()
  2744. {
  2745. std::cout << "\a" << std::flush;
  2746. }
  2747. //==============================================================================
  2748. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  2749. const String& title, const String& message,
  2750. Component* /* associatedComponent */)
  2751. {
  2752. AlertWindow::showMessageBox (iconType, title, message);
  2753. }
  2754. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  2755. const String& title, const String& message,
  2756. Component* associatedComponent,
  2757. ModalComponentManager::Callback* callback)
  2758. {
  2759. AlertWindow::showMessageBoxAsync (iconType, title, message, String::empty, associatedComponent, callback);
  2760. }
  2761. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  2762. const String& title, const String& message,
  2763. Component* associatedComponent,
  2764. ModalComponentManager::Callback* callback)
  2765. {
  2766. return AlertWindow::showOkCancelBox (iconType, title, message, String::empty, String::empty,
  2767. associatedComponent, callback);
  2768. }
  2769. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  2770. const String& title, const String& message,
  2771. Component* associatedComponent,
  2772. ModalComponentManager::Callback* callback)
  2773. {
  2774. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  2775. String::empty, String::empty, String::empty,
  2776. associatedComponent, callback);
  2777. }
  2778. //==============================================================================
  2779. const int KeyPress::spaceKey = XK_space & 0xff;
  2780. const int KeyPress::returnKey = XK_Return & 0xff;
  2781. const int KeyPress::escapeKey = XK_Escape & 0xff;
  2782. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  2783. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  2784. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  2785. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  2786. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  2787. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  2788. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  2789. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  2790. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  2791. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  2792. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  2793. const int KeyPress::tabKey = XK_Tab & 0xff;
  2794. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  2795. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  2796. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  2797. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  2798. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  2799. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  2800. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  2801. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  2802. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  2803. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  2804. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  2805. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  2806. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  2807. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  2808. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  2809. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  2810. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  2811. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  2812. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  2813. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  2814. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  2815. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  2816. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  2817. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  2818. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  2819. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  2820. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  2821. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  2822. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  2823. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  2824. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  2825. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  2826. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  2827. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  2828. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  2829. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  2830. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  2831. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;