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.

667 lines
22KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. bool juce_handleXEmbedEvent (ComponentPeer*, void*);
  22. Window juce_getCurrentFocusWindow (ComponentPeer*);
  23. //==============================================================================
  24. unsigned long juce_createKeyProxyWindow (ComponentPeer*);
  25. void juce_deleteKeyProxyWindow (ComponentPeer*);
  26. //==============================================================================
  27. class XEmbedComponent::Pimpl : private ComponentListener
  28. {
  29. public:
  30. //==============================================================================
  31. struct SharedKeyWindow : public ReferenceCountedObject
  32. {
  33. SharedKeyWindow (ComponentPeer* peerToUse)
  34. : keyPeer (peerToUse),
  35. keyProxy (juce_createKeyProxyWindow (keyPeer))
  36. {}
  37. ~SharedKeyWindow()
  38. {
  39. juce_deleteKeyProxyWindow (keyPeer);
  40. auto& keyWindows = getKeyWindows();
  41. keyWindows.remove (keyPeer);
  42. }
  43. using Ptr = ReferenceCountedObjectPtr<SharedKeyWindow>;
  44. //==============================================================================
  45. Window getHandle() { return keyProxy; }
  46. static Window getCurrentFocusWindow (ComponentPeer* peerToLookFor)
  47. {
  48. auto& keyWindows = getKeyWindows();
  49. if (peerToLookFor != nullptr)
  50. if (auto* foundKeyWindow = keyWindows[peerToLookFor])
  51. return foundKeyWindow->keyProxy;
  52. return {};
  53. }
  54. static SharedKeyWindow::Ptr getKeyWindowForPeer (ComponentPeer* peerToLookFor)
  55. {
  56. jassert (peerToLookFor != nullptr);
  57. auto& keyWindows = getKeyWindows();
  58. auto foundKeyWindow = keyWindows[peerToLookFor];
  59. if (foundKeyWindow == nullptr)
  60. {
  61. foundKeyWindow = new SharedKeyWindow (peerToLookFor);
  62. keyWindows.set (peerToLookFor, foundKeyWindow);
  63. }
  64. return foundKeyWindow;
  65. }
  66. private:
  67. //==============================================================================
  68. ComponentPeer* keyPeer;
  69. Window keyProxy;
  70. static HashMap<ComponentPeer*, SharedKeyWindow*>& getKeyWindows()
  71. {
  72. // store a weak reference to the shared key windows
  73. static HashMap<ComponentPeer*, SharedKeyWindow*> keyWindows;
  74. return keyWindows;
  75. }
  76. };
  77. public:
  78. //==============================================================================
  79. Pimpl (XEmbedComponent& parent, Window x11Window,
  80. bool wantsKeyboardFocus, bool isClientInitiated, bool shouldAllowResize)
  81. : owner (parent), atoms (x11display.display), clientInitiated (isClientInitiated),
  82. wantsFocus (wantsKeyboardFocus), allowResize (shouldAllowResize)
  83. {
  84. getWidgets().add (this);
  85. createHostWindow();
  86. if (clientInitiated)
  87. setClient (x11Window, true);
  88. owner.setWantsKeyboardFocus (wantsFocus);
  89. owner.addComponentListener (this);
  90. }
  91. ~Pimpl() override
  92. {
  93. owner.removeComponentListener (this);
  94. setClient (0, true);
  95. if (host != 0)
  96. {
  97. auto dpy = getDisplay();
  98. XDestroyWindow (dpy, host);
  99. XSync (dpy, false);
  100. const long mask = NoEventMask | KeyPressMask | KeyReleaseMask
  101. | EnterWindowMask | LeaveWindowMask | PointerMotionMask
  102. | KeymapStateMask | ExposureMask | StructureNotifyMask
  103. | FocusChangeMask;
  104. XEvent event;
  105. while (XCheckWindowEvent (dpy, host, mask, &event) == True)
  106. {}
  107. host = 0;
  108. }
  109. getWidgets().removeAllInstancesOf (this);
  110. }
  111. //==============================================================================
  112. void setClient (Window xembedClient, bool shouldReparent)
  113. {
  114. removeClient();
  115. if (xembedClient != 0)
  116. {
  117. auto dpy = getDisplay();
  118. client = xembedClient;
  119. // if the client has initiated the component then keep the clients size
  120. // otherwise the client should use the host's window' size
  121. if (clientInitiated)
  122. {
  123. configureNotify();
  124. }
  125. else
  126. {
  127. auto newBounds = getX11BoundsFromJuce();
  128. XResizeWindow (dpy, client, static_cast<unsigned int> (newBounds.getWidth()),
  129. static_cast<unsigned int> (newBounds.getHeight()));
  130. }
  131. auto eventMask = StructureNotifyMask | PropertyChangeMask | FocusChangeMask;
  132. XWindowAttributes clientAttr;
  133. XGetWindowAttributes (dpy, client, &clientAttr);
  134. if ((eventMask & clientAttr.your_event_mask) != eventMask)
  135. XSelectInput (dpy, client, clientAttr.your_event_mask | eventMask);
  136. getXEmbedMappedFlag();
  137. if (shouldReparent)
  138. XReparentWindow (dpy, client, host, 0, 0);
  139. if (supportsXembed)
  140. sendXEmbedEvent (CurrentTime, XEMBED_EMBEDDED_NOTIFY, 0, (long) host, xembedVersion);
  141. updateMapping();
  142. }
  143. }
  144. void focusGained (FocusChangeType changeType)
  145. {
  146. if (client != 0 && supportsXembed && wantsFocus)
  147. {
  148. updateKeyFocus();
  149. sendXEmbedEvent (CurrentTime, XEMBED_FOCUS_IN,
  150. (changeType == focusChangedByTabKey ? XEMBED_FOCUS_FIRST : XEMBED_FOCUS_CURRENT));
  151. }
  152. }
  153. void focusLost (FocusChangeType)
  154. {
  155. if (client != 0 && supportsXembed && wantsFocus)
  156. {
  157. sendXEmbedEvent (CurrentTime, XEMBED_FOCUS_OUT);
  158. updateKeyFocus();
  159. }
  160. }
  161. void broughtToFront()
  162. {
  163. if (client != 0 && supportsXembed)
  164. sendXEmbedEvent (CurrentTime, XEMBED_WINDOW_ACTIVATE);
  165. }
  166. unsigned long getHostWindowID()
  167. {
  168. // You are using the client initiated version of the protocol. You cannot
  169. // retrieve the window id of the host. Please read the documentation for
  170. // the XEmebedComponent class.
  171. jassert (! clientInitiated);
  172. return host;
  173. }
  174. private:
  175. //==============================================================================
  176. XEmbedComponent& owner;
  177. Window client = 0, host = 0;
  178. ScopedXDisplay x11display;
  179. Atoms atoms;
  180. bool clientInitiated;
  181. bool wantsFocus = false;
  182. bool allowResize = false;
  183. bool supportsXembed = false;
  184. bool hasBeenMapped = false;
  185. int xembedVersion = maxXEmbedVersionToSupport;
  186. ComponentPeer* lastPeer = nullptr;
  187. SharedKeyWindow::Ptr keyWindow;
  188. //==============================================================================
  189. void componentParentHierarchyChanged (Component&) override { peerChanged (owner.getPeer()); }
  190. void componentMovedOrResized (Component&, bool, bool) override
  191. {
  192. if (host != 0 && lastPeer != nullptr)
  193. {
  194. auto dpy = getDisplay();
  195. auto newBounds = getX11BoundsFromJuce();
  196. XWindowAttributes attr;
  197. if (XGetWindowAttributes (dpy, host, &attr))
  198. {
  199. Rectangle<int> currentBounds (attr.x, attr.y, attr.width, attr.height);
  200. if (currentBounds != newBounds)
  201. {
  202. XMoveResizeWindow (dpy, host, newBounds.getX(), newBounds.getY(),
  203. static_cast<unsigned int> (newBounds.getWidth()),
  204. static_cast<unsigned int> (newBounds.getHeight()));
  205. }
  206. }
  207. if (client != 0 && XGetWindowAttributes (dpy, client, &attr))
  208. {
  209. Rectangle<int> currentBounds (attr.x, attr.y, attr.width, attr.height);
  210. if ((currentBounds.getWidth() != newBounds.getWidth()
  211. || currentBounds.getHeight() != newBounds.getHeight()))
  212. {
  213. XMoveResizeWindow (dpy, client, 0, 0,
  214. static_cast<unsigned int> (newBounds.getWidth()),
  215. static_cast<unsigned int> (newBounds.getHeight()));
  216. }
  217. }
  218. }
  219. }
  220. //==============================================================================
  221. void createHostWindow()
  222. {
  223. auto dpy = getDisplay();
  224. int defaultScreen = XDefaultScreen (dpy);
  225. Window root = RootWindow (dpy, defaultScreen);
  226. XSetWindowAttributes swa;
  227. swa.border_pixel = 0;
  228. swa.background_pixmap = None;
  229. swa.override_redirect = True;
  230. swa.event_mask = SubstructureNotifyMask | StructureNotifyMask | FocusChangeMask;
  231. host = XCreateWindow (dpy, root, 0, 0, 1, 1, 0, CopyFromParent,
  232. InputOutput, CopyFromParent,
  233. CWEventMask | CWBorderPixel | CWBackPixmap | CWOverrideRedirect,
  234. &swa);
  235. }
  236. void removeClient()
  237. {
  238. if (client != 0)
  239. {
  240. auto dpy = getDisplay();
  241. XSelectInput (dpy, client, 0);
  242. keyWindow = nullptr;
  243. int defaultScreen = XDefaultScreen (dpy);
  244. Window root = RootWindow (dpy, defaultScreen);
  245. if (hasBeenMapped)
  246. {
  247. XUnmapWindow (dpy, client);
  248. hasBeenMapped = false;
  249. }
  250. XReparentWindow (dpy, client, root, 0, 0);
  251. client = 0;
  252. }
  253. }
  254. void updateMapping()
  255. {
  256. if (client != 0)
  257. {
  258. const bool shouldBeMapped = getXEmbedMappedFlag();
  259. if (shouldBeMapped != hasBeenMapped)
  260. {
  261. hasBeenMapped = shouldBeMapped;
  262. if (shouldBeMapped)
  263. XMapWindow (getDisplay(), client);
  264. else
  265. XUnmapWindow (getDisplay(), client);
  266. }
  267. }
  268. }
  269. Window getParentX11Window()
  270. {
  271. if (auto* peer = owner.getPeer())
  272. return reinterpret_cast<Window> (peer->getNativeHandle());
  273. return {};
  274. }
  275. Display* getDisplay() { return reinterpret_cast<Display*> (x11display.display); }
  276. //==============================================================================
  277. bool getXEmbedMappedFlag()
  278. {
  279. GetXProperty embedInfo (x11display.display, client, atoms.XembedInfo, 0, 2, false, atoms.XembedInfo);
  280. if (embedInfo.success && embedInfo.actualFormat == 32
  281. && embedInfo.numItems >= 2 && embedInfo.data != nullptr)
  282. {
  283. long version;
  284. memcpy (&version, embedInfo.data, sizeof (long));
  285. supportsXembed = true;
  286. xembedVersion = jmin ((int) maxXEmbedVersionToSupport, (int) version);
  287. long flags;
  288. memcpy (&flags, embedInfo.data + sizeof (long), sizeof (long));
  289. return ((flags & XEMBED_MAPPED) != 0);
  290. }
  291. else
  292. {
  293. supportsXembed = false;
  294. xembedVersion = maxXEmbedVersionToSupport;
  295. }
  296. return true;
  297. }
  298. //==============================================================================
  299. void propertyChanged (const Atom& a)
  300. {
  301. if (a == atoms.XembedInfo)
  302. updateMapping();
  303. }
  304. void configureNotify()
  305. {
  306. XWindowAttributes attr;
  307. auto dpy = getDisplay();
  308. if (XGetWindowAttributes (dpy, client, &attr))
  309. {
  310. XWindowAttributes hostAttr;
  311. if (XGetWindowAttributes (dpy, host, &hostAttr))
  312. if (attr.width != hostAttr.width || attr.height != hostAttr.height)
  313. XResizeWindow (dpy, host, (unsigned int) attr.width, (unsigned int) attr.height);
  314. // as the client window is not on any screen yet, we need to guess
  315. // on which screen it might appear to get a scaling factor :-(
  316. auto& displays = Desktop::getInstance().getDisplays();
  317. auto* peer = owner.getPeer();
  318. const double scale = (peer != nullptr ? peer->getPlatformScaleFactor()
  319. : displays.getMainDisplay().scale);
  320. Point<int> topLeftInPeer
  321. = (peer != nullptr ? peer->getComponent().getLocalPoint (&owner, Point<int> (0, 0))
  322. : owner.getBounds().getTopLeft());
  323. Rectangle<int> newBounds (topLeftInPeer.getX(), topLeftInPeer.getY(),
  324. static_cast<int> (static_cast<double> (attr.width) / scale),
  325. static_cast<int> (static_cast<double> (attr.height) / scale));
  326. if (peer != nullptr)
  327. newBounds = owner.getLocalArea (&peer->getComponent(), newBounds);
  328. jassert (newBounds.getX() == 0 && newBounds.getY() == 0);
  329. if (newBounds != owner.getLocalBounds())
  330. owner.setSize (newBounds.getWidth(), newBounds.getHeight());
  331. }
  332. }
  333. void peerChanged (ComponentPeer* newPeer)
  334. {
  335. if (newPeer != lastPeer)
  336. {
  337. if (lastPeer != nullptr)
  338. keyWindow = nullptr;
  339. auto dpy = getDisplay();
  340. Window rootWindow = RootWindow (dpy, DefaultScreen (dpy));
  341. Rectangle<int> newBounds = getX11BoundsFromJuce();
  342. if (newPeer == nullptr)
  343. XUnmapWindow (dpy, host);
  344. Window newParent = (newPeer != nullptr ? getParentX11Window() : rootWindow);
  345. XReparentWindow (dpy, host, newParent, newBounds.getX(), newBounds.getY());
  346. lastPeer = newPeer;
  347. if (newPeer != nullptr)
  348. {
  349. if (wantsFocus)
  350. {
  351. keyWindow = SharedKeyWindow::getKeyWindowForPeer (newPeer);
  352. updateKeyFocus();
  353. }
  354. componentMovedOrResized (owner, true, true);
  355. XMapWindow (dpy, host);
  356. broughtToFront();
  357. }
  358. }
  359. }
  360. void updateKeyFocus()
  361. {
  362. if (lastPeer != nullptr && lastPeer->isFocused())
  363. XSetInputFocus (getDisplay(), getCurrentFocusWindow (lastPeer), RevertToParent, CurrentTime);
  364. }
  365. //==============================================================================
  366. void handleXembedCmd (const ::Time& /*xTime*/, long opcode, long /*detail*/, long /*data1*/, long /*data2*/)
  367. {
  368. switch (opcode)
  369. {
  370. case XEMBED_REQUEST_FOCUS:
  371. if (wantsFocus)
  372. owner.grabKeyboardFocus();
  373. break;
  374. case XEMBED_FOCUS_NEXT:
  375. if (wantsFocus)
  376. owner.moveKeyboardFocusToSibling (true);
  377. break;
  378. case XEMBED_FOCUS_PREV:
  379. if (wantsFocus)
  380. owner.moveKeyboardFocusToSibling (false);
  381. break;
  382. default:
  383. break;
  384. }
  385. }
  386. bool handleX11Event (const XEvent& e)
  387. {
  388. if (e.xany.window == client && client != 0)
  389. {
  390. switch (e.type)
  391. {
  392. case PropertyNotify:
  393. propertyChanged (e.xproperty.atom);
  394. return true;
  395. case ConfigureNotify:
  396. if (allowResize)
  397. configureNotify();
  398. else
  399. MessageManager::callAsync ([this] {componentMovedOrResized (owner, true, true);});
  400. return true;
  401. default:
  402. break;
  403. }
  404. }
  405. else if (e.xany.window == host && host != 0)
  406. {
  407. switch (e.type)
  408. {
  409. case ReparentNotify:
  410. if (e.xreparent.parent == host && e.xreparent.window != client)
  411. {
  412. setClient (e.xreparent.window, false);
  413. return true;
  414. }
  415. break;
  416. case CreateNotify:
  417. if (e.xcreatewindow.parent != e.xcreatewindow.window && e.xcreatewindow.parent == host && e.xcreatewindow.window != client)
  418. {
  419. setClient (e.xcreatewindow.window, false);
  420. return true;
  421. }
  422. break;
  423. case GravityNotify:
  424. componentMovedOrResized (owner, true, true);
  425. return true;
  426. case ClientMessage:
  427. if (e.xclient.message_type == atoms.XembedMsgType && e.xclient.format == 32)
  428. {
  429. handleXembedCmd ((::Time) e.xclient.data.l[0], e.xclient.data.l[1],
  430. e.xclient.data.l[2], e.xclient.data.l[3],
  431. e.xclient.data.l[4]);
  432. return true;
  433. }
  434. break;
  435. default:
  436. break;
  437. }
  438. }
  439. return false;
  440. }
  441. void sendXEmbedEvent (const ::Time& xTime, long opcode,
  442. long opcodeMinor = 0, long data1 = 0, long data2 = 0)
  443. {
  444. XClientMessageEvent msg;
  445. auto dpy = getDisplay();
  446. ::memset (&msg, 0, sizeof (XClientMessageEvent));
  447. msg.window = client;
  448. msg.type = ClientMessage;
  449. msg.message_type = atoms.XembedMsgType;
  450. msg.format = 32;
  451. msg.data.l[0] = (long) xTime;
  452. msg.data.l[1] = opcode;
  453. msg.data.l[2] = opcodeMinor;
  454. msg.data.l[3] = data1;
  455. msg.data.l[4] = data2;
  456. XSendEvent (dpy, client, False, NoEventMask, (XEvent*) &msg);
  457. XSync (dpy, False);
  458. }
  459. Rectangle<int> getX11BoundsFromJuce()
  460. {
  461. if (auto* peer = owner.getPeer())
  462. {
  463. auto r = peer->getComponent().getLocalArea (&owner, owner.getLocalBounds());
  464. return r * peer->getPlatformScaleFactor();
  465. }
  466. return owner.getLocalBounds();
  467. }
  468. //==============================================================================
  469. friend bool juce::juce_handleXEmbedEvent (ComponentPeer*, void*);
  470. friend unsigned long juce::juce_getCurrentFocusWindow (ComponentPeer*);
  471. static Array<Pimpl*>& getWidgets()
  472. {
  473. static Array<Pimpl*> i;
  474. return i;
  475. }
  476. static bool dispatchX11Event (ComponentPeer* p, const XEvent* eventArg)
  477. {
  478. if (eventArg != nullptr)
  479. {
  480. auto& e = *eventArg;
  481. if (auto w = e.xany.window)
  482. for (auto* widget : getWidgets())
  483. if (w == widget->host || w == widget->client)
  484. return widget->handleX11Event (e);
  485. }
  486. else
  487. {
  488. for (auto* widget : getWidgets())
  489. if (widget->owner.getPeer() == p)
  490. widget->peerChanged (nullptr);
  491. }
  492. return false;
  493. }
  494. static Window getCurrentFocusWindow (ComponentPeer* p)
  495. {
  496. if (p != nullptr)
  497. {
  498. for (auto* widget : getWidgets())
  499. if (widget->owner.getPeer() == p && widget->owner.hasKeyboardFocus (false))
  500. return widget->client;
  501. }
  502. return SharedKeyWindow::getCurrentFocusWindow (p);
  503. }
  504. };
  505. //==============================================================================
  506. XEmbedComponent::XEmbedComponent (bool wantsKeyboardFocus, bool allowForeignWidgetToResizeComponent)
  507. : pimpl (new Pimpl (*this, 0, wantsKeyboardFocus, false, allowForeignWidgetToResizeComponent))
  508. {
  509. setOpaque (true);
  510. }
  511. XEmbedComponent::XEmbedComponent (unsigned long wID, bool wantsKeyboardFocus, bool allowForeignWidgetToResizeComponent)
  512. : pimpl (new Pimpl (*this, wID, wantsKeyboardFocus, true, allowForeignWidgetToResizeComponent))
  513. {
  514. setOpaque (true);
  515. }
  516. XEmbedComponent::~XEmbedComponent() {}
  517. void XEmbedComponent::paint (Graphics& g)
  518. {
  519. g.fillAll (Colours::lightgrey);
  520. }
  521. void XEmbedComponent::focusGained (FocusChangeType changeType) { pimpl->focusGained (changeType); }
  522. void XEmbedComponent::focusLost (FocusChangeType changeType) { pimpl->focusLost (changeType); }
  523. void XEmbedComponent::broughtToFront() { pimpl->broughtToFront(); }
  524. unsigned long XEmbedComponent::getHostWindowID() { return pimpl->getHostWindowID(); }
  525. //==============================================================================
  526. bool juce_handleXEmbedEvent (ComponentPeer* p, void* e)
  527. {
  528. return XEmbedComponent::Pimpl::dispatchX11Event (p, reinterpret_cast<const XEvent*> (e));
  529. }
  530. unsigned long juce_getCurrentFocusWindow (ComponentPeer* peer)
  531. {
  532. return (unsigned long) XEmbedComponent::Pimpl::getCurrentFocusWindow (peer);
  533. }
  534. } // namespace juce