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.

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