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.

658 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. }
  383. }
  384. bool handleX11Event (const XEvent& e)
  385. {
  386. if (e.xany.window == client && client != 0)
  387. {
  388. switch (e.type)
  389. {
  390. case PropertyNotify:
  391. propertyChanged (e.xproperty.atom);
  392. return true;
  393. case ConfigureNotify:
  394. if (allowResize)
  395. configureNotify();
  396. else
  397. MessageManager::callAsync ([this] {componentMovedOrResized (owner, true, true);});
  398. return true;
  399. }
  400. }
  401. else if (e.xany.window == host && host != 0)
  402. {
  403. switch (e.type)
  404. {
  405. case ReparentNotify:
  406. if (e.xreparent.parent == host && e.xreparent.window != client)
  407. {
  408. setClient (e.xreparent.window, false);
  409. return true;
  410. }
  411. break;
  412. case CreateNotify:
  413. if (e.xcreatewindow.parent != e.xcreatewindow.window && e.xcreatewindow.parent == host && e.xcreatewindow.window != client)
  414. {
  415. setClient (e.xcreatewindow.window, false);
  416. return true;
  417. }
  418. break;
  419. case GravityNotify:
  420. componentMovedOrResized (owner, true, true);
  421. return true;
  422. case ClientMessage:
  423. if (e.xclient.message_type == atoms.XembedMsgType && e.xclient.format == 32)
  424. {
  425. handleXembedCmd ((::Time) e.xclient.data.l[0], e.xclient.data.l[1],
  426. e.xclient.data.l[2], e.xclient.data.l[3],
  427. e.xclient.data.l[4]);
  428. return true;
  429. }
  430. break;
  431. }
  432. }
  433. return false;
  434. }
  435. void sendXEmbedEvent (const ::Time& xTime, long opcode,
  436. long opcodeMinor = 0, long data1 = 0, long data2 = 0)
  437. {
  438. XClientMessageEvent msg;
  439. auto dpy = getDisplay();
  440. ::memset (&msg, 0, sizeof (XClientMessageEvent));
  441. msg.window = client;
  442. msg.type = ClientMessage;
  443. msg.message_type = atoms.XembedMsgType;
  444. msg.format = 32;
  445. msg.data.l[0] = (long) xTime;
  446. msg.data.l[1] = opcode;
  447. msg.data.l[2] = opcodeMinor;
  448. msg.data.l[3] = data1;
  449. msg.data.l[4] = data2;
  450. XSendEvent (dpy, client, False, NoEventMask, (XEvent*) &msg);
  451. XSync (dpy, False);
  452. }
  453. Rectangle<int> getX11BoundsFromJuce()
  454. {
  455. if (auto* peer = owner.getPeer())
  456. {
  457. auto r = peer->getComponent().getLocalArea (&owner, owner.getLocalBounds());
  458. return r * peer->getPlatformScaleFactor();
  459. }
  460. return owner.getLocalBounds();
  461. }
  462. //==============================================================================
  463. friend bool juce::juce_handleXEmbedEvent (ComponentPeer*, void*);
  464. friend unsigned long juce::juce_getCurrentFocusWindow (ComponentPeer*);
  465. static Array<Pimpl*>& getWidgets()
  466. {
  467. static Array<Pimpl*> i;
  468. return i;
  469. }
  470. static bool dispatchX11Event (ComponentPeer* p, const XEvent* eventArg)
  471. {
  472. if (eventArg != nullptr)
  473. {
  474. auto& e = *eventArg;
  475. if (auto w = e.xany.window)
  476. for (auto* widget : getWidgets())
  477. if (w == widget->host || w == widget->client)
  478. return widget->handleX11Event (e);
  479. }
  480. else
  481. {
  482. for (auto* widget : getWidgets())
  483. if (widget->owner.getPeer() == p)
  484. widget->peerChanged (nullptr);
  485. }
  486. return false;
  487. }
  488. static Window getCurrentFocusWindow (ComponentPeer* p)
  489. {
  490. if (p != nullptr)
  491. {
  492. for (auto* widget : getWidgets())
  493. if (widget->owner.getPeer() == p && widget->owner.hasKeyboardFocus (false))
  494. return widget->client;
  495. }
  496. return SharedKeyWindow::getCurrentFocusWindow (p);
  497. }
  498. };
  499. //==============================================================================
  500. XEmbedComponent::XEmbedComponent (bool wantsKeyboardFocus, bool allowForeignWidgetToResizeComponent)
  501. : pimpl (new Pimpl (*this, 0, wantsKeyboardFocus, false, allowForeignWidgetToResizeComponent))
  502. {
  503. setOpaque (true);
  504. }
  505. XEmbedComponent::XEmbedComponent (unsigned long wID, bool wantsKeyboardFocus, bool allowForeignWidgetToResizeComponent)
  506. : pimpl (new Pimpl (*this, wID, wantsKeyboardFocus, true, allowForeignWidgetToResizeComponent))
  507. {
  508. setOpaque (true);
  509. }
  510. XEmbedComponent::~XEmbedComponent() {}
  511. void XEmbedComponent::paint (Graphics& g)
  512. {
  513. g.fillAll (Colours::lightgrey);
  514. }
  515. void XEmbedComponent::focusGained (FocusChangeType changeType) { pimpl->focusGained (changeType); }
  516. void XEmbedComponent::focusLost (FocusChangeType changeType) { pimpl->focusLost (changeType); }
  517. void XEmbedComponent::broughtToFront() { pimpl->broughtToFront(); }
  518. unsigned long XEmbedComponent::getHostWindowID() { return pimpl->getHostWindowID(); }
  519. //==============================================================================
  520. bool juce_handleXEmbedEvent (ComponentPeer* p, void* e)
  521. {
  522. return XEmbedComponent::Pimpl::dispatchX11Event (p, reinterpret_cast<const XEvent*> (e));
  523. }
  524. unsigned long juce_getCurrentFocusWindow (ComponentPeer* peer)
  525. {
  526. return (unsigned long) XEmbedComponent::Pimpl::getCurrentFocusWindow (peer);
  527. }
  528. } // namespace juce