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