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.

686 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. //==============================================================================
  21. static int numAlwaysOnTopPeers = 0;
  22. bool juce_areThereAnyAlwaysOnTopWindows() { return numAlwaysOnTopPeers > 0; }
  23. //==============================================================================
  24. template<typename WindowHandleType>
  25. class LinuxComponentPeer : public ComponentPeer
  26. {
  27. public:
  28. LinuxComponentPeer (Component& comp, int windowStyleFlags, WindowHandleType parentToAddTo)
  29. : ComponentPeer (comp, windowStyleFlags),
  30. isAlwaysOnTop (comp.isAlwaysOnTop())
  31. {
  32. // it's dangerous to create a window on a thread other than the message thread..
  33. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  34. if (isAlwaysOnTop)
  35. ++numAlwaysOnTopPeers;
  36. repainter = std::make_unique<LinuxRepaintManager> (*this);
  37. windowH = XWindowSystem::getInstance()->createWindow (parentToAddTo, this);
  38. parentWindow = parentToAddTo;
  39. setTitle (component.getName());
  40. getNativeRealtimeModifiers = []() -> ModifierKeys { return XWindowSystem::getInstance()->getNativeRealtimeModifiers(); };
  41. }
  42. ~LinuxComponentPeer() override
  43. {
  44. // it's dangerous to delete a window on a thread other than the message thread..
  45. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  46. repainter = nullptr;
  47. XWindowSystem::getInstance()->destroyWindow (windowH);
  48. if (isAlwaysOnTop)
  49. --numAlwaysOnTopPeers;
  50. }
  51. //==============================================================================
  52. void* getNativeHandle() const override
  53. {
  54. return (void*) windowH;
  55. }
  56. //==============================================================================
  57. void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
  58. {
  59. bounds = newBounds.withSize (jmax (1, newBounds.getWidth()),
  60. jmax (1, newBounds.getHeight()));
  61. updateScaleFactorFromNewBounds (bounds, false);
  62. auto physicalBounds = (parentWindow == 0 ? Desktop::getInstance().getDisplays().logicalToPhysical (bounds)
  63. : bounds * currentScaleFactor);
  64. WeakReference<Component> deletionChecker (&component);
  65. XWindowSystem::getInstance()->setBounds (windowH, physicalBounds, isNowFullScreen);
  66. fullScreen = isNowFullScreen;
  67. if (deletionChecker != nullptr)
  68. {
  69. updateBorderSize();
  70. handleMovedOrResized();
  71. }
  72. }
  73. Point<int> getScreenPosition (bool physical) const
  74. {
  75. auto parentPosition = XWindowSystem::getInstance()->getParentScreenPosition();
  76. auto screenBounds = (parentWindow == 0 ? bounds
  77. : bounds.translated (parentPosition.x, parentPosition.y));
  78. if (physical)
  79. return Desktop::getInstance().getDisplays().logicalToPhysical (screenBounds.getTopLeft());
  80. return screenBounds.getTopLeft();
  81. }
  82. Rectangle<int> getBounds() const override
  83. {
  84. return bounds;
  85. }
  86. BorderSize<int> getFrameSize() const override
  87. {
  88. return windowBorder;
  89. }
  90. Point<float> localToGlobal (Point<float> relativePosition) override
  91. {
  92. return relativePosition + getScreenPosition (false).toFloat();
  93. }
  94. Point<float> globalToLocal (Point<float> screenPosition) override
  95. {
  96. return screenPosition - getScreenPosition (false).toFloat();
  97. }
  98. using ComponentPeer::localToGlobal;
  99. using ComponentPeer::globalToLocal;
  100. //==============================================================================
  101. StringArray getAvailableRenderingEngines() override
  102. {
  103. return { "Software Renderer" };
  104. }
  105. void setVisible (bool shouldBeVisible) override
  106. {
  107. XWindowSystem::getInstance()->setVisible (windowH, shouldBeVisible);
  108. }
  109. void setTitle (const String& title) override
  110. {
  111. XWindowSystem::getInstance()->setTitle (windowH, title);
  112. }
  113. void setMinimised (bool shouldBeMinimised) override
  114. {
  115. if (shouldBeMinimised)
  116. XWindowSystem::getInstance()->setMinimised (windowH, shouldBeMinimised);
  117. else
  118. setVisible (true);
  119. }
  120. bool isMinimised() const override
  121. {
  122. return XWindowSystem::getInstance()->isMinimised (windowH);
  123. }
  124. void setFullScreen (bool shouldBeFullScreen) override
  125. {
  126. auto r = lastNonFullscreenBounds; // (get a copy of this before de-minimising)
  127. setMinimised (false);
  128. if (fullScreen != shouldBeFullScreen)
  129. {
  130. if (shouldBeFullScreen)
  131. r = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  132. if (! r.isEmpty())
  133. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  134. component.repaint();
  135. }
  136. }
  137. bool isFullScreen() const override
  138. {
  139. return fullScreen;
  140. }
  141. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  142. {
  143. if (! bounds.withZeroOrigin().contains (localPos))
  144. return false;
  145. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  146. {
  147. auto* c = Desktop::getInstance().getComponent (i);
  148. if (c == &component)
  149. break;
  150. if (! c->isVisible())
  151. continue;
  152. if (auto* peer = c->getPeer())
  153. if (peer->contains (localPos + bounds.getPosition() - peer->getBounds().getPosition(), true))
  154. return false;
  155. }
  156. if (trueIfInAChildWindow)
  157. return true;
  158. return XWindowSystem::getInstance()->contains (windowH, localPos * currentScaleFactor);
  159. }
  160. void toFront (bool makeActive) override
  161. {
  162. if (makeActive)
  163. {
  164. setVisible (true);
  165. grabFocus();
  166. }
  167. XWindowSystem::getInstance()->toFront (windowH, makeActive);
  168. handleBroughtToFront();
  169. }
  170. void toBehind (ComponentPeer* other) override
  171. {
  172. if (auto* otherPeer = dynamic_cast<LinuxComponentPeer*> (other))
  173. {
  174. if (otherPeer->styleFlags & windowIsTemporary)
  175. return;
  176. setMinimised (false);
  177. XWindowSystem::getInstance()->toBehind (windowH, otherPeer->windowH);
  178. }
  179. else
  180. {
  181. jassertfalse; // wrong type of window?
  182. }
  183. }
  184. bool isFocused() const override
  185. {
  186. return XWindowSystem::getInstance()->isFocused (windowH);
  187. }
  188. void grabFocus() override
  189. {
  190. if (XWindowSystem::getInstance()->grabFocus (windowH))
  191. isActiveApplication = true;
  192. }
  193. //==============================================================================
  194. void repaint (const Rectangle<int>& area) override
  195. {
  196. repainter->repaint (area.getIntersection (bounds.withZeroOrigin()));
  197. }
  198. void performAnyPendingRepaintsNow() override
  199. {
  200. repainter->performAnyPendingRepaintsNow();
  201. }
  202. void setIcon (const Image& newIcon) override
  203. {
  204. XWindowSystem::getInstance()->setIcon (windowH, newIcon);
  205. }
  206. double getPlatformScaleFactor() const noexcept override
  207. {
  208. return currentScaleFactor;
  209. }
  210. void setAlpha (float) override {}
  211. bool setAlwaysOnTop (bool) override { return false; }
  212. void textInputRequired (Point<int>, TextInputTarget&) override {}
  213. //==============================================================================
  214. void addOpenGLRepaintListener (Component* dummy)
  215. {
  216. if (dummy != nullptr)
  217. glRepaintListeners.addIfNotAlreadyThere (dummy);
  218. }
  219. void removeOpenGLRepaintListener (Component* dummy)
  220. {
  221. if (dummy != nullptr)
  222. glRepaintListeners.removeAllInstancesOf (dummy);
  223. }
  224. void repaintOpenGLContexts()
  225. {
  226. for (auto* c : glRepaintListeners)
  227. c->handleCommandMessage (0);
  228. }
  229. //==============================================================================
  230. WindowHandleType getParentWindow() { return parentWindow; }
  231. void setParentWindow (WindowHandleType newParent) { parentWindow = newParent; }
  232. //==============================================================================
  233. void updateWindowBounds()
  234. {
  235. jassert (windowH != 0);
  236. if (windowH != 0)
  237. {
  238. auto physicalBounds = XWindowSystem::getInstance()->getWindowBounds (windowH, parentWindow);
  239. updateScaleFactorFromNewBounds (physicalBounds, true);
  240. bounds = (parentWindow == 0 ? Desktop::getInstance().getDisplays().physicalToLogical (physicalBounds)
  241. : physicalBounds / currentScaleFactor);
  242. }
  243. }
  244. void updateBorderSize()
  245. {
  246. if ((styleFlags & windowHasTitleBar) == 0)
  247. windowBorder = {};
  248. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  249. windowBorder = XWindowSystem::getInstance()->getBorderSize (windowH);
  250. }
  251. //==============================================================================
  252. static bool isActiveApplication;
  253. bool focused = false;
  254. private:
  255. //==============================================================================
  256. class LinuxRepaintManager : public Timer
  257. {
  258. public:
  259. LinuxRepaintManager (LinuxComponentPeer& p) : peer (p) {}
  260. void timerCallback() override
  261. {
  262. if (XWindowSystem::getInstance()->getNumPaintsPending (peer.windowH) > 0)
  263. return;
  264. if (! regionsNeedingRepaint.isEmpty())
  265. {
  266. stopTimer();
  267. performAnyPendingRepaintsNow();
  268. }
  269. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  270. {
  271. stopTimer();
  272. image = Image();
  273. }
  274. }
  275. void repaint (Rectangle<int> area)
  276. {
  277. if (! isTimerRunning())
  278. startTimer (repaintTimerPeriod);
  279. regionsNeedingRepaint.add (area * peer.currentScaleFactor);
  280. }
  281. void performAnyPendingRepaintsNow()
  282. {
  283. if (XWindowSystem::getInstance()->getNumPaintsPending (peer.windowH) > 0)
  284. {
  285. startTimer (repaintTimerPeriod);
  286. return;
  287. }
  288. auto originalRepaintRegion = regionsNeedingRepaint;
  289. regionsNeedingRepaint.clear();
  290. auto totalArea = originalRepaintRegion.getBounds();
  291. if (! totalArea.isEmpty())
  292. {
  293. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  294. || image.getHeight() < totalArea.getHeight())
  295. {
  296. image = XWindowSystem::getInstance()->createImage (totalArea.getWidth(), totalArea.getHeight(),
  297. useARGBImagesForRendering);
  298. }
  299. startTimer (repaintTimerPeriod);
  300. RectangleList<int> adjustedList (originalRepaintRegion);
  301. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  302. if (XWindowSystem::getInstance()->canUseARGBImages())
  303. for (auto& i : originalRepaintRegion)
  304. image.clear (i - totalArea.getPosition());
  305. {
  306. auto context = peer.getComponent().getLookAndFeel()
  307. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList);
  308. context->addTransform (AffineTransform::scale ((float) peer.currentScaleFactor));
  309. peer.handlePaint (*context);
  310. }
  311. for (auto& i : originalRepaintRegion)
  312. XWindowSystem::getInstance()->blitToWindow (peer.windowH, image, i, totalArea);
  313. }
  314. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  315. startTimer (repaintTimerPeriod);
  316. }
  317. private:
  318. enum { repaintTimerPeriod = 1000 / 100 };
  319. LinuxComponentPeer& peer;
  320. Image image;
  321. uint32 lastTimeImageUsed = 0;
  322. RectangleList<int> regionsNeedingRepaint;
  323. bool useARGBImagesForRendering = XWindowSystem::getInstance()->canUseARGBImages();
  324. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  325. };
  326. //==============================================================================
  327. void updateScaleFactorFromNewBounds (const Rectangle<int>& newBounds, bool isPhysical)
  328. {
  329. if (! JUCEApplicationBase::isStandaloneApp())
  330. return;
  331. Point<int> translation = (parentWindow != 0 ? getScreenPosition (isPhysical) : Point<int>());
  332. auto newScaleFactor = Desktop::getInstance().getDisplays().findDisplayForRect (newBounds.translated (translation.x, translation.y), isPhysical).scale
  333. / Desktop::getInstance().getGlobalScaleFactor();
  334. if (! approximatelyEqual (newScaleFactor, currentScaleFactor))
  335. {
  336. currentScaleFactor = newScaleFactor;
  337. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (currentScaleFactor); });
  338. }
  339. }
  340. //==============================================================================
  341. std::unique_ptr<LinuxRepaintManager> repainter;
  342. WindowHandleType windowH = {}, parentWindow = {}, keyProxy = {};
  343. Rectangle<int> bounds;
  344. BorderSize<int> windowBorder;
  345. bool fullScreen = false, isAlwaysOnTop = false;
  346. double currentScaleFactor = 1.0;
  347. Array<Component*> glRepaintListeners;
  348. //==============================================================================
  349. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  350. };
  351. template<typename WindowHandleType>
  352. bool LinuxComponentPeer<WindowHandleType>::isActiveApplication = false;
  353. //==============================================================================
  354. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  355. {
  356. return new LinuxComponentPeer<::Window> (*this, styleFlags, (::Window) nativeWindowToAttachTo);
  357. }
  358. //==============================================================================
  359. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess() { return LinuxComponentPeer<::Window>::isActiveApplication; }
  360. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  361. JUCE_API void JUCE_CALLTYPE Process::hide() {}
  362. //==============================================================================
  363. void Desktop::setKioskComponent (Component* comp, bool enableOrDisable, bool)
  364. {
  365. if (enableOrDisable)
  366. comp->setBounds (getDisplays().findDisplayForRect (comp->getScreenBounds()).totalArea);
  367. }
  368. void Displays::findDisplays (float masterScale)
  369. {
  370. displays = XWindowSystem::getInstance()->findDisplays (masterScale);
  371. if (! displays.isEmpty())
  372. updateToLogical();
  373. }
  374. bool Desktop::canUseSemiTransparentWindows() noexcept
  375. {
  376. return XWindowSystem::getInstance()->canUseSemiTransparentWindows();
  377. }
  378. static bool screenSaverAllowed = true;
  379. void Desktop::setScreenSaverEnabled (bool isEnabled)
  380. {
  381. if (screenSaverAllowed != isEnabled)
  382. {
  383. screenSaverAllowed = isEnabled;
  384. XWindowSystem::getInstance()->setScreenSaverEnabled (screenSaverAllowed);
  385. }
  386. }
  387. bool Desktop::isScreenSaverEnabled()
  388. {
  389. return screenSaverAllowed;
  390. }
  391. double Desktop::getDefaultMasterScale() { return 1.0; }
  392. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const { return upright; }
  393. void Desktop::allowedOrientationsChanged() {}
  394. //==============================================================================
  395. bool MouseInputSource::SourceList::addSource()
  396. {
  397. if (sources.isEmpty())
  398. {
  399. addSource (0, MouseInputSource::InputSourceType::mouse);
  400. return true;
  401. }
  402. return false;
  403. }
  404. bool MouseInputSource::SourceList::canUseTouch()
  405. {
  406. return false;
  407. }
  408. Point<float> MouseInputSource::getCurrentRawMousePosition()
  409. {
  410. return Desktop::getInstance().getDisplays().physicalToLogical (XWindowSystem::getInstance()->getCurrentMousePosition());
  411. }
  412. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  413. {
  414. XWindowSystem::getInstance()->setMousePosition (Desktop::getInstance().getDisplays().logicalToPhysical (newPosition));
  415. }
  416. //==============================================================================
  417. void* CustomMouseCursorInfo::create() const
  418. {
  419. return XWindowSystem::getInstance()->createCustomMouseCursorInfo (image, hotspot);
  420. }
  421. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool)
  422. {
  423. if (cursorHandle != nullptr)
  424. XWindowSystem::getInstance()->deleteMouseCursor (cursorHandle);
  425. }
  426. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  427. {
  428. return XWindowSystem::getInstance()->createStandardMouseCursor (type);
  429. }
  430. void MouseCursor::showInWindow (ComponentPeer* peer) const
  431. {
  432. if (peer != nullptr)
  433. XWindowSystem::getInstance()->showCursor ((::Window) peer->getNativeHandle(), getHandle());
  434. }
  435. //==============================================================================
  436. template<typename WindowHandleType>
  437. static LinuxComponentPeer<WindowHandleType>* getPeerForDragEvent (Component* sourceComp)
  438. {
  439. if (sourceComp == nullptr)
  440. if (auto* draggingSource = Desktop::getInstance().getDraggingMouseSource (0))
  441. sourceComp = draggingSource->getComponentUnderMouse();
  442. if (sourceComp != nullptr)
  443. if (auto* lp = dynamic_cast<LinuxComponentPeer<::Window>*> (sourceComp->getPeer()))
  444. return lp;
  445. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  446. return nullptr;
  447. }
  448. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles,
  449. Component* sourceComp, std::function<void()> callback)
  450. {
  451. if (files.isEmpty())
  452. return false;
  453. if (auto* peer = getPeerForDragEvent<::Window> (sourceComp))
  454. return XWindowSystem::getInstance()->externalDragFileInit (peer, files, canMoveFiles, std::move (callback));
  455. // This method must be called in response to a component's mouseDown or mouseDrag event!
  456. jassertfalse;
  457. return false;
  458. }
  459. bool DragAndDropContainer::performExternalDragDropOfText (const String& text, Component* sourceComp,
  460. std::function<void()> callback)
  461. {
  462. if (text.isEmpty())
  463. return false;
  464. if (auto* peer = getPeerForDragEvent<::Window> (sourceComp))
  465. return XWindowSystem::getInstance()->externalDragTextInit (peer, text, std::move (callback));
  466. // This method must be called in response to a component's mouseDown or mouseDrag event!
  467. jassertfalse;
  468. return false;
  469. }
  470. //==============================================================================
  471. void SystemClipboard::copyTextToClipboard (const String& clipText)
  472. {
  473. XWindowSystem::getInstance()->copyTextToClipboard (clipText);
  474. }
  475. String SystemClipboard::getTextFromClipboard()
  476. {
  477. return XWindowSystem::getInstance()->getTextFromClipboard();
  478. }
  479. //==============================================================================
  480. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  481. {
  482. return XWindowSystem::getInstance()->isKeyCurrentlyDown (keyCode);
  483. }
  484. void LookAndFeel::playAlertSound()
  485. {
  486. std::cout << "\a" << std::flush;
  487. }
  488. //==============================================================================
  489. #if JUCE_MODAL_LOOPS_PERMITTED
  490. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  491. const String& title, const String& message,
  492. Component*)
  493. {
  494. AlertWindow::showMessageBox (iconType, title, message);
  495. }
  496. #endif
  497. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  498. const String& title, const String& message,
  499. Component* associatedComponent,
  500. ModalComponentManager::Callback* callback)
  501. {
  502. AlertWindow::showMessageBoxAsync (iconType, title, message, {}, associatedComponent, callback);
  503. }
  504. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  505. const String& title, const String& message,
  506. Component* associatedComponent,
  507. ModalComponentManager::Callback* callback)
  508. {
  509. return AlertWindow::showOkCancelBox (iconType, title, message, {}, {}, associatedComponent, callback);
  510. }
  511. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  512. const String& title, const String& message,
  513. Component* associatedComponent,
  514. ModalComponentManager::Callback* callback)
  515. {
  516. return AlertWindow::showYesNoCancelBox (iconType, title, message, {}, {}, {},
  517. associatedComponent, callback);
  518. }
  519. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  520. const String& title, const String& message,
  521. Component* associatedComponent,
  522. ModalComponentManager::Callback* callback)
  523. {
  524. return AlertWindow::showOkCancelBox (iconType, title, message, TRANS ("Yes"), TRANS ("No"),
  525. associatedComponent, callback);
  526. }
  527. //==============================================================================
  528. Image juce_createIconForFile (const File&)
  529. {
  530. return {};
  531. }
  532. void juce_LinuxAddRepaintListener (ComponentPeer* peer, Component* dummy)
  533. {
  534. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer<::Window>*> (peer))
  535. linuxPeer->addOpenGLRepaintListener (dummy);
  536. }
  537. void juce_LinuxRemoveRepaintListener (ComponentPeer* peer, Component* dummy)
  538. {
  539. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer<::Window>*> (peer))
  540. linuxPeer->removeOpenGLRepaintListener (dummy);
  541. }
  542. } // namespace juce