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.

3359 lines
112KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. #include "../../../juce_Config.h"
  24. #include "linuxincludes.h"
  25. #include <X11/Xlib.h>
  26. #include <X11/Xutil.h>
  27. #include <X11/Xatom.h>
  28. #include <X11/Xmd.h>
  29. #include <X11/keysym.h>
  30. #include <X11/cursorfont.h>
  31. #include <dlfcn.h>
  32. #if JUCE_USE_XINERAMA
  33. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package..
  34. */
  35. #include <X11/extensions/Xinerama.h>
  36. #endif
  37. #if JUCE_USE_XSHM
  38. #include <X11/extensions/XShm.h>
  39. #include <sys/shm.h>
  40. #include <sys/ipc.h>
  41. #endif
  42. #if JUCE_OPENGL
  43. /* Got an include error here?
  44. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  45. and "freeglut3-dev".
  46. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  47. want to disable it.
  48. */
  49. #include <GL/glx.h>
  50. #endif
  51. #undef KeyPress
  52. #include "../../../src/juce_core/basics/juce_StandardHeader.h"
  53. BEGIN_JUCE_NAMESPACE
  54. #include "../../../src/juce_appframework/events/juce_Timer.h"
  55. #include "../../../src/juce_appframework/application/juce_DeletedAtShutdown.h"
  56. #include "../../../src/juce_appframework/gui/components/keyboard/juce_KeyPress.h"
  57. #include "../../../src/juce_appframework/application/juce_SystemClipboard.h"
  58. #include "../../../src/juce_appframework/gui/components/windows/juce_AlertWindow.h"
  59. #include "../../../src/juce_appframework/gui/components/special/juce_OpenGLComponent.h"
  60. #include "../../../src/juce_appframework/gui/components/juce_Desktop.h"
  61. #include "../../../src/juce_appframework/events/juce_MessageManager.h"
  62. #include "../../../src/juce_appframework/gui/components/juce_ComponentDeletionWatcher.h"
  63. #include "../../../src/juce_appframework/gui/graphics/geometry/juce_RectangleList.h"
  64. #include "../../../src/juce_appframework/gui/graphics/imaging/juce_ImageFileFormat.h"
  65. #include "../../../src/juce_appframework/gui/graphics/contexts/juce_LowLevelGraphicsSoftwareRenderer.h"
  66. #include "../../../src/juce_appframework/gui/components/mouse/juce_DragAndDropContainer.h"
  67. #include "../../../src/juce_appframework/gui/components/special/juce_SystemTrayIconComponent.h"
  68. #include "../../../src/juce_appframework/application/juce_Application.h"
  69. #include "../../../src/juce_core/threads/juce_Process.h"
  70. #include "../../../src/juce_core/io/network/juce_URL.h"
  71. #include "../../../src/juce_core/misc/juce_PlatformUtilities.h"
  72. //==============================================================================
  73. #define TAKE_FOCUS 0
  74. #define DELETE_WINDOW 1
  75. #define SYSTEM_TRAY_REQUEST_DOCK 0
  76. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  77. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  78. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  79. //==============================================================================
  80. static Atom wm_ChangeState = None;
  81. static Atom wm_State = None;
  82. static Atom wm_Protocols = None;
  83. static Atom wm_ProtocolList [2] = { None, None };
  84. static Atom wm_ActiveWin = None;
  85. #define ourDndVersion 3
  86. static Atom XA_XdndAware = None;
  87. static Atom XA_XdndEnter = None;
  88. static Atom XA_XdndLeave = None;
  89. static Atom XA_XdndPosition = None;
  90. static Atom XA_XdndStatus = None;
  91. static Atom XA_XdndDrop = None;
  92. static Atom XA_XdndFinished = None;
  93. static Atom XA_XdndSelection = None;
  94. static Atom XA_XdndProxy = None;
  95. static Atom XA_XdndTypeList = None;
  96. static Atom XA_XdndActionList = None;
  97. static Atom XA_XdndActionDescription = None;
  98. static Atom XA_XdndActionCopy = None;
  99. static Atom XA_XdndActionMove = None;
  100. static Atom XA_XdndActionLink = None;
  101. static Atom XA_XdndActionAsk = None;
  102. static Atom XA_XdndActionPrivate = None;
  103. static Atom XA_JXSelectionWindowProperty = None;
  104. static Atom XA_MimeTextPlain = None;
  105. static Atom XA_MimeTextUriList = None;
  106. static Atom XA_MimeRootDrop = None;
  107. //==============================================================================
  108. static XErrorHandler oldHandler = 0;
  109. static int trappedErrorCode = 0;
  110. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  111. {
  112. trappedErrorCode = err->error_code;
  113. return 0;
  114. }
  115. static void trapErrors()
  116. {
  117. trappedErrorCode = 0;
  118. oldHandler = XSetErrorHandler (errorTrapHandler);
  119. }
  120. static bool untrapErrors()
  121. {
  122. XSetErrorHandler (oldHandler);
  123. return (trappedErrorCode == 0);
  124. }
  125. //==============================================================================
  126. static bool isActiveApplication = false;
  127. bool Process::isForegroundProcess() throw()
  128. {
  129. return isActiveApplication;
  130. }
  131. // (used in the messaging code, declared here for build reasons)
  132. bool juce_isRunningAsApplication()
  133. {
  134. return JUCEApplication::getInstance() != 0;
  135. }
  136. //==============================================================================
  137. // These are defined in juce_linux_Messaging.cpp
  138. extern Display* display;
  139. extern XContext improbableNumber;
  140. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  141. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  142. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  143. //==============================================================================
  144. static int pointerMap[5];
  145. static int lastMousePosX = 0, lastMousePosY = 0;
  146. enum MouseButtons
  147. {
  148. NoButton = 0,
  149. LeftButton = 1,
  150. MiddleButton = 2,
  151. RightButton = 3,
  152. WheelUp = 4,
  153. WheelDown = 5
  154. };
  155. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  156. {
  157. Window root, child;
  158. int winx, winy;
  159. unsigned int mask;
  160. mouseMods = 0;
  161. if (XQueryPointer (display,
  162. RootWindow (display, DefaultScreen (display)),
  163. &root, &child,
  164. &x, &y, &winx, &winy, &mask) == False)
  165. {
  166. // Pointer not on the default screen
  167. x = y = -1;
  168. }
  169. else
  170. {
  171. if ((mask & Button1Mask) != 0)
  172. mouseMods |= ModifierKeys::leftButtonModifier;
  173. if ((mask & Button2Mask) != 0)
  174. mouseMods |= ModifierKeys::middleButtonModifier;
  175. if ((mask & Button3Mask) != 0)
  176. mouseMods |= ModifierKeys::rightButtonModifier;
  177. }
  178. }
  179. //==============================================================================
  180. static int AltMask = 0;
  181. static int NumLockMask = 0;
  182. static bool numLock = 0;
  183. static bool capsLock = 0;
  184. static char keyStates [32];
  185. static void updateKeyStates (const int keycode, const bool press) throw()
  186. {
  187. const int keybyte = keycode >> 3;
  188. const int keybit = (1 << (keycode & 7));
  189. if (press)
  190. keyStates [keybyte] |= keybit;
  191. else
  192. keyStates [keybyte] &= ~keybit;
  193. }
  194. static bool keyDown (const int keycode) throw()
  195. {
  196. const int keybyte = keycode >> 3;
  197. const int keybit = (1 << (keycode & 7));
  198. return (keyStates [keybyte] & keybit) != 0;
  199. }
  200. static const int extendedKeyModifier = 0x10000000;
  201. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  202. {
  203. int keysym;
  204. if (keyCode & extendedKeyModifier)
  205. {
  206. keysym = 0xff00 | (keyCode & 0xff);
  207. }
  208. else
  209. {
  210. keysym = keyCode;
  211. if (keysym == (XK_Tab & 0xff)
  212. || keysym == (XK_Return & 0xff)
  213. || keysym == (XK_Escape & 0xff)
  214. || keysym == (XK_BackSpace & 0xff))
  215. {
  216. keysym |= 0xff00;
  217. }
  218. }
  219. return keyDown (XKeysymToKeycode (display, keysym));
  220. }
  221. //==============================================================================
  222. // Alt and Num lock are not defined by standard X
  223. // modifier constants: check what they're mapped to
  224. static void getModifierMapping() throw()
  225. {
  226. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  227. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  228. AltMask = 0;
  229. NumLockMask = 0;
  230. XModifierKeymap* mapping = XGetModifierMapping (display);
  231. if (mapping)
  232. {
  233. for (int i = 0; i < 8; i++)
  234. {
  235. if (mapping->modifiermap [i << 1] == altLeftCode)
  236. AltMask = 1 << i;
  237. else if (mapping->modifiermap [i << 1] == numLockCode)
  238. NumLockMask = 1 << i;
  239. }
  240. XFreeModifiermap (mapping);
  241. }
  242. }
  243. static int currentModifiers = 0;
  244. void ModifierKeys::updateCurrentModifiers() throw()
  245. {
  246. currentModifierFlags = currentModifiers;
  247. }
  248. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  249. {
  250. int x, y, mouseMods;
  251. getMousePos (x, y, mouseMods);
  252. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  253. currentModifiers |= mouseMods;
  254. return ModifierKeys (currentModifiers);
  255. }
  256. static void updateKeyModifiers (const int status) throw()
  257. {
  258. currentModifiers &= ~(ModifierKeys::shiftModifier
  259. | ModifierKeys::ctrlModifier
  260. | ModifierKeys::altModifier);
  261. if (status & ShiftMask)
  262. currentModifiers |= ModifierKeys::shiftModifier;
  263. if (status & ControlMask)
  264. currentModifiers |= ModifierKeys::ctrlModifier;
  265. if (status & AltMask)
  266. currentModifiers |= ModifierKeys::altModifier;
  267. numLock = ((status & NumLockMask) != 0);
  268. capsLock = ((status & LockMask) != 0);
  269. }
  270. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  271. {
  272. int modifier = 0;
  273. bool isModifier = true;
  274. switch (sym)
  275. {
  276. case XK_Shift_L:
  277. case XK_Shift_R:
  278. modifier = ModifierKeys::shiftModifier;
  279. break;
  280. case XK_Control_L:
  281. case XK_Control_R:
  282. modifier = ModifierKeys::ctrlModifier;
  283. break;
  284. case XK_Alt_L:
  285. case XK_Alt_R:
  286. modifier = ModifierKeys::altModifier;
  287. break;
  288. case XK_Num_Lock:
  289. if (press)
  290. numLock = ! numLock;
  291. break;
  292. case XK_Caps_Lock:
  293. if (press)
  294. capsLock = ! capsLock;
  295. break;
  296. case XK_Scroll_Lock:
  297. break;
  298. default:
  299. isModifier = false;
  300. break;
  301. }
  302. if (modifier != 0)
  303. {
  304. if (press)
  305. currentModifiers |= modifier;
  306. else
  307. currentModifiers &= ~modifier;
  308. }
  309. return isModifier;
  310. }
  311. //==============================================================================
  312. #if JUCE_USE_XSHM
  313. static bool isShmAvailable() throw()
  314. {
  315. static bool isChecked = false;
  316. static bool isAvailable = false;
  317. if (! isChecked)
  318. {
  319. isChecked = true;
  320. int major, minor;
  321. Bool pixmaps;
  322. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  323. {
  324. trapErrors();
  325. XShmSegmentInfo segmentInfo;
  326. zerostruct (segmentInfo);
  327. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  328. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  329. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  330. xImage->bytes_per_line * xImage->height,
  331. IPC_CREAT | 0777)) >= 0)
  332. {
  333. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  334. if (segmentInfo.shmaddr != (void*) -1)
  335. {
  336. segmentInfo.readOnly = False;
  337. xImage->data = segmentInfo.shmaddr;
  338. XSync (display, False);
  339. if (XShmAttach (display, &segmentInfo) != 0)
  340. {
  341. XSync (display, False);
  342. XShmDetach (display, &segmentInfo);
  343. isAvailable = true;
  344. }
  345. }
  346. XFlush (display);
  347. XDestroyImage (xImage);
  348. shmdt (segmentInfo.shmaddr);
  349. }
  350. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  351. isAvailable &= untrapErrors();
  352. }
  353. }
  354. return isAvailable;
  355. }
  356. #endif
  357. //==============================================================================
  358. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  359. {
  360. const int width = image.getWidth();
  361. const int height = image.getHeight();
  362. uint32* const colour = (uint32*) juce_malloc (width * height * sizeof (uint32));
  363. int index = 0;
  364. for (int y = 0; y < height; ++y)
  365. for (int x = 0; x < width; ++x)
  366. colour[index++] = image.getPixelAt (x, y).getARGB();
  367. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  368. 0, (char*) colour, width, height, 32, 0);
  369. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  370. width, height, 24);
  371. GC gc = XCreateGC (display, pixmap, 0, 0);
  372. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  373. XFreeGC (display, gc);
  374. juce_free (colour);
  375. return pixmap;
  376. }
  377. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  378. {
  379. const int width = image.getWidth();
  380. const int height = image.getHeight();
  381. const int stride = (width + 7) >> 3;
  382. uint8* const mask = (uint8*) juce_calloc (stride * height);
  383. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  384. for (int y = 0; y < height; ++y)
  385. {
  386. for (int x = 0; x < width; ++x)
  387. {
  388. const uint8 bit = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  389. const int offset = y * stride + (x >> 3);
  390. if (image.getPixelAt (x, y).getAlpha() >= 128)
  391. mask[offset] |= bit;
  392. }
  393. }
  394. Pixmap pixmap = XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  395. (char*) mask, width, height, 1, 0, 1);
  396. juce_free (mask);
  397. return pixmap;
  398. }
  399. //==============================================================================
  400. class XBitmapImage : public Image
  401. {
  402. public:
  403. //==============================================================================
  404. XBitmapImage (const PixelFormat format_, const int w, const int h,
  405. const bool clearImage, const bool is16Bit_)
  406. : Image (format_, w, h),
  407. is16Bit (is16Bit_)
  408. {
  409. jassert (format_ == RGB || format_ == ARGB);
  410. pixelStride = (format_ == RGB) ? 3 : 4;
  411. lineStride = ((w * pixelStride + 3) & ~3);
  412. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  413. #if JUCE_USE_XSHM
  414. usingXShm = false;
  415. if ((! is16Bit) && isShmAvailable())
  416. {
  417. zerostruct (segmentInfo);
  418. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  419. if (xImage != 0)
  420. {
  421. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  422. xImage->bytes_per_line * xImage->height,
  423. IPC_CREAT | 0777)) >= 0)
  424. {
  425. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  426. if (segmentInfo.shmaddr != (void*) -1)
  427. {
  428. segmentInfo.readOnly = False;
  429. xImage->data = segmentInfo.shmaddr;
  430. imageData = (uint8*) segmentInfo.shmaddr;
  431. XSync (display, False);
  432. if (XShmAttach (display, &segmentInfo) != 0)
  433. {
  434. XSync (display, False);
  435. usingXShm = true;
  436. }
  437. else
  438. {
  439. jassertfalse
  440. }
  441. }
  442. else
  443. {
  444. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  445. }
  446. }
  447. }
  448. }
  449. if (! usingXShm)
  450. #endif
  451. {
  452. imageData = (uint8*) juce_malloc (lineStride * h);
  453. if (format_ == ARGB && clearImage)
  454. zeromem (imageData, h * lineStride);
  455. xImage = (XImage*) juce_calloc (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 (is16Bit)
  472. {
  473. const int pixelStride = 2;
  474. const int lineStride = ((w * pixelStride + 3) & ~3);
  475. xImage->data = (char*) juce_malloc (lineStride * h);
  476. xImage->bitmap_pad = 16;
  477. xImage->depth = pixelStride * 8;
  478. xImage->bytes_per_line = lineStride;
  479. xImage->bits_per_pixel = pixelStride * 8;
  480. xImage->red_mask = visual->red_mask;
  481. xImage->green_mask = visual->green_mask;
  482. xImage->blue_mask = visual->blue_mask;
  483. }
  484. if (! XInitImage (xImage))
  485. {
  486. jassertfalse
  487. }
  488. }
  489. }
  490. ~XBitmapImage()
  491. {
  492. #if JUCE_USE_XSHM
  493. if (usingXShm)
  494. {
  495. XShmDetach (display, &segmentInfo);
  496. XFlush (display);
  497. XDestroyImage (xImage);
  498. shmdt (segmentInfo.shmaddr);
  499. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  500. }
  501. else
  502. #endif
  503. {
  504. juce_free (xImage->data);
  505. xImage->data = 0;
  506. XDestroyImage (xImage);
  507. }
  508. if (! is16Bit)
  509. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  510. }
  511. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  512. {
  513. static GC gc = 0;
  514. if (gc == 0)
  515. gc = DefaultGC (display, DefaultScreen (display));
  516. if (is16Bit)
  517. {
  518. const uint32 rMask = xImage->red_mask;
  519. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  520. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  521. const uint32 gMask = xImage->green_mask;
  522. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  523. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  524. const uint32 bMask = xImage->blue_mask;
  525. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  526. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  527. int ls, ps;
  528. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  529. jassert (! isARGB())
  530. for (int y = sy; y < sy + dh; ++y)
  531. {
  532. const uint8* p = pixels + y * ls + sx * ps;
  533. for (int x = sx; x < sx + dw; ++x)
  534. {
  535. const PixelRGB* const pixel = (const PixelRGB*) p;
  536. p += ps;
  537. XPutPixel (xImage, x, y,
  538. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  539. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  540. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  541. }
  542. }
  543. releasePixelDataReadOnly (pixels);
  544. }
  545. // blit results to screen.
  546. #if JUCE_USE_XSHM
  547. if (usingXShm)
  548. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  549. else
  550. #endif
  551. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  552. }
  553. //==============================================================================
  554. juce_UseDebuggingNewOperator
  555. private:
  556. XImage* xImage;
  557. const bool is16Bit;
  558. #if JUCE_USE_XSHM
  559. XShmSegmentInfo segmentInfo;
  560. bool usingXShm;
  561. #endif
  562. static int getShiftNeeded (const uint32 mask) throw()
  563. {
  564. for (int i = 32; --i >= 0;)
  565. if (((mask >> i) & 1) != 0)
  566. return i - 7;
  567. jassertfalse
  568. return 0;
  569. }
  570. };
  571. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  572. //==============================================================================
  573. class LinuxComponentPeer : public ComponentPeer
  574. {
  575. public:
  576. //==============================================================================
  577. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  578. : ComponentPeer (component, windowStyleFlags),
  579. windowH (0),
  580. parentWindow (0),
  581. wx (0),
  582. wy (0),
  583. ww (0),
  584. wh (0),
  585. taskbarImage (0),
  586. fullScreen (false),
  587. entered (false),
  588. mapped (false)
  589. {
  590. // it's dangerous to create a window on a thread other than the message thread..
  591. checkMessageManagerIsLocked
  592. repainter = new LinuxRepaintManager (this);
  593. createWindow();
  594. setTitle (component->getName());
  595. }
  596. ~LinuxComponentPeer()
  597. {
  598. // it's dangerous to delete a window on a thread other than the message thread..
  599. checkMessageManagerIsLocked
  600. deleteTaskBarIcon();
  601. deleteIconPixmaps();
  602. destroyWindow();
  603. windowH = 0;
  604. delete repainter;
  605. }
  606. //==============================================================================
  607. void* getNativeHandle() const
  608. {
  609. return (void*) windowH;
  610. }
  611. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  612. {
  613. XPointer peer = 0;
  614. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  615. {
  616. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  617. peer = 0;
  618. }
  619. return (LinuxComponentPeer*) peer;
  620. }
  621. void setVisible (bool shouldBeVisible)
  622. {
  623. if (shouldBeVisible)
  624. XMapWindow (display, windowH);
  625. else
  626. XUnmapWindow (display, windowH);
  627. }
  628. void setTitle (const String& title)
  629. {
  630. setWindowTitle (windowH, title);
  631. }
  632. void setPosition (int x, int y)
  633. {
  634. setBounds (x, y, ww, wh, false);
  635. }
  636. void setSize (int w, int h)
  637. {
  638. setBounds (wx, wy, w, h, false);
  639. }
  640. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  641. {
  642. fullScreen = isNowFullScreen;
  643. if (windowH != 0)
  644. {
  645. const ComponentDeletionWatcher deletionChecker (component);
  646. wx = x;
  647. wy = y;
  648. ww = jmax (1, w);
  649. wh = jmax (1, h);
  650. if (! mapped)
  651. {
  652. // Make sure the Window manager does what we want
  653. XSizeHints* hints = XAllocSizeHints();
  654. hints->flags = USSize | USPosition;
  655. hints->width = ww + windowBorder.getLeftAndRight();
  656. hints->height = wh + windowBorder.getTopAndBottom();
  657. hints->x = wx - windowBorder.getLeft();
  658. hints->y = wy - windowBorder.getTop();
  659. XSetWMNormalHints (display, windowH, hints);
  660. XFree (hints);
  661. }
  662. XMoveResizeWindow (display, windowH,
  663. wx - windowBorder.getLeft(),
  664. wy - windowBorder.getTop(),
  665. ww + windowBorder.getLeftAndRight(),
  666. wh + windowBorder.getTopAndBottom());
  667. if (! deletionChecker.hasBeenDeleted())
  668. {
  669. updateBorderSize();
  670. handleMovedOrResized();
  671. }
  672. }
  673. }
  674. void getBounds (int& x, int& y, int& w, int& h) const
  675. {
  676. x = wx;
  677. y = wy;
  678. w = ww;
  679. h = wh;
  680. }
  681. int getScreenX() const
  682. {
  683. return wx;
  684. }
  685. int getScreenY() const
  686. {
  687. return wy;
  688. }
  689. void relativePositionToGlobal (int& x, int& y)
  690. {
  691. x += wx;
  692. y += wy;
  693. }
  694. void globalPositionToRelative (int& x, int& y)
  695. {
  696. x -= wx;
  697. y -= wy;
  698. }
  699. void setMinimised (bool shouldBeMinimised)
  700. {
  701. if (shouldBeMinimised)
  702. {
  703. Window root = RootWindow (display, DefaultScreen (display));
  704. XClientMessageEvent clientMsg;
  705. clientMsg.display = display;
  706. clientMsg.window = windowH;
  707. clientMsg.type = ClientMessage;
  708. clientMsg.format = 32;
  709. clientMsg.message_type = wm_ChangeState;
  710. clientMsg.data.l[0] = IconicState;
  711. XSendEvent (display, root, false,
  712. SubstructureRedirectMask | SubstructureNotifyMask,
  713. (XEvent*) &clientMsg);
  714. }
  715. else
  716. {
  717. setVisible (true);
  718. }
  719. }
  720. bool isMinimised() const
  721. {
  722. bool minimised = false;
  723. unsigned char* stateProp;
  724. unsigned long nitems, bytesLeft;
  725. Atom actualType;
  726. int actualFormat;
  727. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  728. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  729. &stateProp) == Success
  730. && actualType == wm_State
  731. && actualFormat == 32
  732. && nitems > 0)
  733. {
  734. if (((unsigned long*) stateProp)[0] == IconicState)
  735. minimised = true;
  736. XFree (stateProp);
  737. }
  738. return minimised;
  739. }
  740. void setFullScreen (const bool shouldBeFullScreen)
  741. {
  742. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  743. setMinimised (false);
  744. if (fullScreen != shouldBeFullScreen)
  745. {
  746. if (shouldBeFullScreen)
  747. r = Desktop::getInstance().getMainMonitorArea();
  748. if (! r.isEmpty())
  749. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  750. getComponent()->repaint();
  751. }
  752. }
  753. bool isFullScreen() const
  754. {
  755. return fullScreen;
  756. }
  757. bool isChildWindowOf (Window possibleParent) const
  758. {
  759. Window* windowList = 0;
  760. uint32 windowListSize = 0;
  761. Window parent, root;
  762. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  763. {
  764. if (windowList != 0)
  765. XFree (windowList);
  766. return parent == possibleParent;
  767. }
  768. return false;
  769. }
  770. bool isFrontWindow() const
  771. {
  772. Window* windowList = 0;
  773. uint32 windowListSize = 0;
  774. bool result = false;
  775. Window parent, root = RootWindow (display, DefaultScreen (display));
  776. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  777. {
  778. for (int i = windowListSize; --i >= 0;)
  779. {
  780. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  781. if (peer != 0)
  782. {
  783. result = (peer == this);
  784. break;
  785. }
  786. }
  787. }
  788. if (windowList != 0)
  789. XFree (windowList);
  790. return result;
  791. }
  792. bool contains (int x, int y, bool trueIfInAChildWindow) const
  793. {
  794. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  795. if (((unsigned int) x) >= (unsigned int) ww
  796. || ((unsigned int) y) >= (unsigned int) wh)
  797. return false;
  798. bool inFront = false;
  799. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  800. {
  801. Component* const c = Desktop::getInstance().getComponent (i);
  802. if (inFront)
  803. {
  804. if (c->contains (x + wx - c->getScreenX(),
  805. y + wy - c->getScreenY()))
  806. {
  807. return false;
  808. }
  809. }
  810. else if (c == getComponent())
  811. {
  812. inFront = true;
  813. }
  814. }
  815. if (trueIfInAChildWindow)
  816. return true;
  817. ::Window root, child;
  818. unsigned int bw, depth;
  819. int wx, wy, w, h;
  820. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  821. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  822. &bw, &depth))
  823. {
  824. return false;
  825. }
  826. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  827. return false;
  828. return child == None;
  829. }
  830. const BorderSize getFrameSize() const
  831. {
  832. return BorderSize();
  833. }
  834. bool setAlwaysOnTop (bool alwaysOnTop)
  835. {
  836. if (windowH != 0)
  837. {
  838. const bool wasVisible = component->isVisible();
  839. if (wasVisible)
  840. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  841. XSetWindowAttributes swa;
  842. swa.override_redirect = alwaysOnTop ? True : False;
  843. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  844. if (wasVisible)
  845. setVisible (true);
  846. }
  847. return true;
  848. }
  849. void toFront (bool makeActive)
  850. {
  851. if (makeActive)
  852. {
  853. setVisible (true);
  854. grabFocus();
  855. }
  856. XEvent ev;
  857. ev.xclient.type = ClientMessage;
  858. ev.xclient.serial = 0;
  859. ev.xclient.send_event = True;
  860. ev.xclient.message_type = wm_ActiveWin;
  861. ev.xclient.window = windowH;
  862. ev.xclient.format = 32;
  863. ev.xclient.data.l[0] = 2;
  864. ev.xclient.data.l[1] = CurrentTime;
  865. ev.xclient.data.l[2] = 0;
  866. ev.xclient.data.l[3] = 0;
  867. ev.xclient.data.l[4] = 0;
  868. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  869. False,
  870. SubstructureRedirectMask | SubstructureNotifyMask,
  871. &ev);
  872. XSync (display, False);
  873. handleBroughtToFront();
  874. }
  875. void toBehind (ComponentPeer* other)
  876. {
  877. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  878. jassert (otherPeer != 0); // wrong type of window?
  879. if (otherPeer != 0)
  880. {
  881. setMinimised (false);
  882. Window newStack[] = { otherPeer->windowH, windowH };
  883. XRestackWindows (display, newStack, 2);
  884. }
  885. }
  886. bool isFocused() const
  887. {
  888. int revert;
  889. Window focusedWindow = 0;
  890. XGetInputFocus (display, &focusedWindow, &revert);
  891. return focusedWindow == windowH;
  892. }
  893. void grabFocus()
  894. {
  895. XWindowAttributes atts;
  896. if (windowH != 0
  897. && XGetWindowAttributes (display, windowH, &atts)
  898. && atts.map_state == IsViewable
  899. && ! isFocused())
  900. {
  901. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  902. isActiveApplication = true;
  903. }
  904. }
  905. void textInputRequired (int /*x*/, int /*y*/)
  906. {
  907. }
  908. void repaint (int x, int y, int w, int h)
  909. {
  910. if (Rectangle::intersectRectangles (x, y, w, h,
  911. 0, 0,
  912. getComponent()->getWidth(),
  913. getComponent()->getHeight()))
  914. {
  915. repainter->repaint (x, y, w, h);
  916. }
  917. }
  918. void performAnyPendingRepaintsNow()
  919. {
  920. repainter->performAnyPendingRepaintsNow();
  921. }
  922. void setIcon (const Image& newIcon)
  923. {
  924. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  925. uint32* const data = (uint32*) juce_malloc (dataSize * sizeof (uint32));
  926. int index = 0;
  927. data[index++] = newIcon.getWidth();
  928. data[index++] = newIcon.getHeight();
  929. for (int y = 0; y < newIcon.getHeight(); ++y)
  930. for (int x = 0; x < newIcon.getWidth(); ++x)
  931. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  932. XChangeProperty (display, windowH,
  933. XInternAtom (display, "_NET_WM_ICON", False),
  934. XA_CARDINAL, 32, PropModeReplace,
  935. (unsigned char*) data, dataSize);
  936. juce_free (data);
  937. deleteIconPixmaps();
  938. XWMHints* wmHints = XGetWMHints (display, windowH);
  939. if (wmHints == 0)
  940. wmHints = XAllocWMHints();
  941. wmHints->flags |= IconPixmapHint | IconMaskHint;
  942. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  943. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  944. XSetWMHints (display, windowH, wmHints);
  945. XFree (wmHints);
  946. XSync (display, False);
  947. }
  948. void deleteIconPixmaps()
  949. {
  950. XWMHints* wmHints = XGetWMHints (display, windowH);
  951. if (wmHints != 0)
  952. {
  953. if ((wmHints->flags & IconPixmapHint) != 0)
  954. {
  955. wmHints->flags &= ~IconPixmapHint;
  956. XFreePixmap (display, wmHints->icon_pixmap);
  957. }
  958. if ((wmHints->flags & IconMaskHint) != 0)
  959. {
  960. wmHints->flags &= ~IconMaskHint;
  961. XFreePixmap (display, wmHints->icon_mask);
  962. }
  963. XSetWMHints (display, windowH, wmHints);
  964. XFree (wmHints);
  965. }
  966. }
  967. //==============================================================================
  968. void handleWindowMessage (XEvent* event)
  969. {
  970. switch (event->xany.type)
  971. {
  972. case 2: // 'KeyPress'
  973. {
  974. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  975. updateKeyStates (keyEvent->keycode, true);
  976. char utf8 [64];
  977. zeromem (utf8, sizeof (utf8));
  978. KeySym sym;
  979. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  980. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  981. int keyCode = (int) unicodeChar;
  982. if (keyCode < 0x20)
  983. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  984. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  985. const int oldMods = currentModifiers;
  986. bool keyPressed = false;
  987. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  988. if ((sym & 0xff00) == 0xff00)
  989. {
  990. // Translate keypad
  991. if (sym == XK_KP_Divide)
  992. keyCode = XK_slash;
  993. else if (sym == XK_KP_Multiply)
  994. keyCode = XK_asterisk;
  995. else if (sym == XK_KP_Subtract)
  996. keyCode = XK_hyphen;
  997. else if (sym == XK_KP_Add)
  998. keyCode = XK_plus;
  999. else if (sym == XK_KP_Enter)
  1000. keyCode = XK_Return;
  1001. else if (sym == XK_KP_Decimal)
  1002. keyCode = numLock ? XK_period : XK_Delete;
  1003. else if (sym == XK_KP_0)
  1004. keyCode = numLock ? XK_0 : XK_Insert;
  1005. else if (sym == XK_KP_1)
  1006. keyCode = numLock ? XK_1 : XK_End;
  1007. else if (sym == XK_KP_2)
  1008. keyCode = numLock ? XK_2 : XK_Down;
  1009. else if (sym == XK_KP_3)
  1010. keyCode = numLock ? XK_3 : XK_Page_Down;
  1011. else if (sym == XK_KP_4)
  1012. keyCode = numLock ? XK_4 : XK_Left;
  1013. else if (sym == XK_KP_5)
  1014. keyCode = XK_5;
  1015. else if (sym == XK_KP_6)
  1016. keyCode = numLock ? XK_6 : XK_Right;
  1017. else if (sym == XK_KP_7)
  1018. keyCode = numLock ? XK_7 : XK_Home;
  1019. else if (sym == XK_KP_8)
  1020. keyCode = numLock ? XK_8 : XK_Up;
  1021. else if (sym == XK_KP_9)
  1022. keyCode = numLock ? XK_9 : XK_Page_Up;
  1023. switch (sym)
  1024. {
  1025. case XK_Left:
  1026. case XK_Right:
  1027. case XK_Up:
  1028. case XK_Down:
  1029. case XK_Page_Up:
  1030. case XK_Page_Down:
  1031. case XK_End:
  1032. case XK_Home:
  1033. case XK_Delete:
  1034. case XK_Insert:
  1035. keyPressed = true;
  1036. keyCode = (sym & 0xff) | extendedKeyModifier;
  1037. break;
  1038. case XK_Tab:
  1039. case XK_Return:
  1040. case XK_Escape:
  1041. case XK_BackSpace:
  1042. keyPressed = true;
  1043. keyCode &= 0xff;
  1044. break;
  1045. default:
  1046. {
  1047. if (sym >= XK_F1 && sym <= XK_F16)
  1048. {
  1049. keyPressed = true;
  1050. keyCode = (sym & 0xff) | extendedKeyModifier;
  1051. }
  1052. break;
  1053. }
  1054. }
  1055. }
  1056. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  1057. keyPressed = true;
  1058. if (oldMods != currentModifiers)
  1059. handleModifierKeysChange();
  1060. if (keyDownChange)
  1061. handleKeyUpOrDown();
  1062. if (keyPressed)
  1063. handleKeyPress (keyCode, unicodeChar);
  1064. break;
  1065. }
  1066. case KeyRelease:
  1067. {
  1068. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  1069. updateKeyStates (keyEvent->keycode, false);
  1070. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  1071. const int oldMods = currentModifiers;
  1072. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  1073. if (oldMods != currentModifiers)
  1074. handleModifierKeysChange();
  1075. if (keyDownChange)
  1076. handleKeyUpOrDown();
  1077. break;
  1078. }
  1079. case ButtonPress:
  1080. {
  1081. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  1082. bool buttonMsg = false;
  1083. bool wheelUpMsg = false;
  1084. bool wheelDownMsg = false;
  1085. const int map = pointerMap [buttonPressEvent->button - Button1];
  1086. if (map == LeftButton)
  1087. {
  1088. currentModifiers |= ModifierKeys::leftButtonModifier;
  1089. buttonMsg = true;
  1090. }
  1091. else if (map == RightButton)
  1092. {
  1093. currentModifiers |= ModifierKeys::rightButtonModifier;
  1094. buttonMsg = true;
  1095. }
  1096. else if (map == MiddleButton)
  1097. {
  1098. currentModifiers |= ModifierKeys::middleButtonModifier;
  1099. buttonMsg = true;
  1100. }
  1101. else if (map == WheelUp)
  1102. {
  1103. wheelUpMsg = true;
  1104. }
  1105. else if (map == WheelDown)
  1106. {
  1107. wheelDownMsg = true;
  1108. }
  1109. updateKeyModifiers (buttonPressEvent->state);
  1110. if (buttonMsg)
  1111. {
  1112. toFront (true);
  1113. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  1114. getEventTime (buttonPressEvent->time));
  1115. }
  1116. else if (wheelUpMsg || wheelDownMsg)
  1117. {
  1118. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  1119. getEventTime (buttonPressEvent->time));
  1120. }
  1121. lastMousePosX = lastMousePosY = 0x100000;
  1122. break;
  1123. }
  1124. case ButtonRelease:
  1125. {
  1126. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  1127. const int oldModifiers = currentModifiers;
  1128. const int map = pointerMap [buttonRelEvent->button - Button1];
  1129. if (map == LeftButton)
  1130. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  1131. else if (map == RightButton)
  1132. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  1133. else if (map == MiddleButton)
  1134. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  1135. updateKeyModifiers (buttonRelEvent->state);
  1136. handleMouseUp (oldModifiers,
  1137. buttonRelEvent->x, buttonRelEvent->y,
  1138. getEventTime (buttonRelEvent->time));
  1139. lastMousePosX = lastMousePosY = 0x100000;
  1140. break;
  1141. }
  1142. case MotionNotify:
  1143. {
  1144. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  1145. updateKeyModifiers (movedEvent->state);
  1146. int x, y, mouseMods;
  1147. getMousePos (x, y, mouseMods);
  1148. if (lastMousePosX != x || lastMousePosY != y)
  1149. {
  1150. lastMousePosX = x;
  1151. lastMousePosY = y;
  1152. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  1153. {
  1154. Window wRoot = 0, wParent = 0;
  1155. Window* wChild = 0;
  1156. unsigned int numChildren;
  1157. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  1158. if (wParent != 0
  1159. && wParent != windowH
  1160. && wParent != wRoot)
  1161. {
  1162. parentWindow = wParent;
  1163. updateBounds();
  1164. x -= getScreenX();
  1165. y -= getScreenY();
  1166. }
  1167. else
  1168. {
  1169. parentWindow = 0;
  1170. x -= getScreenX();
  1171. y -= getScreenY();
  1172. }
  1173. }
  1174. else
  1175. {
  1176. x -= getScreenX();
  1177. y -= getScreenY();
  1178. }
  1179. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  1180. handleMouseMove (x, y, getEventTime (movedEvent->time));
  1181. else
  1182. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  1183. }
  1184. break;
  1185. }
  1186. case EnterNotify:
  1187. {
  1188. lastMousePosX = lastMousePosY = 0x100000;
  1189. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  1190. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  1191. && ! entered)
  1192. {
  1193. updateKeyModifiers (enterEvent->state);
  1194. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  1195. entered = true;
  1196. }
  1197. break;
  1198. }
  1199. case LeaveNotify:
  1200. {
  1201. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  1202. // Suppress the normal leave if we've got a pointer grab, or if
  1203. // it's a bogus one caused by clicking a mouse button when running
  1204. // in a Window manager
  1205. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  1206. && leaveEvent->mode == NotifyNormal)
  1207. || leaveEvent->mode == NotifyUngrab)
  1208. {
  1209. updateKeyModifiers (leaveEvent->state);
  1210. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  1211. entered = false;
  1212. }
  1213. break;
  1214. }
  1215. case FocusIn:
  1216. {
  1217. isActiveApplication = true;
  1218. if (isFocused())
  1219. handleFocusGain();
  1220. break;
  1221. }
  1222. case FocusOut:
  1223. {
  1224. isActiveApplication = false;
  1225. if (! isFocused())
  1226. handleFocusLoss();
  1227. break;
  1228. }
  1229. case Expose:
  1230. {
  1231. // Batch together all pending expose events
  1232. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  1233. XEvent nextEvent;
  1234. if (exposeEvent->window != windowH)
  1235. {
  1236. Window child;
  1237. XTranslateCoordinates (display, exposeEvent->window, windowH,
  1238. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  1239. &child);
  1240. }
  1241. repaint (exposeEvent->x, exposeEvent->y,
  1242. exposeEvent->width, exposeEvent->height);
  1243. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  1244. {
  1245. XPeekEvent (display, (XEvent*) &nextEvent);
  1246. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  1247. break;
  1248. XNextEvent (display, (XEvent*) &nextEvent);
  1249. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  1250. repaint (nextExposeEvent->x, nextExposeEvent->y,
  1251. nextExposeEvent->width, nextExposeEvent->height);
  1252. }
  1253. break;
  1254. }
  1255. case CirculateNotify:
  1256. case CreateNotify:
  1257. case DestroyNotify:
  1258. // Think we can ignore these
  1259. break;
  1260. case ConfigureNotify:
  1261. {
  1262. updateBounds();
  1263. updateBorderSize();
  1264. handleMovedOrResized();
  1265. // if the native title bar is dragged, need to tell any active menus, etc.
  1266. if ((styleFlags & windowHasTitleBar) != 0
  1267. && component->isCurrentlyBlockedByAnotherModalComponent())
  1268. {
  1269. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  1270. if (currentModalComp != 0)
  1271. currentModalComp->inputAttemptWhenModal();
  1272. }
  1273. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  1274. if (confEvent->window == windowH
  1275. && confEvent->above != 0
  1276. && isFrontWindow())
  1277. {
  1278. handleBroughtToFront();
  1279. }
  1280. break;
  1281. }
  1282. case ReparentNotify:
  1283. case GravityNotify:
  1284. {
  1285. parentWindow = 0;
  1286. Window wRoot = 0;
  1287. Window* wChild = 0;
  1288. unsigned int numChildren;
  1289. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  1290. if (parentWindow == windowH || parentWindow == wRoot)
  1291. parentWindow = 0;
  1292. updateBounds();
  1293. updateBorderSize();
  1294. handleMovedOrResized();
  1295. break;
  1296. }
  1297. case MapNotify:
  1298. mapped = true;
  1299. handleBroughtToFront();
  1300. break;
  1301. case UnmapNotify:
  1302. mapped = false;
  1303. break;
  1304. case MappingNotify:
  1305. {
  1306. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  1307. if (mappingEvent->request != MappingPointer)
  1308. {
  1309. // Deal with modifier/keyboard mapping
  1310. XRefreshKeyboardMapping (mappingEvent);
  1311. getModifierMapping();
  1312. }
  1313. break;
  1314. }
  1315. case ClientMessage:
  1316. {
  1317. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  1318. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  1319. {
  1320. const Atom atom = (Atom) clientMsg->data.l[0];
  1321. if (atom == wm_ProtocolList [TAKE_FOCUS])
  1322. {
  1323. XWindowAttributes atts;
  1324. if (clientMsg->window != 0
  1325. && XGetWindowAttributes (display, clientMsg->window, &atts))
  1326. {
  1327. if (atts.map_state == IsViewable)
  1328. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  1329. }
  1330. }
  1331. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  1332. {
  1333. handleUserClosingWindow();
  1334. }
  1335. }
  1336. else if (clientMsg->message_type == XA_XdndEnter)
  1337. {
  1338. handleDragAndDropEnter (clientMsg);
  1339. }
  1340. else if (clientMsg->message_type == XA_XdndLeave)
  1341. {
  1342. resetDragAndDrop();
  1343. }
  1344. else if (clientMsg->message_type == XA_XdndPosition)
  1345. {
  1346. handleDragAndDropPosition (clientMsg);
  1347. }
  1348. else if (clientMsg->message_type == XA_XdndDrop)
  1349. {
  1350. handleDragAndDropDrop (clientMsg);
  1351. }
  1352. else if (clientMsg->message_type == XA_XdndStatus)
  1353. {
  1354. handleDragAndDropStatus (clientMsg);
  1355. }
  1356. else if (clientMsg->message_type == XA_XdndFinished)
  1357. {
  1358. resetDragAndDrop();
  1359. }
  1360. break;
  1361. }
  1362. case SelectionNotify:
  1363. handleDragAndDropSelection (event);
  1364. break;
  1365. case SelectionClear:
  1366. case SelectionRequest:
  1367. break;
  1368. default:
  1369. break;
  1370. }
  1371. }
  1372. void showMouseCursor (Cursor cursor) throw()
  1373. {
  1374. XDefineCursor (display, windowH, cursor);
  1375. }
  1376. //==============================================================================
  1377. void setTaskBarIcon (const Image& image)
  1378. {
  1379. deleteTaskBarIcon();
  1380. taskbarImage = image.createCopy();
  1381. Screen* const screen = XDefaultScreenOfDisplay (display);
  1382. const int screenNumber = XScreenNumberOfScreen (screen);
  1383. char screenAtom[32];
  1384. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  1385. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  1386. XGrabServer (display);
  1387. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  1388. if (managerWin != None)
  1389. XSelectInput (display, managerWin, StructureNotifyMask);
  1390. XUngrabServer (display);
  1391. XFlush (display);
  1392. if (managerWin != None)
  1393. {
  1394. XEvent ev;
  1395. zerostruct (ev);
  1396. ev.xclient.type = ClientMessage;
  1397. ev.xclient.window = managerWin;
  1398. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  1399. ev.xclient.format = 32;
  1400. ev.xclient.data.l[0] = CurrentTime;
  1401. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  1402. ev.xclient.data.l[2] = windowH;
  1403. ev.xclient.data.l[3] = 0;
  1404. ev.xclient.data.l[4] = 0;
  1405. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  1406. XSync (display, False);
  1407. }
  1408. // For older KDE's ...
  1409. long atomData = 1;
  1410. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  1411. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  1412. // For more recent KDE's...
  1413. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  1414. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  1415. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  1416. XSizeHints* hints = XAllocSizeHints();
  1417. hints->flags = PMinSize;
  1418. hints->min_width = 22;
  1419. hints->min_height = 22;
  1420. XSetWMNormalHints (display, windowH, hints);
  1421. XFree (hints);
  1422. }
  1423. void deleteTaskBarIcon()
  1424. {
  1425. deleteAndZero (taskbarImage);
  1426. }
  1427. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  1428. //==============================================================================
  1429. juce_UseDebuggingNewOperator
  1430. bool dontRepaint;
  1431. private:
  1432. //==============================================================================
  1433. class LinuxRepaintManager : public Timer
  1434. {
  1435. public:
  1436. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  1437. : peer (peer_),
  1438. image (0),
  1439. lastTimeImageUsed (0)
  1440. {
  1441. #if JUCE_USE_XSHM
  1442. useARGBImagesForRendering = isShmAvailable();
  1443. if (useARGBImagesForRendering)
  1444. {
  1445. XShmSegmentInfo segmentinfo;
  1446. XImage* const testImage
  1447. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  1448. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  1449. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  1450. XDestroyImage (testImage);
  1451. }
  1452. #endif
  1453. }
  1454. ~LinuxRepaintManager()
  1455. {
  1456. delete image;
  1457. }
  1458. void timerCallback()
  1459. {
  1460. if (! regionsNeedingRepaint.isEmpty())
  1461. {
  1462. stopTimer();
  1463. performAnyPendingRepaintsNow();
  1464. }
  1465. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  1466. {
  1467. stopTimer();
  1468. deleteAndZero (image);
  1469. }
  1470. }
  1471. void repaint (int x, int y, int w, int h)
  1472. {
  1473. if (! isTimerRunning())
  1474. startTimer (repaintTimerPeriod);
  1475. regionsNeedingRepaint.add (x, y, w, h);
  1476. }
  1477. void performAnyPendingRepaintsNow()
  1478. {
  1479. peer->clearMaskedRegion();
  1480. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  1481. if (! totalArea.isEmpty())
  1482. {
  1483. if (image == 0 || image->getWidth() < totalArea.getWidth()
  1484. || image->getHeight() < totalArea.getHeight())
  1485. {
  1486. delete image;
  1487. #if JUCE_USE_XSHM
  1488. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  1489. : Image::RGB,
  1490. #else
  1491. image = new XBitmapImage (Image::RGB,
  1492. #endif
  1493. (totalArea.getWidth() + 31) & ~31,
  1494. (totalArea.getHeight() + 31) & ~31,
  1495. false,
  1496. peer->depthIs16Bit);
  1497. }
  1498. startTimer (repaintTimerPeriod);
  1499. LowLevelGraphicsSoftwareRenderer context (*image);
  1500. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  1501. if (context.reduceClipRegion (regionsNeedingRepaint))
  1502. peer->handlePaint (context);
  1503. if (! peer->maskedRegion.isEmpty())
  1504. regionsNeedingRepaint.subtract (peer->maskedRegion);
  1505. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  1506. {
  1507. const Rectangle& r = *i.getRectangle();
  1508. image->blitToWindow (peer->windowH,
  1509. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  1510. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  1511. }
  1512. }
  1513. regionsNeedingRepaint.clear();
  1514. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  1515. startTimer (repaintTimerPeriod);
  1516. }
  1517. private:
  1518. LinuxComponentPeer* const peer;
  1519. XBitmapImage* image;
  1520. uint32 lastTimeImageUsed;
  1521. RectangleList regionsNeedingRepaint;
  1522. #if JUCE_USE_XSHM
  1523. bool useARGBImagesForRendering;
  1524. #endif
  1525. LinuxRepaintManager (const LinuxRepaintManager&);
  1526. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  1527. };
  1528. LinuxRepaintManager* repainter;
  1529. friend class LinuxRepaintManager;
  1530. Window windowH, parentWindow;
  1531. int wx, wy, ww, wh;
  1532. Image* taskbarImage;
  1533. bool fullScreen, entered, mapped, depthIs16Bit;
  1534. BorderSize windowBorder;
  1535. //==============================================================================
  1536. void removeWindowDecorations (Window wndH)
  1537. {
  1538. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  1539. if (hints != None)
  1540. {
  1541. typedef struct
  1542. {
  1543. unsigned long flags;
  1544. unsigned long functions;
  1545. unsigned long decorations;
  1546. long input_mode;
  1547. unsigned long status;
  1548. } MotifWmHints;
  1549. MotifWmHints motifHints;
  1550. zerostruct (motifHints);
  1551. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  1552. motifHints.decorations = 0;
  1553. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  1554. (unsigned char*) &motifHints, 4);
  1555. }
  1556. hints = XInternAtom (display, "_WIN_HINTS", True);
  1557. if (hints != None)
  1558. {
  1559. long gnomeHints = 0;
  1560. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  1561. (unsigned char*) &gnomeHints, 1);
  1562. }
  1563. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  1564. if (hints != None)
  1565. {
  1566. long kwmHints = 2; /*KDE_tinyDecoration*/
  1567. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  1568. (unsigned char*) &kwmHints, 1);
  1569. }
  1570. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  1571. if (hints != None)
  1572. {
  1573. long netHints [2];
  1574. netHints[0] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  1575. if ((styleFlags & windowIsTemporary) != 0)
  1576. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  1577. else
  1578. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  1579. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  1580. (unsigned char*) &netHints, 2);
  1581. }
  1582. }
  1583. void addWindowButtons (Window wndH)
  1584. {
  1585. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  1586. if (hints != None)
  1587. {
  1588. typedef struct
  1589. {
  1590. unsigned long flags;
  1591. unsigned long functions;
  1592. unsigned long decorations;
  1593. long input_mode;
  1594. unsigned long status;
  1595. } MotifWmHints;
  1596. MotifWmHints motifHints;
  1597. zerostruct (motifHints);
  1598. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  1599. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  1600. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  1601. if ((styleFlags & windowHasCloseButton) != 0)
  1602. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  1603. if ((styleFlags & windowHasMinimiseButton) != 0)
  1604. {
  1605. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  1606. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  1607. }
  1608. if ((styleFlags & windowHasMaximiseButton) != 0)
  1609. {
  1610. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  1611. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  1612. }
  1613. if ((styleFlags & windowIsResizable) != 0)
  1614. {
  1615. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  1616. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  1617. }
  1618. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  1619. }
  1620. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  1621. if (hints != None)
  1622. {
  1623. long netHints [6];
  1624. int num = 0;
  1625. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  1626. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  1627. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  1628. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  1629. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  1630. (unsigned char*) &netHints, num);
  1631. }
  1632. }
  1633. void createWindow()
  1634. {
  1635. static bool atomsInitialised = false;
  1636. if (! atomsInitialised)
  1637. {
  1638. atomsInitialised = true;
  1639. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  1640. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  1641. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  1642. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  1643. wm_State = XInternAtom (display, "WM_STATE", 1);
  1644. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  1645. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  1646. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  1647. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  1648. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  1649. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  1650. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  1651. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  1652. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  1653. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  1654. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  1655. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  1656. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  1657. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  1658. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  1659. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  1660. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  1661. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  1662. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  1663. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  1664. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  1665. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  1666. }
  1667. resetDragAndDrop();
  1668. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  1669. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  1670. allowedMimeTypeAtoms [1] = XA_OtherMime;
  1671. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  1672. allowedActions [0] = XA_XdndActionMove;
  1673. allowedActions [1] = XA_XdndActionCopy;
  1674. allowedActions [2] = XA_XdndActionLink;
  1675. allowedActions [3] = XA_XdndActionAsk;
  1676. allowedActions [4] = XA_XdndActionPrivate;
  1677. // Get defaults for various properties
  1678. const int screen = DefaultScreen (display);
  1679. Window root = RootWindow (display, screen);
  1680. // Attempt to create a 24-bit window on the default screen. If this is not
  1681. // possible then exit
  1682. XVisualInfo desiredVisual;
  1683. desiredVisual.screen = screen;
  1684. desiredVisual.depth = 24;
  1685. depthIs16Bit = false;
  1686. int numVisuals;
  1687. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  1688. &desiredVisual, &numVisuals);
  1689. if (numVisuals < 1 || visuals == 0)
  1690. {
  1691. XFree (visuals);
  1692. desiredVisual.depth = 16;
  1693. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  1694. &desiredVisual, &numVisuals);
  1695. if (numVisuals < 1 || visuals == 0)
  1696. {
  1697. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  1698. Process::terminate();
  1699. }
  1700. depthIs16Bit = true;
  1701. }
  1702. XFree (visuals);
  1703. // Set up the window attributes
  1704. XSetWindowAttributes swa;
  1705. swa.border_pixel = 0;
  1706. swa.background_pixmap = None;
  1707. swa.colormap = DefaultColormap (display, screen);
  1708. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  1709. swa.event_mask = eventMask;
  1710. Window wndH = XCreateWindow (display, root,
  1711. 0, 0, 1, 1,
  1712. 0, 0, InputOutput, (Visual*) CopyFromParent,
  1713. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  1714. &swa);
  1715. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  1716. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  1717. GrabModeAsync, GrabModeAsync, None, None);
  1718. // Set the window context to identify the window handle object
  1719. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  1720. {
  1721. // Failed
  1722. jassertfalse
  1723. Logger::outputDebugString ("Failed to create context information for window.\n");
  1724. XDestroyWindow (display, wndH);
  1725. wndH = 0;
  1726. }
  1727. // Set window manager hints
  1728. XWMHints* wmHints = XAllocWMHints();
  1729. wmHints->flags = InputHint | StateHint;
  1730. wmHints->input = True; // Locally active input model
  1731. wmHints->initial_state = NormalState;
  1732. XSetWMHints (display, wndH, wmHints);
  1733. XFree (wmHints);
  1734. if ((styleFlags & windowIsSemiTransparent) != 0)
  1735. {
  1736. //xxx
  1737. }
  1738. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  1739. {
  1740. //xxx
  1741. }
  1742. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  1743. if ((styleFlags & windowHasTitleBar) == 0)
  1744. removeWindowDecorations (wndH);
  1745. else
  1746. addWindowButtons (wndH);
  1747. // Set window manager protocols
  1748. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  1749. (unsigned char*) wm_ProtocolList, 2);
  1750. // Set drag and drop flags
  1751. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  1752. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  1753. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  1754. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  1755. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  1756. (const unsigned char*) "", 0);
  1757. unsigned long dndVersion = ourDndVersion;
  1758. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  1759. (const unsigned char*) &dndVersion, 1);
  1760. // Set window name
  1761. setWindowTitle (wndH, getComponent()->getName());
  1762. // Initialise the pointer and keyboard mapping
  1763. // This is not the same as the logical pointer mapping the X server uses:
  1764. // we don't mess with this.
  1765. static bool mappingInitialised = false;
  1766. if (! mappingInitialised)
  1767. {
  1768. mappingInitialised = true;
  1769. const int numButtons = XGetPointerMapping (display, 0, 0);
  1770. if (numButtons == 2)
  1771. {
  1772. pointerMap[0] = LeftButton;
  1773. pointerMap[1] = RightButton;
  1774. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  1775. }
  1776. else if (numButtons >= 3)
  1777. {
  1778. pointerMap[0] = LeftButton;
  1779. pointerMap[1] = MiddleButton;
  1780. pointerMap[2] = RightButton;
  1781. if (numButtons >= 5)
  1782. {
  1783. pointerMap[3] = WheelUp;
  1784. pointerMap[4] = WheelDown;
  1785. }
  1786. }
  1787. getModifierMapping();
  1788. }
  1789. windowH = wndH;
  1790. }
  1791. void destroyWindow()
  1792. {
  1793. XPointer handlePointer;
  1794. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  1795. XDeleteContext (display, (XID) windowH, improbableNumber);
  1796. XDestroyWindow (display, windowH);
  1797. // Wait for it to complete and then remove any events for this
  1798. // window from the event queue.
  1799. XSync (display, false);
  1800. XEvent event;
  1801. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  1802. {}
  1803. }
  1804. static int64 getEventTime (::Time t) throw()
  1805. {
  1806. static int64 eventTimeOffset = 0x12345678;
  1807. const int64 thisMessageTime = t;
  1808. if (eventTimeOffset == 0x12345678)
  1809. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  1810. return eventTimeOffset + thisMessageTime;
  1811. }
  1812. static void setWindowTitle (Window xwin, const char* const title) throw()
  1813. {
  1814. XTextProperty nameProperty;
  1815. char* strings[] = { (char*) title };
  1816. if (XStringListToTextProperty (strings, 1, &nameProperty))
  1817. {
  1818. XSetWMName (display, xwin, &nameProperty);
  1819. XSetWMIconName (display, xwin, &nameProperty);
  1820. XFree (nameProperty.value);
  1821. }
  1822. }
  1823. void updateBorderSize()
  1824. {
  1825. if ((styleFlags & windowHasTitleBar) == 0)
  1826. {
  1827. windowBorder = BorderSize (0);
  1828. }
  1829. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  1830. {
  1831. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  1832. if (hints != None)
  1833. {
  1834. unsigned char* data = 0;
  1835. unsigned long nitems, bytesLeft;
  1836. Atom actualType;
  1837. int actualFormat;
  1838. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  1839. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  1840. &data) == Success)
  1841. {
  1842. const unsigned long* const sizes = (const unsigned long*) data;
  1843. if (actualFormat == 32)
  1844. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  1845. (int) sizes[3], (int) sizes[1]);
  1846. XFree (data);
  1847. }
  1848. }
  1849. }
  1850. }
  1851. void updateBounds()
  1852. {
  1853. jassert (windowH != 0);
  1854. if (windowH != 0)
  1855. {
  1856. Window root, child;
  1857. unsigned int bw, depth;
  1858. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  1859. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  1860. &bw, &depth))
  1861. {
  1862. wx = wy = ww = wh = 0;
  1863. }
  1864. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  1865. {
  1866. wx = wy = 0;
  1867. }
  1868. }
  1869. }
  1870. //==============================================================================
  1871. void resetDragAndDrop()
  1872. {
  1873. dragAndDropFiles.clear();
  1874. lastDropX = lastDropY = -1;
  1875. dragAndDropCurrentMimeType = 0;
  1876. dragAndDropSourceWindow = 0;
  1877. srcMimeTypeAtomList.clear();
  1878. }
  1879. void sendDragAndDropMessage (XClientMessageEvent& msg)
  1880. {
  1881. msg.type = ClientMessage;
  1882. msg.display = display;
  1883. msg.window = dragAndDropSourceWindow;
  1884. msg.format = 32;
  1885. msg.data.l[0] = windowH;
  1886. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  1887. }
  1888. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  1889. {
  1890. XClientMessageEvent msg;
  1891. zerostruct (msg);
  1892. msg.message_type = XA_XdndStatus;
  1893. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  1894. msg.data.l[4] = dropAction;
  1895. sendDragAndDropMessage (msg);
  1896. }
  1897. void sendDragAndDropLeave()
  1898. {
  1899. XClientMessageEvent msg;
  1900. zerostruct (msg);
  1901. msg.message_type = XA_XdndLeave;
  1902. sendDragAndDropMessage (msg);
  1903. }
  1904. void sendDragAndDropFinish()
  1905. {
  1906. XClientMessageEvent msg;
  1907. zerostruct (msg);
  1908. msg.message_type = XA_XdndFinished;
  1909. sendDragAndDropMessage (msg);
  1910. }
  1911. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  1912. {
  1913. if ((clientMsg->data.l[1] & 1) == 0)
  1914. {
  1915. sendDragAndDropLeave();
  1916. if (dragAndDropFiles.size() > 0)
  1917. handleFileDragExit (dragAndDropFiles);
  1918. dragAndDropFiles.clear();
  1919. }
  1920. }
  1921. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  1922. {
  1923. if (dragAndDropSourceWindow == 0)
  1924. return;
  1925. dragAndDropSourceWindow = clientMsg->data.l[0];
  1926. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  1927. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  1928. if (lastDropX != dropX || lastDropY != dropY)
  1929. {
  1930. lastDropX = dropX;
  1931. lastDropY = dropY;
  1932. dragAndDropTimestamp = clientMsg->data.l[3];
  1933. Atom targetAction = XA_XdndActionCopy;
  1934. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  1935. {
  1936. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  1937. {
  1938. targetAction = allowedActions[i];
  1939. break;
  1940. }
  1941. }
  1942. sendDragAndDropStatus (true, targetAction);
  1943. if (dragAndDropFiles.size() == 0)
  1944. updateDraggedFileList (clientMsg);
  1945. if (dragAndDropFiles.size() > 0)
  1946. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  1947. }
  1948. }
  1949. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  1950. {
  1951. if (dragAndDropFiles.size() == 0)
  1952. updateDraggedFileList (clientMsg);
  1953. const StringArray files (dragAndDropFiles);
  1954. const int lastX = lastDropX, lastY = lastDropY;
  1955. sendDragAndDropFinish();
  1956. resetDragAndDrop();
  1957. if (files.size() > 0)
  1958. handleFileDragDrop (files, lastX, lastY);
  1959. }
  1960. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  1961. {
  1962. dragAndDropFiles.clear();
  1963. srcMimeTypeAtomList.clear();
  1964. dragAndDropCurrentMimeType = 0;
  1965. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  1966. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  1967. {
  1968. dragAndDropSourceWindow = 0;
  1969. return;
  1970. }
  1971. dragAndDropSourceWindow = clientMsg->data.l[0];
  1972. if ((clientMsg->data.l[1] & 1) != 0)
  1973. {
  1974. Atom actual;
  1975. int format;
  1976. unsigned long count = 0, remaining = 0;
  1977. unsigned char* data = 0;
  1978. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  1979. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  1980. &count, &remaining, &data);
  1981. if (data != 0)
  1982. {
  1983. if (actual == XA_ATOM && format == 32 && count != 0)
  1984. {
  1985. const unsigned long* const types = (const unsigned long*) data;
  1986. for (unsigned int i = 0; i < count; ++i)
  1987. if (types[i] != None)
  1988. srcMimeTypeAtomList.add (types[i]);
  1989. }
  1990. XFree (data);
  1991. }
  1992. }
  1993. if (srcMimeTypeAtomList.size() == 0)
  1994. {
  1995. for (int i = 2; i < 5; ++i)
  1996. if (clientMsg->data.l[i] != None)
  1997. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  1998. if (srcMimeTypeAtomList.size() == 0)
  1999. {
  2000. dragAndDropSourceWindow = 0;
  2001. return;
  2002. }
  2003. }
  2004. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  2005. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  2006. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  2007. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  2008. handleDragAndDropPosition (clientMsg);
  2009. }
  2010. void handleDragAndDropSelection (const XEvent* const evt)
  2011. {
  2012. dragAndDropFiles.clear();
  2013. if (evt->xselection.property != 0)
  2014. {
  2015. StringArray lines;
  2016. {
  2017. MemoryBlock dropData;
  2018. for (;;)
  2019. {
  2020. Atom actual;
  2021. uint8* data = 0;
  2022. unsigned long count = 0, remaining = 0;
  2023. int format = 0;
  2024. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  2025. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  2026. &format, &count, &remaining, &data) == Success)
  2027. {
  2028. dropData.append (data, count * format / 8);
  2029. XFree (data);
  2030. if (remaining == 0)
  2031. break;
  2032. }
  2033. else
  2034. {
  2035. XFree (data);
  2036. break;
  2037. }
  2038. }
  2039. lines.addLines (dropData.toString());
  2040. }
  2041. for (int i = 0; i < lines.size(); ++i)
  2042. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  2043. dragAndDropFiles.trim();
  2044. dragAndDropFiles.removeEmptyStrings();
  2045. }
  2046. }
  2047. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  2048. {
  2049. dragAndDropFiles.clear();
  2050. if (dragAndDropSourceWindow != None
  2051. && dragAndDropCurrentMimeType != 0)
  2052. {
  2053. dragAndDropTimestamp = clientMsg->data.l[2];
  2054. XConvertSelection (display,
  2055. XA_XdndSelection,
  2056. dragAndDropCurrentMimeType,
  2057. XA_JXSelectionWindowProperty,
  2058. windowH,
  2059. dragAndDropTimestamp);
  2060. }
  2061. }
  2062. StringArray dragAndDropFiles;
  2063. int dragAndDropTimestamp, lastDropX, lastDropY;
  2064. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  2065. Window dragAndDropSourceWindow;
  2066. unsigned long allowedActions [5];
  2067. unsigned long allowedMimeTypeAtoms [3];
  2068. Array <Atom> srcMimeTypeAtomList;
  2069. };
  2070. //==============================================================================
  2071. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  2072. {
  2073. if (enableOrDisable)
  2074. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  2075. }
  2076. //==============================================================================
  2077. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  2078. {
  2079. return new LinuxComponentPeer (this, styleFlags);
  2080. }
  2081. //==============================================================================
  2082. // (this callback is hooked up in the messaging code)
  2083. void juce_windowMessageReceive (XEvent* event)
  2084. {
  2085. if (event->xany.window != None)
  2086. {
  2087. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  2088. if (ComponentPeer::isValidPeer (peer))
  2089. peer->handleWindowMessage (event);
  2090. }
  2091. else
  2092. {
  2093. switch (event->xany.type)
  2094. {
  2095. case KeymapNotify:
  2096. {
  2097. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  2098. memcpy (keyStates, keymapEvent->key_vector, 32);
  2099. break;
  2100. }
  2101. default:
  2102. break;
  2103. }
  2104. }
  2105. }
  2106. //==============================================================================
  2107. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  2108. {
  2109. #if JUCE_USE_XINERAMA
  2110. int major_opcode, first_event, first_error;
  2111. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  2112. && XineramaIsActive (display))
  2113. {
  2114. int numMonitors = 0;
  2115. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  2116. if (screens != 0)
  2117. {
  2118. for (int i = numMonitors; --i >= 0;)
  2119. {
  2120. int index = screens[i].screen_number;
  2121. if (index >= 0)
  2122. {
  2123. while (monitorCoords.size() < index)
  2124. monitorCoords.add (Rectangle (0, 0, 0, 0));
  2125. monitorCoords.set (index, Rectangle (screens[i].x_org,
  2126. screens[i].y_org,
  2127. screens[i].width,
  2128. screens[i].height));
  2129. }
  2130. }
  2131. XFree (screens);
  2132. }
  2133. }
  2134. if (monitorCoords.size() == 0)
  2135. #endif
  2136. {
  2137. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  2138. if (hints != None)
  2139. {
  2140. const int numMonitors = ScreenCount (display);
  2141. for (int i = 0; i < numMonitors; ++i)
  2142. {
  2143. Window root = RootWindow (display, i);
  2144. unsigned long nitems, bytesLeft;
  2145. Atom actualType;
  2146. int actualFormat;
  2147. unsigned char* data = 0;
  2148. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  2149. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  2150. &data) == Success)
  2151. {
  2152. const long* const position = (const long*) data;
  2153. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  2154. monitorCoords.add (Rectangle (position[0], position[1],
  2155. position[2], position[3]));
  2156. XFree (data);
  2157. }
  2158. }
  2159. }
  2160. if (monitorCoords.size() == 0)
  2161. {
  2162. monitorCoords.add (Rectangle (0, 0,
  2163. DisplayWidth (display, DefaultScreen (display)),
  2164. DisplayHeight (display, DefaultScreen (display))));
  2165. }
  2166. }
  2167. }
  2168. //==============================================================================
  2169. bool Desktop::canUseSemiTransparentWindows() throw()
  2170. {
  2171. return false;
  2172. }
  2173. void Desktop::getMousePosition (int& x, int& y) throw()
  2174. {
  2175. int mouseMods;
  2176. getMousePos (x, y, mouseMods);
  2177. }
  2178. void Desktop::setMousePosition (int x, int y) throw()
  2179. {
  2180. Window root = RootWindow (display, DefaultScreen (display));
  2181. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  2182. }
  2183. //==============================================================================
  2184. static bool screenSaverAllowed = true;
  2185. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  2186. {
  2187. if (screenSaverAllowed != isEnabled)
  2188. {
  2189. screenSaverAllowed = isEnabled;
  2190. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  2191. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  2192. if (xScreenSaverSuspend == 0)
  2193. {
  2194. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  2195. if (h != 0)
  2196. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  2197. }
  2198. if (xScreenSaverSuspend != 0)
  2199. xScreenSaverSuspend (display, ! isEnabled);
  2200. }
  2201. }
  2202. bool Desktop::isScreenSaverEnabled() throw()
  2203. {
  2204. return screenSaverAllowed;
  2205. }
  2206. //==============================================================================
  2207. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  2208. {
  2209. Window root = RootWindow (display, DefaultScreen (display));
  2210. const unsigned int imageW = image.getWidth();
  2211. const unsigned int imageH = image.getHeight();
  2212. unsigned int cursorW, cursorH;
  2213. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  2214. return 0;
  2215. Image im (Image::ARGB, cursorW, cursorH, true);
  2216. Graphics g (im);
  2217. if (imageW > cursorW || imageH > cursorH)
  2218. {
  2219. hotspotX = (hotspotX * cursorW) / imageW;
  2220. hotspotY = (hotspotY * cursorH) / imageH;
  2221. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  2222. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  2223. false);
  2224. }
  2225. else
  2226. {
  2227. g.drawImageAt (&image, 0, 0);
  2228. }
  2229. const int stride = (cursorW + 7) >> 3;
  2230. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  2231. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  2232. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  2233. for (int y = cursorH; --y >= 0;)
  2234. {
  2235. for (int x = cursorW; --x >= 0;)
  2236. {
  2237. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  2238. const int offset = y * stride + (x >> 3);
  2239. const Colour c (im.getPixelAt (x, y));
  2240. if (c.getAlpha() >= 128)
  2241. maskPlane[offset] |= mask;
  2242. if (c.getBrightness() >= 0.5f)
  2243. sourcePlane[offset] |= mask;
  2244. }
  2245. }
  2246. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  2247. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  2248. juce_free (maskPlane);
  2249. juce_free (sourcePlane);
  2250. XColor white, black;
  2251. black.red = black.green = black.blue = 0;
  2252. white.red = white.green = white.blue = 0xffff;
  2253. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  2254. XFreePixmap (display, sourcePixmap);
  2255. XFreePixmap (display, maskPixmap);
  2256. return result;
  2257. }
  2258. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  2259. {
  2260. if (cursorHandle != None)
  2261. XFreeCursor (display, (Cursor) cursorHandle);
  2262. }
  2263. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  2264. {
  2265. unsigned int shape;
  2266. switch (type)
  2267. {
  2268. case MouseCursor::NoCursor:
  2269. {
  2270. const Image im (Image::ARGB, 16, 16, true);
  2271. return juce_createMouseCursorFromImage (im, 0, 0);
  2272. }
  2273. case MouseCursor::NormalCursor:
  2274. return (void*) None; // Use parent cursor
  2275. case MouseCursor::DraggingHandCursor:
  2276. {
  2277. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  2278. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  2279. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  2280. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  2281. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  2282. const int dragHandDataSize = 99;
  2283. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  2284. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  2285. delete im;
  2286. return dragHandCursor;
  2287. }
  2288. case MouseCursor::CopyingCursor:
  2289. {
  2290. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  2291. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  2292. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  2293. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  2294. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  2295. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  2296. const int copyCursorSize = 119;
  2297. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  2298. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  2299. delete im;
  2300. return copyCursor;
  2301. }
  2302. case MouseCursor::WaitCursor:
  2303. shape = XC_watch;
  2304. break;
  2305. case MouseCursor::IBeamCursor:
  2306. shape = XC_xterm;
  2307. break;
  2308. case MouseCursor::PointingHandCursor:
  2309. shape = XC_hand2;
  2310. break;
  2311. case MouseCursor::LeftRightResizeCursor:
  2312. shape = XC_sb_h_double_arrow;
  2313. break;
  2314. case MouseCursor::UpDownResizeCursor:
  2315. shape = XC_sb_v_double_arrow;
  2316. break;
  2317. case MouseCursor::UpDownLeftRightResizeCursor:
  2318. shape = XC_fleur;
  2319. break;
  2320. case MouseCursor::TopEdgeResizeCursor:
  2321. shape = XC_top_side;
  2322. break;
  2323. case MouseCursor::BottomEdgeResizeCursor:
  2324. shape = XC_bottom_side;
  2325. break;
  2326. case MouseCursor::LeftEdgeResizeCursor:
  2327. shape = XC_left_side;
  2328. break;
  2329. case MouseCursor::RightEdgeResizeCursor:
  2330. shape = XC_right_side;
  2331. break;
  2332. case MouseCursor::TopLeftCornerResizeCursor:
  2333. shape = XC_top_left_corner;
  2334. break;
  2335. case MouseCursor::TopRightCornerResizeCursor:
  2336. shape = XC_top_right_corner;
  2337. break;
  2338. case MouseCursor::BottomLeftCornerResizeCursor:
  2339. shape = XC_bottom_left_corner;
  2340. break;
  2341. case MouseCursor::BottomRightCornerResizeCursor:
  2342. shape = XC_bottom_right_corner;
  2343. break;
  2344. case MouseCursor::CrosshairCursor:
  2345. shape = XC_crosshair;
  2346. break;
  2347. default:
  2348. return (void*) None; // Use parent cursor
  2349. }
  2350. return (void*) XCreateFontCursor (display, shape);
  2351. }
  2352. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  2353. {
  2354. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  2355. if (lp != 0)
  2356. lp->showMouseCursor ((Cursor) getHandle());
  2357. }
  2358. void MouseCursor::showInAllWindows() const throw()
  2359. {
  2360. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  2361. showInWindow (ComponentPeer::getPeer (i));
  2362. }
  2363. //==============================================================================
  2364. Image* juce_createIconForFile (const File& file)
  2365. {
  2366. return 0;
  2367. }
  2368. //==============================================================================
  2369. #if JUCE_OPENGL
  2370. //==============================================================================
  2371. class WindowedGLContext : public OpenGLContext
  2372. {
  2373. public:
  2374. WindowedGLContext (Component* const component,
  2375. const OpenGLPixelFormat& pixelFormat_,
  2376. GLXContext sharedContext)
  2377. : renderContext (0),
  2378. embeddedWindow (0),
  2379. pixelFormat (pixelFormat_)
  2380. {
  2381. jassert (component != 0);
  2382. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  2383. if (peer == 0)
  2384. return;
  2385. XSync (display, False);
  2386. GLint attribs [64];
  2387. int n = 0;
  2388. attribs[n++] = GLX_RGBA;
  2389. attribs[n++] = GLX_DOUBLEBUFFER;
  2390. attribs[n++] = GLX_RED_SIZE;
  2391. attribs[n++] = pixelFormat.redBits;
  2392. attribs[n++] = GLX_GREEN_SIZE;
  2393. attribs[n++] = pixelFormat.greenBits;
  2394. attribs[n++] = GLX_BLUE_SIZE;
  2395. attribs[n++] = pixelFormat.blueBits;
  2396. attribs[n++] = GLX_ALPHA_SIZE;
  2397. attribs[n++] = pixelFormat.alphaBits;
  2398. attribs[n++] = GLX_DEPTH_SIZE;
  2399. attribs[n++] = pixelFormat.depthBufferBits;
  2400. attribs[n++] = GLX_STENCIL_SIZE;
  2401. attribs[n++] = pixelFormat.stencilBufferBits;
  2402. attribs[n++] = GLX_ACCUM_RED_SIZE;
  2403. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  2404. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  2405. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  2406. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  2407. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  2408. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  2409. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  2410. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  2411. attribs[n++] = None;
  2412. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  2413. if (bestVisual == 0)
  2414. return;
  2415. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  2416. Window windowH = (Window) peer->getNativeHandle();
  2417. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  2418. XSetWindowAttributes swa;
  2419. swa.colormap = colourMap;
  2420. swa.border_pixel = 0;
  2421. swa.event_mask = ExposureMask | StructureNotifyMask;
  2422. embeddedWindow = XCreateWindow (display, windowH,
  2423. 0, 0, 1, 1, 0,
  2424. bestVisual->depth,
  2425. InputOutput,
  2426. bestVisual->visual,
  2427. CWBorderPixel | CWColormap | CWEventMask,
  2428. &swa);
  2429. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  2430. XMapWindow (display, embeddedWindow);
  2431. XFreeColormap (display, colourMap);
  2432. XFree (bestVisual);
  2433. XSync (display, False);
  2434. }
  2435. ~WindowedGLContext()
  2436. {
  2437. makeInactive();
  2438. glXDestroyContext (display, renderContext);
  2439. XUnmapWindow (display, embeddedWindow);
  2440. XDestroyWindow (display, embeddedWindow);
  2441. }
  2442. bool makeActive() const throw()
  2443. {
  2444. jassert (renderContext != 0);
  2445. return glXMakeCurrent (display, embeddedWindow, renderContext)
  2446. && XSync (display, False);
  2447. }
  2448. bool makeInactive() const throw()
  2449. {
  2450. return (! isActive()) || glXMakeCurrent (display, None, 0);
  2451. }
  2452. bool isActive() const throw()
  2453. {
  2454. return glXGetCurrentContext() == renderContext;
  2455. }
  2456. const OpenGLPixelFormat getPixelFormat() const
  2457. {
  2458. return pixelFormat;
  2459. }
  2460. void* getRawContext() const throw()
  2461. {
  2462. return renderContext;
  2463. }
  2464. void updateWindowPosition (int x, int y, int w, int h, int)
  2465. {
  2466. XMoveResizeWindow (display, embeddedWindow,
  2467. x, y, jmax (1, w), jmax (1, h));
  2468. }
  2469. void swapBuffers()
  2470. {
  2471. glXSwapBuffers (display, embeddedWindow);
  2472. }
  2473. bool setSwapInterval (const int numFramesPerSwap)
  2474. {
  2475. // xxx needs doing..
  2476. return false;
  2477. }
  2478. int getSwapInterval() const
  2479. {
  2480. // xxx needs doing..
  2481. return 0;
  2482. }
  2483. void repaint()
  2484. {
  2485. }
  2486. //==============================================================================
  2487. juce_UseDebuggingNewOperator
  2488. GLXContext renderContext;
  2489. private:
  2490. Window embeddedWindow;
  2491. OpenGLPixelFormat pixelFormat;
  2492. //==============================================================================
  2493. WindowedGLContext (const WindowedGLContext&);
  2494. const WindowedGLContext& operator= (const WindowedGLContext&);
  2495. };
  2496. //==============================================================================
  2497. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  2498. const OpenGLPixelFormat& pixelFormat,
  2499. const OpenGLContext* const contextToShareWith)
  2500. {
  2501. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  2502. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  2503. if (c->renderContext == 0)
  2504. deleteAndZero (c);
  2505. return c;
  2506. }
  2507. void juce_glViewport (const int w, const int h)
  2508. {
  2509. glViewport (0, 0, w, h);
  2510. }
  2511. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  2512. OwnedArray <OpenGLPixelFormat>& results)
  2513. {
  2514. results.add (new OpenGLPixelFormat()); // xxx
  2515. }
  2516. #endif
  2517. //==============================================================================
  2518. static void initClipboard (Window root, Atom* cutBuffers) throw()
  2519. {
  2520. static bool init = false;
  2521. if (! init)
  2522. {
  2523. init = true;
  2524. // Make sure all cut buffers exist before use
  2525. for (int i = 0; i < 8; i++)
  2526. {
  2527. XChangeProperty (display, root, cutBuffers[i],
  2528. XA_STRING, 8, PropModeAppend, NULL, 0);
  2529. }
  2530. }
  2531. }
  2532. // Clipboard implemented currently using cut buffers
  2533. // rather than the more powerful selection method
  2534. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  2535. {
  2536. Window root = RootWindow (display, DefaultScreen (display));
  2537. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  2538. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  2539. initClipboard (root, cutBuffers);
  2540. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  2541. XChangeProperty (display, root, cutBuffers[0],
  2542. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  2543. clipText.length());
  2544. }
  2545. const String SystemClipboard::getTextFromClipboard() throw()
  2546. {
  2547. const int bufSize = 64; // in words
  2548. String returnData;
  2549. int byteOffset = 0;
  2550. Window root = RootWindow (display, DefaultScreen (display));
  2551. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  2552. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  2553. initClipboard (root, cutBuffers);
  2554. for (;;)
  2555. {
  2556. unsigned long bytesLeft = 0, nitems = 0;
  2557. unsigned char* clipData = 0;
  2558. int actualFormat = 0;
  2559. Atom actualType;
  2560. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  2561. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  2562. &clipData) == Success)
  2563. {
  2564. if (actualType == XA_STRING && actualFormat == 8)
  2565. {
  2566. byteOffset += nitems;
  2567. returnData += String ((const char*) clipData, nitems);
  2568. }
  2569. else
  2570. {
  2571. bytesLeft = 0;
  2572. }
  2573. if (clipData != 0)
  2574. XFree (clipData);
  2575. }
  2576. if (bytesLeft == 0)
  2577. break;
  2578. }
  2579. return returnData;
  2580. }
  2581. //==============================================================================
  2582. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  2583. {
  2584. jassertfalse // not implemented!
  2585. return false;
  2586. }
  2587. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2588. {
  2589. jassertfalse // not implemented!
  2590. return false;
  2591. }
  2592. //==============================================================================
  2593. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  2594. {
  2595. if (! isOnDesktop ())
  2596. addToDesktop (0);
  2597. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  2598. if (wp != 0)
  2599. {
  2600. wp->setTaskBarIcon (newImage);
  2601. setVisible (true);
  2602. toFront (false);
  2603. repaint();
  2604. }
  2605. }
  2606. void SystemTrayIconComponent::paint (Graphics& g)
  2607. {
  2608. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  2609. if (wp != 0)
  2610. {
  2611. const Image* const image = wp->getTaskbarIcon();
  2612. if (image != 0)
  2613. {
  2614. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  2615. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  2616. false);
  2617. }
  2618. }
  2619. }
  2620. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  2621. {
  2622. // xxx not yet implemented!
  2623. }
  2624. //==============================================================================
  2625. void PlatformUtilities::beep()
  2626. {
  2627. fprintf (stdout, "\a");
  2628. fflush (stdout);
  2629. }
  2630. //==============================================================================
  2631. bool AlertWindow::showNativeDialogBox (const String& title,
  2632. const String& bodyText,
  2633. bool isOkCancel)
  2634. {
  2635. // xxx this is supposed to pop up an alert!
  2636. Logger::outputDebugString (title + ": " + bodyText);
  2637. // use a non-native one for the time being..
  2638. if (isOkCancel)
  2639. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  2640. else
  2641. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  2642. return true;
  2643. }
  2644. //==============================================================================
  2645. const int KeyPress::spaceKey = XK_space & 0xff;
  2646. const int KeyPress::returnKey = XK_Return & 0xff;
  2647. const int KeyPress::escapeKey = XK_Escape & 0xff;
  2648. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  2649. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  2650. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  2651. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  2652. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  2653. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  2654. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  2655. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  2656. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  2657. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  2658. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  2659. const int KeyPress::tabKey = XK_Tab & 0xff;
  2660. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  2661. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  2662. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  2663. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  2664. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  2665. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  2666. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  2667. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  2668. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  2669. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  2670. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  2671. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  2672. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  2673. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  2674. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  2675. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  2676. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  2677. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  2678. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  2679. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  2680. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  2681. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  2682. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  2683. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  2684. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  2685. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  2686. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  2687. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  2688. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  2689. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  2690. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  2691. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  2692. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  2693. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  2694. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  2695. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  2696. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  2697. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  2698. END_JUCE_NAMESPACE