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.

689 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().getPrimaryDisplay()->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().getDisplayForRect (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().getDisplayForRect (comp->getScreenBounds())->totalArea);
  367. }
  368. void Displays::findDisplays (float masterScale)
  369. {
  370. if (XWindowSystem::getInstance()->getDisplay() != nullptr)
  371. {
  372. displays = XWindowSystem::getInstance()->findDisplays (masterScale);
  373. if (! displays.isEmpty())
  374. updateToLogical();
  375. }
  376. }
  377. bool Desktop::canUseSemiTransparentWindows() noexcept
  378. {
  379. return XWindowSystem::getInstance()->canUseSemiTransparentWindows();
  380. }
  381. static bool screenSaverAllowed = true;
  382. void Desktop::setScreenSaverEnabled (bool isEnabled)
  383. {
  384. if (screenSaverAllowed != isEnabled)
  385. {
  386. screenSaverAllowed = isEnabled;
  387. XWindowSystem::getInstance()->setScreenSaverEnabled (screenSaverAllowed);
  388. }
  389. }
  390. bool Desktop::isScreenSaverEnabled()
  391. {
  392. return screenSaverAllowed;
  393. }
  394. double Desktop::getDefaultMasterScale() { return 1.0; }
  395. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const { return upright; }
  396. void Desktop::allowedOrientationsChanged() {}
  397. //==============================================================================
  398. bool MouseInputSource::SourceList::addSource()
  399. {
  400. if (sources.isEmpty())
  401. {
  402. addSource (0, MouseInputSource::InputSourceType::mouse);
  403. return true;
  404. }
  405. return false;
  406. }
  407. bool MouseInputSource::SourceList::canUseTouch()
  408. {
  409. return false;
  410. }
  411. Point<float> MouseInputSource::getCurrentRawMousePosition()
  412. {
  413. return Desktop::getInstance().getDisplays().physicalToLogical (XWindowSystem::getInstance()->getCurrentMousePosition());
  414. }
  415. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  416. {
  417. XWindowSystem::getInstance()->setMousePosition (Desktop::getInstance().getDisplays().logicalToPhysical (newPosition));
  418. }
  419. //==============================================================================
  420. void* CustomMouseCursorInfo::create() const
  421. {
  422. return XWindowSystem::getInstance()->createCustomMouseCursorInfo (image, hotspot);
  423. }
  424. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool)
  425. {
  426. if (cursorHandle != nullptr)
  427. XWindowSystem::getInstance()->deleteMouseCursor (cursorHandle);
  428. }
  429. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  430. {
  431. return XWindowSystem::getInstance()->createStandardMouseCursor (type);
  432. }
  433. void MouseCursor::showInWindow (ComponentPeer* peer) const
  434. {
  435. if (peer != nullptr)
  436. XWindowSystem::getInstance()->showCursor ((::Window) peer->getNativeHandle(), getHandle());
  437. }
  438. //==============================================================================
  439. template<typename WindowHandleType>
  440. static LinuxComponentPeer<WindowHandleType>* getPeerForDragEvent (Component* sourceComp)
  441. {
  442. if (sourceComp == nullptr)
  443. if (auto* draggingSource = Desktop::getInstance().getDraggingMouseSource (0))
  444. sourceComp = draggingSource->getComponentUnderMouse();
  445. if (sourceComp != nullptr)
  446. if (auto* lp = dynamic_cast<LinuxComponentPeer<::Window>*> (sourceComp->getPeer()))
  447. return lp;
  448. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  449. return nullptr;
  450. }
  451. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles,
  452. Component* sourceComp, std::function<void()> callback)
  453. {
  454. if (files.isEmpty())
  455. return false;
  456. if (auto* peer = getPeerForDragEvent<::Window> (sourceComp))
  457. return XWindowSystem::getInstance()->externalDragFileInit (peer, files, canMoveFiles, std::move (callback));
  458. // This method must be called in response to a component's mouseDown or mouseDrag event!
  459. jassertfalse;
  460. return false;
  461. }
  462. bool DragAndDropContainer::performExternalDragDropOfText (const String& text, Component* sourceComp,
  463. std::function<void()> callback)
  464. {
  465. if (text.isEmpty())
  466. return false;
  467. if (auto* peer = getPeerForDragEvent<::Window> (sourceComp))
  468. return XWindowSystem::getInstance()->externalDragTextInit (peer, text, std::move (callback));
  469. // This method must be called in response to a component's mouseDown or mouseDrag event!
  470. jassertfalse;
  471. return false;
  472. }
  473. //==============================================================================
  474. void SystemClipboard::copyTextToClipboard (const String& clipText)
  475. {
  476. XWindowSystem::getInstance()->copyTextToClipboard (clipText);
  477. }
  478. String SystemClipboard::getTextFromClipboard()
  479. {
  480. return XWindowSystem::getInstance()->getTextFromClipboard();
  481. }
  482. //==============================================================================
  483. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  484. {
  485. return XWindowSystem::getInstance()->isKeyCurrentlyDown (keyCode);
  486. }
  487. void LookAndFeel::playAlertSound()
  488. {
  489. std::cout << "\a" << std::flush;
  490. }
  491. //==============================================================================
  492. #if JUCE_MODAL_LOOPS_PERMITTED
  493. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  494. const String& title, const String& message,
  495. Component*)
  496. {
  497. AlertWindow::showMessageBox (iconType, title, message);
  498. }
  499. #endif
  500. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  501. const String& title, const String& message,
  502. Component* associatedComponent,
  503. ModalComponentManager::Callback* callback)
  504. {
  505. AlertWindow::showMessageBoxAsync (iconType, title, message, {}, associatedComponent, callback);
  506. }
  507. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  508. const String& title, const String& message,
  509. Component* associatedComponent,
  510. ModalComponentManager::Callback* callback)
  511. {
  512. return AlertWindow::showOkCancelBox (iconType, title, message, {}, {}, associatedComponent, callback);
  513. }
  514. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  515. const String& title, const String& message,
  516. Component* associatedComponent,
  517. ModalComponentManager::Callback* callback)
  518. {
  519. return AlertWindow::showYesNoCancelBox (iconType, title, message, {}, {}, {},
  520. associatedComponent, callback);
  521. }
  522. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  523. const String& title, const String& message,
  524. Component* associatedComponent,
  525. ModalComponentManager::Callback* callback)
  526. {
  527. return AlertWindow::showOkCancelBox (iconType, title, message, TRANS ("Yes"), TRANS ("No"),
  528. associatedComponent, callback);
  529. }
  530. //==============================================================================
  531. Image juce_createIconForFile (const File&)
  532. {
  533. return {};
  534. }
  535. void juce_LinuxAddRepaintListener (ComponentPeer* peer, Component* dummy)
  536. {
  537. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer<::Window>*> (peer))
  538. linuxPeer->addOpenGLRepaintListener (dummy);
  539. }
  540. void juce_LinuxRemoveRepaintListener (ComponentPeer* peer, Component* dummy)
  541. {
  542. if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer<::Window>*> (peer))
  543. linuxPeer->removeOpenGLRepaintListener (dummy);
  544. }
  545. } // namespace juce