Audio plugin host https://kx.studio/carla
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.

682 lines
23KB

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