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.

694 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)
  260. : peer (p),
  261. isSemiTransparentWindow ((peer.getStyleFlags() & ComponentPeer::windowIsSemiTransparent) != 0)
  262. {
  263. }
  264. void timerCallback() override
  265. {
  266. XWindowSystem::getInstance()->processPendingPaintsForWindow (peer.windowH);
  267. if (XWindowSystem::getInstance()->getNumPaintsPendingForWindow (peer.windowH) > 0)
  268. return;
  269. if (! regionsNeedingRepaint.isEmpty())
  270. {
  271. stopTimer();
  272. performAnyPendingRepaintsNow();
  273. }
  274. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  275. {
  276. stopTimer();
  277. image = Image();
  278. }
  279. }
  280. void repaint (Rectangle<int> area)
  281. {
  282. if (! isTimerRunning())
  283. startTimer (repaintTimerPeriod);
  284. regionsNeedingRepaint.add (area * peer.currentScaleFactor);
  285. }
  286. void performAnyPendingRepaintsNow()
  287. {
  288. if (XWindowSystem::getInstance()->getNumPaintsPendingForWindow (peer.windowH) > 0)
  289. {
  290. startTimer (repaintTimerPeriod);
  291. return;
  292. }
  293. auto originalRepaintRegion = regionsNeedingRepaint;
  294. regionsNeedingRepaint.clear();
  295. auto totalArea = originalRepaintRegion.getBounds();
  296. if (! totalArea.isEmpty())
  297. {
  298. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  299. || image.getHeight() < totalArea.getHeight())
  300. {
  301. image = XWindowSystem::getInstance()->createImage (isSemiTransparentWindow,
  302. totalArea.getWidth(), totalArea.getHeight(),
  303. useARGBImagesForRendering);
  304. }
  305. startTimer (repaintTimerPeriod);
  306. RectangleList<int> adjustedList (originalRepaintRegion);
  307. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  308. if (XWindowSystem::getInstance()->canUseARGBImages())
  309. for (auto& i : originalRepaintRegion)
  310. image.clear (i - totalArea.getPosition());
  311. {
  312. auto context = peer.getComponent().getLookAndFeel()
  313. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList);
  314. context->addTransform (AffineTransform::scale ((float) peer.currentScaleFactor));
  315. peer.handlePaint (*context);
  316. }
  317. for (auto& i : originalRepaintRegion)
  318. XWindowSystem::getInstance()->blitToWindow (peer.windowH, image, i, totalArea);
  319. }
  320. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  321. startTimer (repaintTimerPeriod);
  322. }
  323. private:
  324. enum { repaintTimerPeriod = 1000 / 100 };
  325. LinuxComponentPeer& peer;
  326. const bool isSemiTransparentWindow;
  327. Image image;
  328. uint32 lastTimeImageUsed = 0;
  329. RectangleList<int> regionsNeedingRepaint;
  330. bool useARGBImagesForRendering = XWindowSystem::getInstance()->canUseARGBImages();
  331. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  332. };
  333. //==============================================================================
  334. void updateScaleFactorFromNewBounds (const Rectangle<int>& newBounds, bool isPhysical)
  335. {
  336. if (! JUCEApplicationBase::isStandaloneApp())
  337. return;
  338. Point<int> translation = (parentWindow != 0 ? getScreenPosition (isPhysical) : Point<int>());
  339. auto newScaleFactor = Desktop::getInstance().getDisplays().findDisplayForRect (newBounds.translated (translation.x, translation.y), isPhysical).scale
  340. / Desktop::getInstance().getGlobalScaleFactor();
  341. if (! approximatelyEqual (newScaleFactor, currentScaleFactor))
  342. {
  343. currentScaleFactor = newScaleFactor;
  344. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (currentScaleFactor); });
  345. }
  346. }
  347. //==============================================================================
  348. std::unique_ptr<LinuxRepaintManager> repainter;
  349. WindowHandleType windowH = {}, parentWindow = {}, keyProxy = {};
  350. Rectangle<int> bounds;
  351. BorderSize<int> windowBorder;
  352. bool fullScreen = false, isAlwaysOnTop = false;
  353. double currentScaleFactor = 1.0;
  354. Array<Component*> glRepaintListeners;
  355. //==============================================================================
  356. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  357. };
  358. template<typename WindowHandleType>
  359. bool LinuxComponentPeer<WindowHandleType>::isActiveApplication = false;
  360. //==============================================================================
  361. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  362. {
  363. return new LinuxComponentPeer<::Window> (*this, styleFlags, (::Window) nativeWindowToAttachTo);
  364. }
  365. //==============================================================================
  366. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess() { return LinuxComponentPeer<::Window>::isActiveApplication; }
  367. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  368. JUCE_API void JUCE_CALLTYPE Process::hide() {}
  369. //==============================================================================
  370. void Desktop::setKioskComponent (Component* comp, bool enableOrDisable, bool)
  371. {
  372. if (enableOrDisable)
  373. comp->setBounds (getDisplays().findDisplayForRect (comp->getScreenBounds()).totalArea);
  374. }
  375. void Displays::findDisplays (float masterScale)
  376. {
  377. displays = XWindowSystem::getInstance()->findDisplays (masterScale);
  378. if (! displays.isEmpty())
  379. updateToLogical();
  380. }
  381. bool Desktop::canUseSemiTransparentWindows() noexcept
  382. {
  383. return XWindowSystem::getInstance()->canUseSemiTransparentWindows();
  384. }
  385. static bool screenSaverAllowed = true;
  386. void Desktop::setScreenSaverEnabled (bool isEnabled)
  387. {
  388. if (screenSaverAllowed != isEnabled)
  389. {
  390. screenSaverAllowed = isEnabled;
  391. XWindowSystem::getInstance()->setScreenSaverEnabled (screenSaverAllowed);
  392. }
  393. }
  394. bool Desktop::isScreenSaverEnabled()
  395. {
  396. return screenSaverAllowed;
  397. }
  398. double Desktop::getDefaultMasterScale() { return 1.0; }
  399. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const { return upright; }
  400. void Desktop::allowedOrientationsChanged() {}
  401. //==============================================================================
  402. bool MouseInputSource::SourceList::addSource()
  403. {
  404. if (sources.isEmpty())
  405. {
  406. addSource (0, MouseInputSource::InputSourceType::mouse);
  407. return true;
  408. }
  409. return false;
  410. }
  411. bool MouseInputSource::SourceList::canUseTouch()
  412. {
  413. return false;
  414. }
  415. Point<float> MouseInputSource::getCurrentRawMousePosition()
  416. {
  417. return Desktop::getInstance().getDisplays().physicalToLogical (XWindowSystem::getInstance()->getCurrentMousePosition());
  418. }
  419. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  420. {
  421. XWindowSystem::getInstance()->setMousePosition (Desktop::getInstance().getDisplays().logicalToPhysical (newPosition));
  422. }
  423. //==============================================================================
  424. void* CustomMouseCursorInfo::create() const
  425. {
  426. return XWindowSystem::getInstance()->createCustomMouseCursorInfo (image, hotspot);
  427. }
  428. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool)
  429. {
  430. if (cursorHandle != nullptr)
  431. XWindowSystem::getInstance()->deleteMouseCursor (cursorHandle);
  432. }
  433. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  434. {
  435. return XWindowSystem::getInstance()->createStandardMouseCursor (type);
  436. }
  437. void MouseCursor::showInWindow (ComponentPeer* peer) const
  438. {
  439. if (peer != nullptr)
  440. XWindowSystem::getInstance()->showCursor ((::Window) peer->getNativeHandle(), getHandle());
  441. }
  442. //==============================================================================
  443. template<typename WindowHandleType>
  444. static LinuxComponentPeer<WindowHandleType>* getPeerForDragEvent (Component* sourceComp)
  445. {
  446. if (sourceComp == nullptr)
  447. if (auto* draggingSource = Desktop::getInstance().getDraggingMouseSource (0))
  448. sourceComp = draggingSource->getComponentUnderMouse();
  449. if (sourceComp != nullptr)
  450. if (auto* lp = dynamic_cast<LinuxComponentPeer<::Window>*> (sourceComp->getPeer()))
  451. return lp;
  452. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  453. return nullptr;
  454. }
  455. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles,
  456. Component* sourceComp, std::function<void()> callback)
  457. {
  458. if (files.isEmpty())
  459. return false;
  460. if (auto* peer = getPeerForDragEvent<::Window> (sourceComp))
  461. return XWindowSystem::getInstance()->externalDragFileInit (peer, files, canMoveFiles, std::move (callback));
  462. // This method must be called in response to a component's mouseDown or mouseDrag event!
  463. jassertfalse;
  464. return false;
  465. }
  466. bool DragAndDropContainer::performExternalDragDropOfText (const String& text, Component* sourceComp,
  467. std::function<void()> callback)
  468. {
  469. if (text.isEmpty())
  470. return false;
  471. if (auto* peer = getPeerForDragEvent<::Window> (sourceComp))
  472. return XWindowSystem::getInstance()->externalDragTextInit (peer, text, std::move (callback));
  473. // This method must be called in response to a component's mouseDown or mouseDrag event!
  474. jassertfalse;
  475. return false;
  476. }
  477. //==============================================================================
  478. void SystemClipboard::copyTextToClipboard (const String& clipText)
  479. {
  480. XWindowSystem::getInstance()->copyTextToClipboard (clipText);
  481. }
  482. String SystemClipboard::getTextFromClipboard()
  483. {
  484. return XWindowSystem::getInstance()->getTextFromClipboard();
  485. }
  486. //==============================================================================
  487. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  488. {
  489. return XWindowSystem::getInstance()->isKeyCurrentlyDown (keyCode);
  490. }
  491. void LookAndFeel::playAlertSound()
  492. {
  493. std::cout << "\a" << std::flush;
  494. }
  495. //==============================================================================
  496. #if JUCE_MODAL_LOOPS_PERMITTED
  497. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  498. const String& title, const String& message,
  499. Component*)
  500. {
  501. AlertWindow::showMessageBox (iconType, title, message);
  502. }
  503. #endif
  504. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  505. const String& title, const String& message,
  506. Component* associatedComponent,
  507. ModalComponentManager::Callback* callback)
  508. {
  509. AlertWindow::showMessageBoxAsync (iconType, title, message, {}, associatedComponent, callback);
  510. }
  511. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  512. const String& title, const String& message,
  513. Component* associatedComponent,
  514. ModalComponentManager::Callback* callback)
  515. {
  516. return AlertWindow::showOkCancelBox (iconType, title, message, {}, {}, associatedComponent, callback);
  517. }
  518. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  519. const String& title, const String& message,
  520. Component* associatedComponent,
  521. ModalComponentManager::Callback* callback)
  522. {
  523. return AlertWindow::showYesNoCancelBox (iconType, title, message, {}, {}, {},
  524. associatedComponent, callback);
  525. }
  526. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  527. const String& title, const String& message,
  528. Component* associatedComponent,
  529. ModalComponentManager::Callback* callback)
  530. {
  531. return AlertWindow::showOkCancelBox (iconType, title, message, TRANS ("Yes"), TRANS ("No"),
  532. associatedComponent, callback);
  533. }
  534. //==============================================================================
  535. Image juce_createIconForFile (const File&)
  536. {
  537. return {};
  538. }
  539. void juce_LinuxAddRepaintListener (ComponentPeer* peer, Component* dummy)
  540. {
  541. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer<::Window>*> (peer))
  542. linuxPeer->addOpenGLRepaintListener (dummy);
  543. }
  544. void juce_LinuxRemoveRepaintListener (ComponentPeer* peer, Component* dummy)
  545. {
  546. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer<::Window>*> (peer))
  547. linuxPeer->removeOpenGLRepaintListener (dummy);
  548. }
  549. } // namespace juce