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.

685 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() override
  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. long version;
  310. memcpy (&version, embedInfo.data, sizeof (long));
  311. supportsXembed = true;
  312. xembedVersion = jmin ((int) maxXEmbedVersionToSupport, (int) version);
  313. long flags;
  314. memcpy (&flags, embedInfo.data + sizeof (long), sizeof (long));
  315. return ((flags & XEMBED_MAPPED) != 0);
  316. }
  317. else
  318. {
  319. supportsXembed = false;
  320. xembedVersion = maxXEmbedVersionToSupport;
  321. }
  322. return true;
  323. }
  324. //==============================================================================
  325. void propertyChanged (const Atom& a)
  326. {
  327. if (a == atoms.XembedInfo)
  328. updateMapping();
  329. }
  330. void configureNotify()
  331. {
  332. XWindowAttributes attr;
  333. auto dpy = getDisplay();
  334. if (XGetWindowAttributes (dpy, client, &attr))
  335. {
  336. XWindowAttributes hostAttr;
  337. if (XGetWindowAttributes (dpy, host, &hostAttr))
  338. if (attr.width != hostAttr.width || attr.height != hostAttr.height)
  339. XResizeWindow (dpy, host, (unsigned int) attr.width, (unsigned int) attr.height);
  340. // as the client window is not on any screen yet, we need to guess
  341. // on which screen it might appear to get a scaling factor :-(
  342. auto& displays = Desktop::getInstance().getDisplays();
  343. auto* peer = owner.getPeer();
  344. const double scale = (peer != nullptr ? peer->getPlatformScaleFactor()
  345. : displays.getMainDisplay().scale);
  346. Point<int> topLeftInPeer
  347. = (peer != nullptr ? peer->getComponent().getLocalPoint (&owner, Point<int> (0, 0))
  348. : owner.getBounds().getTopLeft());
  349. Rectangle<int> newBounds (topLeftInPeer.getX(), topLeftInPeer.getY(),
  350. static_cast<int> (static_cast<double> (attr.width) / scale),
  351. static_cast<int> (static_cast<double> (attr.height) / scale));
  352. if (peer != nullptr)
  353. newBounds = owner.getLocalArea (&peer->getComponent(), newBounds);
  354. jassert (newBounds.getX() == 0 && newBounds.getY() == 0);
  355. if (newBounds != owner.getLocalBounds())
  356. owner.setSize (newBounds.getWidth(), newBounds.getHeight());
  357. }
  358. }
  359. void peerChanged (ComponentPeer* newPeer)
  360. {
  361. if (newPeer != lastPeer)
  362. {
  363. if (lastPeer != nullptr)
  364. keyWindow = nullptr;
  365. auto dpy = getDisplay();
  366. Window rootWindow = RootWindow (dpy, DefaultScreen (dpy));
  367. Rectangle<int> newBounds = getX11BoundsFromJuce();
  368. if (newPeer == nullptr)
  369. XUnmapWindow (dpy, host);
  370. Window newParent = (newPeer != nullptr ? getParentX11Window() : rootWindow);
  371. XReparentWindow (dpy, host, newParent, newBounds.getX(), newBounds.getY());
  372. lastPeer = newPeer;
  373. if (newPeer != nullptr)
  374. {
  375. if (wantsFocus)
  376. {
  377. keyWindow = SharedKeyWindow::getKeyWindowForPeer (newPeer);
  378. updateKeyFocus();
  379. }
  380. componentMovedOrResized (owner, true, true);
  381. XMapWindow (dpy, host);
  382. broughtToFront();
  383. }
  384. }
  385. }
  386. void updateKeyFocus()
  387. {
  388. if (lastPeer != nullptr && lastPeer->isFocused())
  389. XSetInputFocus (getDisplay(), getCurrentFocusWindow (lastPeer), RevertToParent, CurrentTime);
  390. }
  391. //==============================================================================
  392. void handleXembedCmd (const ::Time& /*xTime*/, long opcode, long /*detail*/, long /*data1*/, long /*data2*/)
  393. {
  394. switch (opcode)
  395. {
  396. case XEMBED_REQUEST_FOCUS:
  397. if (wantsFocus)
  398. owner.grabKeyboardFocus();
  399. break;
  400. case XEMBED_FOCUS_NEXT:
  401. if (wantsFocus)
  402. owner.moveKeyboardFocusToSibling (true);
  403. break;
  404. case XEMBED_FOCUS_PREV:
  405. if (wantsFocus)
  406. owner.moveKeyboardFocusToSibling (false);
  407. break;
  408. }
  409. }
  410. bool handleX11Event (const XEvent& e)
  411. {
  412. if (e.xany.window == client && client != 0)
  413. {
  414. switch (e.type)
  415. {
  416. case PropertyNotify:
  417. propertyChanged (e.xproperty.atom);
  418. return true;
  419. case ConfigureNotify:
  420. if (allowResize)
  421. configureNotify();
  422. else
  423. MessageManager::callAsync ([this] {componentMovedOrResized (owner, true, true);});
  424. return true;
  425. }
  426. }
  427. else if (e.xany.window == host && host != 0)
  428. {
  429. switch (e.type)
  430. {
  431. case ReparentNotify:
  432. if (e.xreparent.parent == host && e.xreparent.window != client)
  433. {
  434. setClient (e.xreparent.window, false);
  435. return true;
  436. }
  437. break;
  438. case CreateNotify:
  439. if (e.xcreatewindow.parent != e.xcreatewindow.window && e.xcreatewindow.parent == host && e.xcreatewindow.window != client)
  440. {
  441. setClient (e.xcreatewindow.window, false);
  442. return true;
  443. }
  444. break;
  445. case GravityNotify:
  446. componentMovedOrResized (owner, true, true);
  447. return true;
  448. case ClientMessage:
  449. if (e.xclient.message_type == atoms.XembedMsgType && e.xclient.format == 32)
  450. {
  451. handleXembedCmd ((::Time) e.xclient.data.l[0], e.xclient.data.l[1],
  452. e.xclient.data.l[2], e.xclient.data.l[3],
  453. e.xclient.data.l[4]);
  454. return true;
  455. }
  456. break;
  457. }
  458. }
  459. return false;
  460. }
  461. void sendXEmbedEvent (const ::Time& xTime, long opcode,
  462. long opcodeMinor = 0, long data1 = 0, long data2 = 0)
  463. {
  464. XClientMessageEvent msg;
  465. auto dpy = getDisplay();
  466. ::memset (&msg, 0, sizeof (XClientMessageEvent));
  467. msg.window = client;
  468. msg.type = ClientMessage;
  469. msg.message_type = atoms.XembedMsgType;
  470. msg.format = 32;
  471. msg.data.l[0] = (long) xTime;
  472. msg.data.l[1] = opcode;
  473. msg.data.l[2] = opcodeMinor;
  474. msg.data.l[3] = data1;
  475. msg.data.l[4] = data2;
  476. XSendEvent (dpy, client, False, NoEventMask, (XEvent*) &msg);
  477. XSync (dpy, False);
  478. }
  479. Rectangle<int> getX11BoundsFromJuce()
  480. {
  481. if (auto* peer = owner.getPeer())
  482. {
  483. auto r = peer->getComponent().getLocalArea (&owner, owner.getLocalBounds());
  484. return r * peer->getPlatformScaleFactor();
  485. }
  486. return owner.getLocalBounds();
  487. }
  488. //==============================================================================
  489. friend bool juce::juce_handleXEmbedEvent (ComponentPeer*, void*);
  490. friend unsigned long juce::juce_getCurrentFocusWindow (ComponentPeer*);
  491. static Array<Pimpl*>& getWidgets()
  492. {
  493. static Array<Pimpl*> i;
  494. return i;
  495. }
  496. static bool dispatchX11Event (ComponentPeer* p, const XEvent* eventArg)
  497. {
  498. if (eventArg != nullptr)
  499. {
  500. auto& e = *eventArg;
  501. if (auto w = e.xany.window)
  502. for (auto* widget : getWidgets())
  503. if (w == widget->host || w == widget->client)
  504. return widget->handleX11Event (e);
  505. }
  506. else
  507. {
  508. for (auto* widget : getWidgets())
  509. if (widget->owner.getPeer() == p)
  510. widget->peerChanged (nullptr);
  511. }
  512. return false;
  513. }
  514. static Window getCurrentFocusWindow (ComponentPeer* p)
  515. {
  516. if (p != nullptr)
  517. {
  518. for (auto* widget : getWidgets())
  519. if (widget->owner.getPeer() == p && widget->owner.hasKeyboardFocus (false))
  520. return widget->client;
  521. }
  522. return SharedKeyWindow::getCurrentFocusWindow (p);
  523. }
  524. };
  525. //==============================================================================
  526. XEmbedComponent::XEmbedComponent (bool wantsKeyboardFocus, bool allowForeignWidgetToResizeComponent)
  527. : pimpl (new Pimpl (*this, 0, wantsKeyboardFocus, false, allowForeignWidgetToResizeComponent))
  528. {
  529. setOpaque (true);
  530. }
  531. XEmbedComponent::XEmbedComponent (unsigned long wID, bool wantsKeyboardFocus, bool allowForeignWidgetToResizeComponent)
  532. : pimpl (new Pimpl (*this, wID, wantsKeyboardFocus, true, allowForeignWidgetToResizeComponent))
  533. {
  534. setOpaque (true);
  535. }
  536. XEmbedComponent::~XEmbedComponent() {}
  537. void XEmbedComponent::paint (Graphics& g)
  538. {
  539. g.fillAll (Colours::lightgrey);
  540. }
  541. void XEmbedComponent::focusGained (FocusChangeType changeType) { pimpl->focusGained (changeType); }
  542. void XEmbedComponent::focusLost (FocusChangeType changeType) { pimpl->focusLost (changeType); }
  543. void XEmbedComponent::broughtToFront() { pimpl->broughtToFront(); }
  544. unsigned long XEmbedComponent::getHostWindowID() { return pimpl->getHostWindowID(); }
  545. //==============================================================================
  546. bool juce_handleXEmbedEvent (ComponentPeer* p, void* e)
  547. {
  548. return XEmbedComponent::Pimpl::dispatchX11Event (p, reinterpret_cast<const XEvent*> (e));
  549. }
  550. unsigned long juce_getCurrentFocusWindow (ComponentPeer* peer)
  551. {
  552. return (unsigned long) XEmbedComponent::Pimpl::getCurrentFocusWindow (peer);
  553. }
  554. } // namespace juce