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.

707 lines
22KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. namespace
  22. {
  23. template <typename Type>
  24. Rectangle<Type> coordsToRectangle (Type x, Type y, Type w, Type h) noexcept
  25. {
  26. #if JUCE_DEBUG
  27. const int maxVal = 0x3fffffff;
  28. jassert ((int) x >= -maxVal && (int) x <= maxVal
  29. && (int) y >= -maxVal && (int) y <= maxVal
  30. && (int) w >= 0 && (int) w <= maxVal
  31. && (int) h >= 0 && (int) h <= maxVal);
  32. #endif
  33. return { x, y, w, h };
  34. }
  35. }
  36. //==============================================================================
  37. LowLevelGraphicsContext::LowLevelGraphicsContext() {}
  38. LowLevelGraphicsContext::~LowLevelGraphicsContext() {}
  39. //==============================================================================
  40. Graphics::Graphics (const Image& imageToDrawOnto)
  41. : context (*imageToDrawOnto.createLowLevelContext()),
  42. contextToDelete (&context)
  43. {
  44. jassert (imageToDrawOnto.isValid()); // Can't draw into a null image!
  45. }
  46. Graphics::Graphics (LowLevelGraphicsContext& internalContext) noexcept
  47. : context (internalContext)
  48. {
  49. }
  50. Graphics::~Graphics()
  51. {
  52. }
  53. //==============================================================================
  54. void Graphics::resetToDefaultState()
  55. {
  56. saveStateIfPending();
  57. context.setFill (FillType());
  58. context.setFont (Font());
  59. context.setInterpolationQuality (Graphics::mediumResamplingQuality);
  60. }
  61. bool Graphics::isVectorDevice() const
  62. {
  63. return context.isVectorDevice();
  64. }
  65. bool Graphics::reduceClipRegion (Rectangle<int> area)
  66. {
  67. saveStateIfPending();
  68. return context.clipToRectangle (area);
  69. }
  70. bool Graphics::reduceClipRegion (int x, int y, int w, int h)
  71. {
  72. return reduceClipRegion (coordsToRectangle (x, y, w, h));
  73. }
  74. bool Graphics::reduceClipRegion (const RectangleList<int>& clipRegion)
  75. {
  76. saveStateIfPending();
  77. return context.clipToRectangleList (clipRegion);
  78. }
  79. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  80. {
  81. saveStateIfPending();
  82. context.clipToPath (path, transform);
  83. return ! context.isClipEmpty();
  84. }
  85. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  86. {
  87. saveStateIfPending();
  88. context.clipToImageAlpha (image, transform);
  89. return ! context.isClipEmpty();
  90. }
  91. void Graphics::excludeClipRegion (Rectangle<int> rectangleToExclude)
  92. {
  93. saveStateIfPending();
  94. context.excludeClipRectangle (rectangleToExclude);
  95. }
  96. bool Graphics::isClipEmpty() const
  97. {
  98. return context.isClipEmpty();
  99. }
  100. Rectangle<int> Graphics::getClipBounds() const
  101. {
  102. return context.getClipBounds();
  103. }
  104. void Graphics::saveState()
  105. {
  106. saveStateIfPending();
  107. saveStatePending = true;
  108. }
  109. void Graphics::restoreState()
  110. {
  111. if (saveStatePending)
  112. saveStatePending = false;
  113. else
  114. context.restoreState();
  115. }
  116. void Graphics::saveStateIfPending()
  117. {
  118. if (saveStatePending)
  119. {
  120. saveStatePending = false;
  121. context.saveState();
  122. }
  123. }
  124. void Graphics::setOrigin (Point<int> newOrigin)
  125. {
  126. saveStateIfPending();
  127. context.setOrigin (newOrigin);
  128. }
  129. void Graphics::setOrigin (int x, int y)
  130. {
  131. setOrigin ({ x, y });
  132. }
  133. void Graphics::addTransform (const AffineTransform& transform)
  134. {
  135. saveStateIfPending();
  136. context.addTransform (transform);
  137. }
  138. bool Graphics::clipRegionIntersects (Rectangle<int> area) const
  139. {
  140. return context.clipRegionIntersects (area);
  141. }
  142. void Graphics::beginTransparencyLayer (float layerOpacity)
  143. {
  144. saveStateIfPending();
  145. context.beginTransparencyLayer (layerOpacity);
  146. }
  147. void Graphics::endTransparencyLayer()
  148. {
  149. context.endTransparencyLayer();
  150. }
  151. //==============================================================================
  152. void Graphics::setColour (Colour newColour)
  153. {
  154. saveStateIfPending();
  155. context.setFill (newColour);
  156. }
  157. void Graphics::setOpacity (float newOpacity)
  158. {
  159. saveStateIfPending();
  160. context.setOpacity (newOpacity);
  161. }
  162. void Graphics::setGradientFill (const ColourGradient& gradient)
  163. {
  164. setFillType (gradient);
  165. }
  166. void Graphics::setGradientFill (ColourGradient&& gradient)
  167. {
  168. setFillType (std::move (gradient));
  169. }
  170. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  171. {
  172. saveStateIfPending();
  173. context.setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  174. context.setOpacity (opacity);
  175. }
  176. void Graphics::setFillType (const FillType& newFill)
  177. {
  178. saveStateIfPending();
  179. context.setFill (newFill);
  180. }
  181. //==============================================================================
  182. void Graphics::setFont (const Font& newFont)
  183. {
  184. saveStateIfPending();
  185. context.setFont (newFont);
  186. }
  187. void Graphics::setFont (const float newFontHeight)
  188. {
  189. setFont (context.getFont().withHeight (newFontHeight));
  190. }
  191. Font Graphics::getCurrentFont() const
  192. {
  193. return context.getFont();
  194. }
  195. //==============================================================================
  196. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY,
  197. Justification justification) const
  198. {
  199. if (text.isNotEmpty())
  200. {
  201. // Don't pass any vertical placement flags to this method - they'll be ignored.
  202. jassert (justification.getOnlyVerticalFlags() == 0);
  203. auto flags = justification.getOnlyHorizontalFlags();
  204. if (flags == Justification::right && startX < context.getClipBounds().getX())
  205. return;
  206. if (flags == Justification::left && startX > context.getClipBounds().getRight())
  207. return;
  208. GlyphArrangement arr;
  209. arr.addLineOfText (context.getFont(), text, (float) startX, (float) baselineY);
  210. if (flags != Justification::left)
  211. {
  212. auto w = arr.getBoundingBox (0, -1, true).getWidth();
  213. if ((flags & (Justification::horizontallyCentred | Justification::horizontallyJustified)) != 0)
  214. w /= 2.0f;
  215. arr.draw (*this, AffineTransform::translation (-w, 0));
  216. }
  217. else
  218. {
  219. arr.draw (*this);
  220. }
  221. }
  222. }
  223. void Graphics::drawMultiLineText (const String& text, const int startX,
  224. const int baselineY, const int maximumLineWidth,
  225. Justification justification) const
  226. {
  227. if (text.isNotEmpty()
  228. && startX < context.getClipBounds().getRight())
  229. {
  230. GlyphArrangement arr;
  231. arr.addJustifiedText (context.getFont(), text,
  232. (float) startX, (float) baselineY, (float) maximumLineWidth,
  233. justification);
  234. arr.draw (*this);
  235. }
  236. }
  237. void Graphics::drawText (const String& text, Rectangle<float> area,
  238. Justification justificationType, bool useEllipsesIfTooBig) const
  239. {
  240. if (text.isNotEmpty() && context.clipRegionIntersects (area.getSmallestIntegerContainer()))
  241. {
  242. GlyphArrangement arr;
  243. arr.addCurtailedLineOfText (context.getFont(), text, 0.0f, 0.0f,
  244. area.getWidth(), useEllipsesIfTooBig);
  245. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  246. area.getX(), area.getY(), area.getWidth(), area.getHeight(),
  247. justificationType);
  248. arr.draw (*this);
  249. }
  250. }
  251. void Graphics::drawText (const String& text, Rectangle<int> area,
  252. Justification justificationType, bool useEllipsesIfTooBig) const
  253. {
  254. drawText (text, area.toFloat(), justificationType, useEllipsesIfTooBig);
  255. }
  256. void Graphics::drawText (const String& text, int x, int y, int width, int height,
  257. Justification justificationType, const bool useEllipsesIfTooBig) const
  258. {
  259. drawText (text, coordsToRectangle (x, y, width, height), justificationType, useEllipsesIfTooBig);
  260. }
  261. void Graphics::drawFittedText (const String& text, Rectangle<int> area,
  262. Justification justification,
  263. const int maximumNumberOfLines,
  264. const float minimumHorizontalScale) const
  265. {
  266. if (text.isNotEmpty() && (! area.isEmpty()) && context.clipRegionIntersects (area))
  267. {
  268. GlyphArrangement arr;
  269. arr.addFittedText (context.getFont(), text,
  270. (float) area.getX(), (float) area.getY(),
  271. (float) area.getWidth(), (float) area.getHeight(),
  272. justification,
  273. maximumNumberOfLines,
  274. minimumHorizontalScale);
  275. arr.draw (*this);
  276. }
  277. }
  278. void Graphics::drawFittedText (const String& text, int x, int y, int width, int height,
  279. Justification justification,
  280. const int maximumNumberOfLines,
  281. const float minimumHorizontalScale) const
  282. {
  283. drawFittedText (text, coordsToRectangle (x, y, width, height),
  284. justification, maximumNumberOfLines, minimumHorizontalScale);
  285. }
  286. //==============================================================================
  287. void Graphics::fillRect (Rectangle<int> r) const
  288. {
  289. context.fillRect (r, false);
  290. }
  291. void Graphics::fillRect (Rectangle<float> r) const
  292. {
  293. context.fillRect (r);
  294. }
  295. void Graphics::fillRect (int x, int y, int width, int height) const
  296. {
  297. context.fillRect (coordsToRectangle (x, y, width, height), false);
  298. }
  299. void Graphics::fillRect (float x, float y, float width, float height) const
  300. {
  301. fillRect (coordsToRectangle (x, y, width, height));
  302. }
  303. void Graphics::fillRectList (const RectangleList<float>& rectangles) const
  304. {
  305. context.fillRectList (rectangles);
  306. }
  307. void Graphics::fillRectList (const RectangleList<int>& rects) const
  308. {
  309. for (auto& r : rects)
  310. context.fillRect (r, false);
  311. }
  312. void Graphics::fillAll() const
  313. {
  314. fillRect (context.getClipBounds());
  315. }
  316. void Graphics::fillAll (Colour colourToUse) const
  317. {
  318. if (! colourToUse.isTransparent())
  319. {
  320. auto clip = context.getClipBounds();
  321. context.saveState();
  322. context.setFill (colourToUse);
  323. context.fillRect (clip, false);
  324. context.restoreState();
  325. }
  326. }
  327. //==============================================================================
  328. void Graphics::fillPath (const Path& path) const
  329. {
  330. if (! (context.isClipEmpty() || path.isEmpty()))
  331. context.fillPath (path, AffineTransform());
  332. }
  333. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  334. {
  335. if (! (context.isClipEmpty() || path.isEmpty()))
  336. context.fillPath (path, transform);
  337. }
  338. void Graphics::strokePath (const Path& path,
  339. const PathStrokeType& strokeType,
  340. const AffineTransform& transform) const
  341. {
  342. Path stroke;
  343. strokeType.createStrokedPath (stroke, path, transform, context.getPhysicalPixelScaleFactor());
  344. fillPath (stroke);
  345. }
  346. //==============================================================================
  347. void Graphics::drawRect (float x, float y, float width, float height, float lineThickness) const
  348. {
  349. drawRect (coordsToRectangle (x, y, width, height), lineThickness);
  350. }
  351. void Graphics::drawRect (int x, int y, int width, int height, int lineThickness) const
  352. {
  353. drawRect (coordsToRectangle (x, y, width, height), lineThickness);
  354. }
  355. void Graphics::drawRect (Rectangle<int> r, int lineThickness) const
  356. {
  357. drawRect (r.toFloat(), (float) lineThickness);
  358. }
  359. void Graphics::drawRect (Rectangle<float> r, const float lineThickness) const
  360. {
  361. jassert (r.getWidth() >= 0.0f && r.getHeight() >= 0.0f);
  362. RectangleList<float> rects;
  363. rects.addWithoutMerging (r.removeFromTop (lineThickness));
  364. rects.addWithoutMerging (r.removeFromBottom (lineThickness));
  365. rects.addWithoutMerging (r.removeFromLeft (lineThickness));
  366. rects.addWithoutMerging (r.removeFromRight (lineThickness));
  367. context.fillRectList (rects);
  368. }
  369. //==============================================================================
  370. void Graphics::fillEllipse (Rectangle<float> area) const
  371. {
  372. Path p;
  373. p.addEllipse (area);
  374. fillPath (p);
  375. }
  376. void Graphics::fillEllipse (float x, float y, float w, float h) const
  377. {
  378. fillEllipse (coordsToRectangle (x, y, w, h));
  379. }
  380. void Graphics::drawEllipse (float x, float y, float width, float height, float lineThickness) const
  381. {
  382. drawEllipse (coordsToRectangle (x, y, width, height), lineThickness);
  383. }
  384. void Graphics::drawEllipse (Rectangle<float> area, float lineThickness) const
  385. {
  386. Path p;
  387. if (area.getWidth() == area.getHeight())
  388. {
  389. // For a circle, we can avoid having to generate a stroke
  390. p.addEllipse (area.expanded (lineThickness * 0.5f));
  391. p.addEllipse (area.reduced (lineThickness * 0.5f));
  392. p.setUsingNonZeroWinding (false);
  393. fillPath (p);
  394. }
  395. else
  396. {
  397. p.addEllipse (area);
  398. strokePath (p, PathStrokeType (lineThickness));
  399. }
  400. }
  401. void Graphics::fillRoundedRectangle (float x, float y, float width, float height, float cornerSize) const
  402. {
  403. fillRoundedRectangle (coordsToRectangle (x, y, width, height), cornerSize);
  404. }
  405. void Graphics::fillRoundedRectangle (Rectangle<float> r, const float cornerSize) const
  406. {
  407. Path p;
  408. p.addRoundedRectangle (r, cornerSize);
  409. fillPath (p);
  410. }
  411. void Graphics::drawRoundedRectangle (float x, float y, float width, float height,
  412. float cornerSize, float lineThickness) const
  413. {
  414. drawRoundedRectangle (coordsToRectangle (x, y, width, height), cornerSize, lineThickness);
  415. }
  416. void Graphics::drawRoundedRectangle (Rectangle<float> r, float cornerSize, float lineThickness) const
  417. {
  418. Path p;
  419. p.addRoundedRectangle (r, cornerSize);
  420. strokePath (p, PathStrokeType (lineThickness));
  421. }
  422. void Graphics::drawArrow (Line<float> line, float lineThickness, float arrowheadWidth, float arrowheadLength) const
  423. {
  424. Path p;
  425. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  426. fillPath (p);
  427. }
  428. void Graphics::fillCheckerBoard (Rectangle<float> area, float checkWidth, float checkHeight,
  429. Colour colour1, Colour colour2) const
  430. {
  431. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  432. if (checkWidth > 0 && checkHeight > 0)
  433. {
  434. context.saveState();
  435. if (colour1 == colour2)
  436. {
  437. context.setFill (colour1);
  438. context.fillRect (area);
  439. }
  440. else
  441. {
  442. auto clipped = context.getClipBounds().getIntersection (area.getSmallestIntegerContainer());
  443. if (! clipped.isEmpty())
  444. {
  445. const int checkNumX = (int) ((clipped.getX() - area.getX()) / checkWidth);
  446. const int checkNumY = (int) ((clipped.getY() - area.getY()) / checkHeight);
  447. const float startX = area.getX() + checkNumX * checkWidth;
  448. const float startY = area.getY() + checkNumY * checkHeight;
  449. const float right = (float) clipped.getRight();
  450. const float bottom = (float) clipped.getBottom();
  451. for (int i = 0; i < 2; ++i)
  452. {
  453. int cy = i;
  454. RectangleList<float> checks;
  455. for (float y = startY; y < bottom; y += checkHeight)
  456. for (float x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2.0f)
  457. checks.addWithoutMerging ({ x, y, checkWidth, checkHeight });
  458. checks.clipTo (area);
  459. context.setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  460. context.fillRectList (checks);
  461. }
  462. }
  463. }
  464. context.restoreState();
  465. }
  466. }
  467. //==============================================================================
  468. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  469. {
  470. if (top < bottom)
  471. context.fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  472. }
  473. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  474. {
  475. if (left < right)
  476. context.fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  477. }
  478. void Graphics::drawLine (Line<float> line) const
  479. {
  480. context.drawLine (line);
  481. }
  482. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  483. {
  484. context.drawLine (Line<float> (x1, y1, x2, y2));
  485. }
  486. void Graphics::drawLine (float x1, float y1, float x2, float y2, float lineThickness) const
  487. {
  488. drawLine (Line<float> (x1, y1, x2, y2), lineThickness);
  489. }
  490. void Graphics::drawLine (Line<float> line, const float lineThickness) const
  491. {
  492. Path p;
  493. p.addLineSegment (line, lineThickness);
  494. fillPath (p);
  495. }
  496. void Graphics::drawDashedLine (Line<float> line, const float* dashLengths,
  497. int numDashLengths, float lineThickness, int n) const
  498. {
  499. jassert (n >= 0 && n < numDashLengths); // your start index must be valid!
  500. const Point<double> delta ((line.getEnd() - line.getStart()).toDouble());
  501. const double totalLen = delta.getDistanceFromOrigin();
  502. if (totalLen >= 0.1)
  503. {
  504. const double onePixAlpha = 1.0 / totalLen;
  505. for (double alpha = 0.0; alpha < 1.0;)
  506. {
  507. jassert (dashLengths[n] > 0); // can't have zero-length dashes!
  508. const double lastAlpha = alpha;
  509. alpha += dashLengths [n] * onePixAlpha;
  510. n = (n + 1) % numDashLengths;
  511. if ((n & 1) != 0)
  512. {
  513. const Line<float> segment (line.getStart() + (delta * lastAlpha).toFloat(),
  514. line.getStart() + (delta * jmin (1.0, alpha)).toFloat());
  515. if (lineThickness != 1.0f)
  516. drawLine (segment, lineThickness);
  517. else
  518. context.drawLine (segment);
  519. }
  520. }
  521. }
  522. }
  523. //==============================================================================
  524. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  525. {
  526. saveStateIfPending();
  527. context.setInterpolationQuality (newQuality);
  528. }
  529. //==============================================================================
  530. void Graphics::drawImageAt (const Image& imageToDraw, int x, int y, bool fillAlphaChannel) const
  531. {
  532. drawImageTransformed (imageToDraw,
  533. AffineTransform::translation ((float) x, (float) y),
  534. fillAlphaChannel);
  535. }
  536. void Graphics::drawImage (const Image& imageToDraw, Rectangle<float> targetArea,
  537. RectanglePlacement placementWithinTarget, bool fillAlphaChannelWithCurrentBrush) const
  538. {
  539. if (imageToDraw.isValid())
  540. drawImageTransformed (imageToDraw,
  541. placementWithinTarget.getTransformToFit (imageToDraw.getBounds().toFloat(), targetArea),
  542. fillAlphaChannelWithCurrentBrush);
  543. }
  544. void Graphics::drawImageWithin (const Image& imageToDraw, int dx, int dy, int dw, int dh,
  545. RectanglePlacement placementWithinTarget, bool fillAlphaChannelWithCurrentBrush) const
  546. {
  547. drawImage (imageToDraw, coordsToRectangle (dx, dy, dw, dh).toFloat(),
  548. placementWithinTarget, fillAlphaChannelWithCurrentBrush);
  549. }
  550. void Graphics::drawImage (const Image& imageToDraw,
  551. int dx, int dy, int dw, int dh,
  552. int sx, int sy, int sw, int sh,
  553. const bool fillAlphaChannelWithCurrentBrush) const
  554. {
  555. if (imageToDraw.isValid() && context.clipRegionIntersects (coordsToRectangle (dx, dy, dw, dh)))
  556. drawImageTransformed (imageToDraw.getClippedImage (coordsToRectangle (sx, sy, sw, sh)),
  557. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  558. .translated ((float) dx, (float) dy),
  559. fillAlphaChannelWithCurrentBrush);
  560. }
  561. void Graphics::drawImageTransformed (const Image& imageToDraw,
  562. const AffineTransform& transform,
  563. const bool fillAlphaChannelWithCurrentBrush) const
  564. {
  565. if (imageToDraw.isValid() && ! context.isClipEmpty())
  566. {
  567. if (fillAlphaChannelWithCurrentBrush)
  568. {
  569. context.saveState();
  570. context.clipToImageAlpha (imageToDraw, transform);
  571. fillAll();
  572. context.restoreState();
  573. }
  574. else
  575. {
  576. context.drawImage (imageToDraw, transform);
  577. }
  578. }
  579. }
  580. //==============================================================================
  581. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g) : context (g)
  582. {
  583. context.saveState();
  584. }
  585. Graphics::ScopedSaveState::~ScopedSaveState()
  586. {
  587. context.restoreState();
  588. }
  589. } // namespace juce