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.

703 lines
24KB

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