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.

1376 lines
48KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. class SVGState
  18. {
  19. public:
  20. //==============================================================================
  21. explicit SVGState (const XmlElement* const topLevel)
  22. : topLevelXml (topLevel, nullptr),
  23. elementX (0), elementY (0),
  24. width (512), height (512),
  25. viewBoxW (0), viewBoxH (0)
  26. {
  27. }
  28. struct XmlPath
  29. {
  30. XmlPath (const XmlElement* e, const XmlPath* p) noexcept : xml (e), parent (p) {}
  31. const XmlElement& operator*() const noexcept { jassert (xml != nullptr); return *xml; }
  32. const XmlElement* operator->() const noexcept { return xml; }
  33. XmlPath getChild (const XmlElement* e) const noexcept { return XmlPath (e, this); }
  34. const XmlElement* xml;
  35. const XmlPath* parent;
  36. };
  37. //==============================================================================
  38. Drawable* parseSVGElement (const XmlPath& xml)
  39. {
  40. if (! xml->hasTagNameIgnoringNamespace ("svg"))
  41. return nullptr;
  42. DrawableComposite* const drawable = new DrawableComposite();
  43. setCommonAttributes (*drawable, xml);
  44. SVGState newState (*this);
  45. if (xml->hasAttribute ("transform"))
  46. newState.addTransform (xml);
  47. newState.elementX = getCoordLength (xml->getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  48. newState.elementY = getCoordLength (xml->getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  49. newState.width = getCoordLength (xml->getStringAttribute ("width", String (newState.width)), viewBoxW);
  50. newState.height = getCoordLength (xml->getStringAttribute ("height", String (newState.height)), viewBoxH);
  51. if (newState.width <= 0) newState.width = 100;
  52. if (newState.height <= 0) newState.height = 100;
  53. Point<float> viewboxXY;
  54. if (xml->hasAttribute ("viewBox"))
  55. {
  56. const String viewBoxAtt (xml->getStringAttribute ("viewBox"));
  57. String::CharPointerType viewParams (viewBoxAtt.getCharPointer());
  58. Point<float> vwh;
  59. if (parseCoords (viewParams, viewboxXY, true)
  60. && parseCoords (viewParams, vwh, true)
  61. && vwh.x > 0
  62. && vwh.y > 0)
  63. {
  64. newState.viewBoxW = vwh.x;
  65. newState.viewBoxH = vwh.y;
  66. const int placementFlags = parsePlacementFlags (xml->getStringAttribute ("preserveAspectRatio").trim());
  67. if (placementFlags != 0)
  68. newState.transform = RectanglePlacement (placementFlags)
  69. .getTransformToFit (Rectangle<float> (viewboxXY.x, viewboxXY.y, vwh.x, vwh.y),
  70. Rectangle<float> (newState.width, newState.height))
  71. .followedBy (newState.transform);
  72. }
  73. }
  74. else
  75. {
  76. if (viewBoxW == 0) newState.viewBoxW = newState.width;
  77. if (viewBoxH == 0) newState.viewBoxH = newState.height;
  78. }
  79. newState.parseSubElements (xml, *drawable);
  80. drawable->setContentArea (RelativeRectangle (RelativeCoordinate (viewboxXY.x),
  81. RelativeCoordinate (viewboxXY.x + newState.viewBoxW),
  82. RelativeCoordinate (viewboxXY.y),
  83. RelativeCoordinate (viewboxXY.y + newState.viewBoxH)));
  84. drawable->resetBoundingBoxToContentArea();
  85. return drawable;
  86. }
  87. //==============================================================================
  88. void parsePathString (Path& path, const String& pathString) const
  89. {
  90. String::CharPointerType d (pathString.getCharPointer().findEndOfWhitespace());
  91. Point<float> subpathStart, last, last2, p1, p2, p3;
  92. juce_wchar lastCommandChar = 0;
  93. bool isRelative = true;
  94. bool carryOn = true;
  95. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  96. while (! d.isEmpty())
  97. {
  98. if (validCommandChars.indexOf (*d) >= 0)
  99. {
  100. lastCommandChar = d.getAndAdvance();
  101. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  102. }
  103. switch (lastCommandChar)
  104. {
  105. case 'M':
  106. case 'm':
  107. case 'L':
  108. case 'l':
  109. if (parseCoordsOrSkip (d, p1, false))
  110. {
  111. if (isRelative)
  112. p1 += last;
  113. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  114. {
  115. subpathStart = p1;
  116. path.startNewSubPath (p1);
  117. lastCommandChar = 'l';
  118. }
  119. else
  120. path.lineTo (p1);
  121. last2 = last;
  122. last = p1;
  123. }
  124. break;
  125. case 'H':
  126. case 'h':
  127. if (parseCoord (d, p1.x, false, true))
  128. {
  129. if (isRelative)
  130. p1.x += last.x;
  131. path.lineTo (p1.x, last.y);
  132. last2.x = last.x;
  133. last.x = p1.x;
  134. }
  135. else
  136. {
  137. ++d;
  138. }
  139. break;
  140. case 'V':
  141. case 'v':
  142. if (parseCoord (d, p1.y, false, false))
  143. {
  144. if (isRelative)
  145. p1.y += last.y;
  146. path.lineTo (last.x, p1.y);
  147. last2.y = last.y;
  148. last.y = p1.y;
  149. }
  150. else
  151. {
  152. ++d;
  153. }
  154. break;
  155. case 'C':
  156. case 'c':
  157. if (parseCoordsOrSkip (d, p1, false)
  158. && parseCoordsOrSkip (d, p2, false)
  159. && parseCoordsOrSkip (d, p3, false))
  160. {
  161. if (isRelative)
  162. {
  163. p1 += last;
  164. p2 += last;
  165. p3 += last;
  166. }
  167. path.cubicTo (p1, p2, p3);
  168. last2 = p2;
  169. last = p3;
  170. }
  171. break;
  172. case 'S':
  173. case 's':
  174. if (parseCoordsOrSkip (d, p1, false)
  175. && parseCoordsOrSkip (d, p3, false))
  176. {
  177. if (isRelative)
  178. {
  179. p1 += last;
  180. p3 += last;
  181. }
  182. p2 = last + (last - last2);
  183. path.cubicTo (p2, p1, p3);
  184. last2 = p1;
  185. last = p3;
  186. }
  187. break;
  188. case 'Q':
  189. case 'q':
  190. if (parseCoordsOrSkip (d, p1, false)
  191. && parseCoordsOrSkip (d, p2, false))
  192. {
  193. if (isRelative)
  194. {
  195. p1 += last;
  196. p2 += last;
  197. }
  198. path.quadraticTo (p1, p2);
  199. last2 = p1;
  200. last = p2;
  201. }
  202. break;
  203. case 'T':
  204. case 't':
  205. if (parseCoordsOrSkip (d, p1, false))
  206. {
  207. if (isRelative)
  208. p1 += last;
  209. p2 = last + (last - last2);
  210. path.quadraticTo (p2, p1);
  211. last2 = p2;
  212. last = p1;
  213. }
  214. break;
  215. case 'A':
  216. case 'a':
  217. if (parseCoordsOrSkip (d, p1, false))
  218. {
  219. String num;
  220. if (parseNextNumber (d, num, false))
  221. {
  222. const float angle = degreesToRadians (num.getFloatValue());
  223. if (parseNextNumber (d, num, false))
  224. {
  225. const bool largeArc = num.getIntValue() != 0;
  226. if (parseNextNumber (d, num, false))
  227. {
  228. const bool sweep = num.getIntValue() != 0;
  229. if (parseCoordsOrSkip (d, p2, false))
  230. {
  231. if (isRelative)
  232. p2 += last;
  233. if (last != p2)
  234. {
  235. double centreX, centreY, startAngle, deltaAngle;
  236. double rx = p1.x, ry = p1.y;
  237. endpointToCentreParameters (last.x, last.y, p2.x, p2.y,
  238. angle, largeArc, sweep,
  239. rx, ry, centreX, centreY,
  240. startAngle, deltaAngle);
  241. path.addCentredArc ((float) centreX, (float) centreY,
  242. (float) rx, (float) ry,
  243. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  244. false);
  245. path.lineTo (p2);
  246. }
  247. last2 = last;
  248. last = p2;
  249. }
  250. }
  251. }
  252. }
  253. }
  254. break;
  255. case 'Z':
  256. case 'z':
  257. path.closeSubPath();
  258. last = last2 = subpathStart;
  259. d = d.findEndOfWhitespace();
  260. lastCommandChar = 'M';
  261. break;
  262. default:
  263. carryOn = false;
  264. break;
  265. }
  266. if (! carryOn)
  267. break;
  268. }
  269. // paths that finish back at their start position often seem to be
  270. // left without a 'z', so need to be closed explicitly..
  271. if (path.getCurrentPosition() == subpathStart)
  272. path.closeSubPath();
  273. }
  274. private:
  275. //==============================================================================
  276. const XmlPath topLevelXml;
  277. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  278. AffineTransform transform;
  279. String cssStyleText;
  280. static void setCommonAttributes (Drawable& d, const XmlPath& xml)
  281. {
  282. String compID (xml->getStringAttribute ("id"));
  283. d.setName (compID);
  284. d.setComponentID (compID);
  285. if (xml->getStringAttribute ("display") == "none")
  286. d.setVisible (false);
  287. }
  288. //==============================================================================
  289. void parseSubElements (const XmlPath& xml, DrawableComposite& parentDrawable)
  290. {
  291. forEachXmlChildElement (*xml, e)
  292. parentDrawable.addAndMakeVisible (parseSubElement (xml.getChild (e)));
  293. }
  294. Drawable* parseSubElement (const XmlPath& xml)
  295. {
  296. const String tag (xml->getTagNameWithoutNamespace());
  297. if (tag == "g") return parseGroupElement (xml);
  298. if (tag == "svg") return parseSVGElement (xml);
  299. if (tag == "path") return parsePath (xml);
  300. if (tag == "rect") return parseRect (xml);
  301. if (tag == "circle") return parseCircle (xml);
  302. if (tag == "ellipse") return parseEllipse (xml);
  303. if (tag == "line") return parseLine (xml);
  304. if (tag == "polyline") return parsePolygon (xml, true);
  305. if (tag == "polygon") return parsePolygon (xml, false);
  306. if (tag == "text") return parseText (xml, true);
  307. if (tag == "switch") return parseSwitch (xml);
  308. if (tag == "a") return parseLinkElement (xml);
  309. if (tag == "style") parseCSSStyle (xml);
  310. return nullptr;
  311. }
  312. DrawableComposite* parseSwitch (const XmlPath& xml)
  313. {
  314. if (const XmlElement* const group = xml->getChildByName ("g"))
  315. return parseGroupElement (xml.getChild (group));
  316. return nullptr;
  317. }
  318. DrawableComposite* parseGroupElement (const XmlPath& xml)
  319. {
  320. DrawableComposite* const drawable = new DrawableComposite();
  321. setCommonAttributes (*drawable, xml);
  322. if (xml->hasAttribute ("transform"))
  323. {
  324. SVGState newState (*this);
  325. newState.addTransform (xml);
  326. newState.parseSubElements (xml, *drawable);
  327. }
  328. else
  329. {
  330. parseSubElements (xml, *drawable);
  331. }
  332. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  333. return drawable;
  334. }
  335. DrawableComposite* parseLinkElement (const XmlPath& xml)
  336. {
  337. return parseGroupElement (xml); // TODO: support for making this clickable
  338. }
  339. //==============================================================================
  340. Drawable* parsePath (const XmlPath& xml) const
  341. {
  342. Path path;
  343. parsePathString (path, xml->getStringAttribute ("d"));
  344. if (getStyleAttribute (xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  345. path.setUsingNonZeroWinding (false);
  346. return parseShape (xml, path);
  347. }
  348. Drawable* parseRect (const XmlPath& xml) const
  349. {
  350. Path rect;
  351. const bool hasRX = xml->hasAttribute ("rx");
  352. const bool hasRY = xml->hasAttribute ("ry");
  353. if (hasRX || hasRY)
  354. {
  355. float rx = getCoordLength (xml, "rx", viewBoxW);
  356. float ry = getCoordLength (xml, "ry", viewBoxH);
  357. if (! hasRX)
  358. rx = ry;
  359. else if (! hasRY)
  360. ry = rx;
  361. rect.addRoundedRectangle (getCoordLength (xml, "x", viewBoxW),
  362. getCoordLength (xml, "y", viewBoxH),
  363. getCoordLength (xml, "width", viewBoxW),
  364. getCoordLength (xml, "height", viewBoxH),
  365. rx, ry);
  366. }
  367. else
  368. {
  369. rect.addRectangle (getCoordLength (xml, "x", viewBoxW),
  370. getCoordLength (xml, "y", viewBoxH),
  371. getCoordLength (xml, "width", viewBoxW),
  372. getCoordLength (xml, "height", viewBoxH));
  373. }
  374. return parseShape (xml, rect);
  375. }
  376. Drawable* parseCircle (const XmlPath& xml) const
  377. {
  378. Path circle;
  379. const float cx = getCoordLength (xml, "cx", viewBoxW);
  380. const float cy = getCoordLength (xml, "cy", viewBoxH);
  381. const float radius = getCoordLength (xml, "r", viewBoxW);
  382. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  383. return parseShape (xml, circle);
  384. }
  385. Drawable* parseEllipse (const XmlPath& xml) const
  386. {
  387. Path ellipse;
  388. const float cx = getCoordLength (xml, "cx", viewBoxW);
  389. const float cy = getCoordLength (xml, "cy", viewBoxH);
  390. const float radiusX = getCoordLength (xml, "rx", viewBoxW);
  391. const float radiusY = getCoordLength (xml, "ry", viewBoxH);
  392. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  393. return parseShape (xml, ellipse);
  394. }
  395. Drawable* parseLine (const XmlPath& xml) const
  396. {
  397. Path line;
  398. const float x1 = getCoordLength (xml, "x1", viewBoxW);
  399. const float y1 = getCoordLength (xml, "y1", viewBoxH);
  400. const float x2 = getCoordLength (xml, "x2", viewBoxW);
  401. const float y2 = getCoordLength (xml, "y2", viewBoxH);
  402. line.startNewSubPath (x1, y1);
  403. line.lineTo (x2, y2);
  404. return parseShape (xml, line);
  405. }
  406. Drawable* parsePolygon (const XmlPath& xml, const bool isPolyline) const
  407. {
  408. const String pointsAtt (xml->getStringAttribute ("points"));
  409. String::CharPointerType points (pointsAtt.getCharPointer());
  410. Path path;
  411. Point<float> p;
  412. if (parseCoords (points, p, true))
  413. {
  414. Point<float> first (p), last;
  415. path.startNewSubPath (first);
  416. while (parseCoords (points, p, true))
  417. {
  418. last = p;
  419. path.lineTo (p);
  420. }
  421. if ((! isPolyline) || first == last)
  422. path.closeSubPath();
  423. }
  424. return parseShape (xml, path);
  425. }
  426. //==============================================================================
  427. Drawable* parseShape (const XmlPath& xml, Path& path,
  428. const bool shouldParseTransform = true) const
  429. {
  430. if (shouldParseTransform && xml->hasAttribute ("transform"))
  431. {
  432. SVGState newState (*this);
  433. newState.addTransform (xml);
  434. return newState.parseShape (xml, path, false);
  435. }
  436. DrawablePath* dp = new DrawablePath();
  437. setCommonAttributes (*dp, xml);
  438. dp->setFill (Colours::transparentBlack);
  439. path.applyTransform (transform);
  440. dp->setPath (path);
  441. dp->setFill (getPathFillType (path,
  442. getStyleAttribute (xml, "fill"),
  443. getStyleAttribute (xml, "fill-opacity"),
  444. getStyleAttribute (xml, "opacity"),
  445. pathContainsClosedSubPath (path) ? Colours::black
  446. : Colours::transparentBlack));
  447. const String strokeType (getStyleAttribute (xml, "stroke"));
  448. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  449. {
  450. dp->setStrokeFill (getPathFillType (path, strokeType,
  451. getStyleAttribute (xml, "stroke-opacity"),
  452. getStyleAttribute (xml, "opacity"),
  453. Colours::transparentBlack));
  454. dp->setStrokeType (getStrokeFor (xml));
  455. }
  456. return dp;
  457. }
  458. static bool pathContainsClosedSubPath (const Path& path) noexcept
  459. {
  460. for (Path::Iterator iter (path); iter.next();)
  461. if (iter.elementType == Path::Iterator::closePath)
  462. return true;
  463. return false;
  464. }
  465. struct SetGradientStopsOp
  466. {
  467. const SVGState* state;
  468. ColourGradient* gradient;
  469. void operator() (const XmlPath& xml)
  470. {
  471. state->addGradientStopsIn (*gradient, xml);
  472. }
  473. };
  474. void addGradientStopsIn (ColourGradient& cg, const XmlPath& fillXml) const
  475. {
  476. if (fillXml.xml != nullptr)
  477. {
  478. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  479. {
  480. int index = 0;
  481. Colour col (parseColour (getStyleAttribute (fillXml.getChild (e), "stop-color"), index, Colours::black));
  482. const String opacity (getStyleAttribute (fillXml.getChild (e), "stop-opacity", "1"));
  483. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  484. double offset = e->getDoubleAttribute ("offset");
  485. if (e->getStringAttribute ("offset").containsChar ('%'))
  486. offset *= 0.01;
  487. cg.addColour (jlimit (0.0, 1.0, offset), col);
  488. }
  489. }
  490. }
  491. FillType getGradientFillType (const XmlPath& fillXml,
  492. const Path& path,
  493. const float opacity) const
  494. {
  495. ColourGradient gradient;
  496. {
  497. const String id (fillXml->getStringAttribute ("xlink:href"));
  498. if (id.startsWithChar ('#'))
  499. {
  500. SetGradientStopsOp op = { this, &gradient, };
  501. findElementForId (topLevelXml, id.substring (1), op);
  502. }
  503. }
  504. addGradientStopsIn (gradient, fillXml);
  505. if (gradient.getNumColours() > 0)
  506. {
  507. gradient.addColour (0.0, gradient.getColour (0));
  508. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  509. }
  510. else
  511. {
  512. gradient.addColour (0.0, Colours::black);
  513. gradient.addColour (1.0, Colours::black);
  514. }
  515. if (opacity < 1.0f)
  516. gradient.multiplyOpacity (opacity);
  517. jassert (gradient.getNumColours() > 0);
  518. gradient.isRadial = fillXml->hasTagNameIgnoringNamespace ("radialGradient");
  519. float gradientWidth = viewBoxW;
  520. float gradientHeight = viewBoxH;
  521. float dx = 0.0f;
  522. float dy = 0.0f;
  523. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  524. if (! userSpace)
  525. {
  526. const Rectangle<float> bounds (path.getBounds());
  527. dx = bounds.getX();
  528. dy = bounds.getY();
  529. gradientWidth = bounds.getWidth();
  530. gradientHeight = bounds.getHeight();
  531. }
  532. if (gradient.isRadial)
  533. {
  534. if (userSpace)
  535. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  536. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  537. else
  538. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  539. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  540. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  541. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  542. //xxx (the fx, fy focal point isn't handled properly here..)
  543. }
  544. else
  545. {
  546. if (userSpace)
  547. {
  548. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  549. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  550. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  551. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  552. }
  553. else
  554. {
  555. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  556. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  557. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  558. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  559. }
  560. if (gradient.point1 == gradient.point2)
  561. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  562. }
  563. FillType type (gradient);
  564. const AffineTransform gradientTransform (parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  565. .followedBy (transform));
  566. if (gradient.isRadial)
  567. {
  568. type.transform = gradientTransform;
  569. }
  570. else
  571. {
  572. // Transform the perpendicular vector into the new coordinate space for the gradient.
  573. // This vector is now the slope of the linear gradient as it should appear in the new coord space
  574. const Point<float> perpendicular (Point<float> (gradient.point2.y - gradient.point1.y,
  575. gradient.point1.x - gradient.point2.x)
  576. .transformedBy (gradientTransform.withAbsoluteTranslation (0, 0)));
  577. const Point<float> newGradPoint1 (gradient.point1.transformedBy (gradientTransform));
  578. const Point<float> newGradPoint2 (gradient.point2.transformedBy (gradientTransform));
  579. // Project the transformed gradient vector onto the transformed slope of the linear
  580. // gradient as it should appear in the new coordinate space
  581. const float scale = perpendicular.getDotProduct (newGradPoint2 - newGradPoint1)
  582. / perpendicular.getDotProduct (perpendicular);
  583. type.gradient->point1 = newGradPoint1;
  584. type.gradient->point2 = newGradPoint2 - perpendicular * scale;
  585. }
  586. return type;
  587. }
  588. struct GetFillTypeOp
  589. {
  590. const SVGState* state;
  591. FillType* dest;
  592. const Path* path;
  593. float opacity;
  594. void operator() (const XmlPath& xml)
  595. {
  596. if (xml->hasTagNameIgnoringNamespace ("linearGradient")
  597. || xml->hasTagNameIgnoringNamespace ("radialGradient"))
  598. *dest = state->getGradientFillType (xml, *path, opacity);
  599. }
  600. };
  601. FillType getPathFillType (const Path& path,
  602. const String& fill,
  603. const String& fillOpacity,
  604. const String& overallOpacity,
  605. const Colour defaultColour) const
  606. {
  607. float opacity = 1.0f;
  608. if (overallOpacity.isNotEmpty())
  609. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  610. if (fillOpacity.isNotEmpty())
  611. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  612. if (fill.startsWithIgnoreCase ("url"))
  613. {
  614. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  615. .upToLastOccurrenceOf (")", false, false).trim());
  616. FillType result;
  617. GetFillTypeOp op = { this, &result, &path, opacity };
  618. if (findElementForId (topLevelXml, id, op))
  619. return result;
  620. }
  621. if (fill.equalsIgnoreCase ("none"))
  622. return Colours::transparentBlack;
  623. int i = 0;
  624. return parseColour (fill, i, defaultColour).withMultipliedAlpha (opacity);
  625. }
  626. static PathStrokeType::JointStyle getJointStyle (const String& join) noexcept
  627. {
  628. if (join.equalsIgnoreCase ("round")) return PathStrokeType::curved;
  629. if (join.equalsIgnoreCase ("bevel")) return PathStrokeType::beveled;
  630. return PathStrokeType::mitered;
  631. }
  632. static PathStrokeType::EndCapStyle getEndCapStyle (const String& cap) noexcept
  633. {
  634. if (cap.equalsIgnoreCase ("round")) return PathStrokeType::rounded;
  635. if (cap.equalsIgnoreCase ("square")) return PathStrokeType::square;
  636. return PathStrokeType::butt;
  637. }
  638. float getStrokeWidth (const String& strokeWidth) const noexcept
  639. {
  640. return transform.getScaleFactor() * getCoordLength (strokeWidth, viewBoxW);
  641. }
  642. PathStrokeType getStrokeFor (const XmlPath& xml) const
  643. {
  644. return PathStrokeType (getStrokeWidth (getStyleAttribute (xml, "stroke-width", "1")),
  645. getJointStyle (getStyleAttribute (xml, "stroke-linejoin")),
  646. getEndCapStyle (getStyleAttribute (xml, "stroke-linecap")));
  647. }
  648. //==============================================================================
  649. Drawable* parseText (const XmlPath& xml, bool shouldParseTransform)
  650. {
  651. if (shouldParseTransform && xml->hasAttribute ("transform"))
  652. {
  653. SVGState newState (*this);
  654. newState.addTransform (xml);
  655. return newState.parseText (xml, false);
  656. }
  657. Array<float> xCoords, yCoords, dxCoords, dyCoords;
  658. getCoordList (xCoords, getInheritedAttribute (xml, "x"), true, true);
  659. getCoordList (yCoords, getInheritedAttribute (xml, "y"), true, false);
  660. getCoordList (dxCoords, getInheritedAttribute (xml, "dx"), true, true);
  661. getCoordList (dyCoords, getInheritedAttribute (xml, "dy"), true, false);
  662. const Font font (getFont (xml));
  663. const String anchorStr = getStyleAttribute(xml, "text-anchor");
  664. DrawableComposite* dc = new DrawableComposite();
  665. setCommonAttributes (*dc, xml);
  666. forEachXmlChildElement (*xml, e)
  667. {
  668. if (e->isTextElement())
  669. {
  670. const String text (e->getText().trim());
  671. DrawableText* dt = new DrawableText();
  672. dc->addAndMakeVisible (dt);
  673. dt->setText (text);
  674. dt->setFont (font, true);
  675. dt->setTransform (transform);
  676. int i = 0;
  677. dt->setColour (parseColour (getStyleAttribute (xml, "fill"), i, Colours::black)
  678. .withMultipliedAlpha (getStyleAttribute (xml, "fill-opacity", "1").getFloatValue()));
  679. Rectangle<float> bounds (xCoords[0], yCoords[0] - font.getAscent(),
  680. font.getStringWidthFloat (text), font.getHeight());
  681. if (anchorStr == "middle") bounds.setX (bounds.getX() - bounds.getWidth() / 2.0f);
  682. else if (anchorStr == "end") bounds.setX (bounds.getX() - bounds.getWidth());
  683. dt->setBoundingBox (bounds);
  684. }
  685. else if (e->hasTagNameIgnoringNamespace ("tspan"))
  686. {
  687. dc->addAndMakeVisible (parseText (xml.getChild (e), true));
  688. }
  689. }
  690. return dc;
  691. }
  692. Font getFont (const XmlPath& xml) const
  693. {
  694. const float fontSize = getCoordLength (getStyleAttribute (xml, "font-size"), 1.0f);
  695. int style = getStyleAttribute (xml, "font-style").containsIgnoreCase ("italic") ? Font::italic : Font::plain;
  696. if (getStyleAttribute (xml, "font-weight").containsIgnoreCase ("bold"))
  697. style |= Font::bold;
  698. const String family (getStyleAttribute (xml, "font-family"));
  699. return family.isEmpty() ? Font (fontSize, style)
  700. : Font (family, fontSize, style);
  701. }
  702. //==============================================================================
  703. void addTransform (const XmlPath& xml)
  704. {
  705. transform = parseTransform (xml->getStringAttribute ("transform"))
  706. .followedBy (transform);
  707. }
  708. //==============================================================================
  709. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  710. {
  711. String number;
  712. if (! parseNextNumber (s, number, allowUnits))
  713. {
  714. value = 0;
  715. return false;
  716. }
  717. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  718. return true;
  719. }
  720. bool parseCoords (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  721. {
  722. return parseCoord (s, p.x, allowUnits, true)
  723. && parseCoord (s, p.y, allowUnits, false);
  724. }
  725. bool parseCoordsOrSkip (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  726. {
  727. if (parseCoords (s, p, allowUnits))
  728. return true;
  729. if (! s.isEmpty()) ++s;
  730. return false;
  731. }
  732. float getCoordLength (const String& s, const float sizeForProportions) const noexcept
  733. {
  734. float n = s.getFloatValue();
  735. const int len = s.length();
  736. if (len > 2)
  737. {
  738. const float dpi = 96.0f;
  739. const juce_wchar n1 = s [len - 2];
  740. const juce_wchar n2 = s [len - 1];
  741. if (n1 == 'i' && n2 == 'n') n *= dpi;
  742. else if (n1 == 'm' && n2 == 'm') n *= dpi / 25.4f;
  743. else if (n1 == 'c' && n2 == 'm') n *= dpi / 2.54f;
  744. else if (n1 == 'p' && n2 == 'c') n *= 15.0f;
  745. else if (n2 == '%') n *= 0.01f * sizeForProportions;
  746. }
  747. return n;
  748. }
  749. float getCoordLength (const XmlPath& xml, const char* attName, const float sizeForProportions) const noexcept
  750. {
  751. return getCoordLength (xml->getStringAttribute (attName), sizeForProportions);
  752. }
  753. void getCoordList (Array<float>& coords, const String& list, bool allowUnits, const bool isX) const
  754. {
  755. String::CharPointerType text (list.getCharPointer());
  756. float value;
  757. while (parseCoord (text, value, allowUnits, isX))
  758. coords.add (value);
  759. }
  760. //==============================================================================
  761. void parseCSSStyle (const XmlPath& xml)
  762. {
  763. cssStyleText = xml->getAllSubText() + "\n" + cssStyleText;
  764. }
  765. static String::CharPointerType findStyleItem (String::CharPointerType source, String::CharPointerType name)
  766. {
  767. const int nameLength = (int) name.length();
  768. while (! source.isEmpty())
  769. {
  770. if (source.getAndAdvance() == '.'
  771. && CharacterFunctions::compareIgnoreCaseUpTo (source, name, nameLength) == 0)
  772. {
  773. String::CharPointerType endOfName ((source + nameLength).findEndOfWhitespace());
  774. if (*endOfName == '{')
  775. return endOfName;
  776. }
  777. }
  778. return source;
  779. }
  780. String getStyleAttribute (const XmlPath& xml, StringRef attributeName,
  781. const String& defaultValue = String()) const
  782. {
  783. if (xml->hasAttribute (attributeName))
  784. return xml->getStringAttribute (attributeName, defaultValue);
  785. const String styleAtt (xml->getStringAttribute ("style"));
  786. if (styleAtt.isNotEmpty())
  787. {
  788. const String value (getAttributeFromStyleList (styleAtt, attributeName, String()));
  789. if (value.isNotEmpty())
  790. return value;
  791. }
  792. else if (xml->hasAttribute ("class"))
  793. {
  794. String::CharPointerType openBrace = findStyleItem (cssStyleText.getCharPointer(),
  795. xml->getStringAttribute ("class").getCharPointer());
  796. if (! openBrace.isEmpty())
  797. {
  798. String::CharPointerType closeBrace = CharacterFunctions::find (openBrace, (juce_wchar) '}');
  799. if (closeBrace != openBrace)
  800. {
  801. const String value (getAttributeFromStyleList (String (openBrace + 1, closeBrace),
  802. attributeName, defaultValue));
  803. if (value.isNotEmpty())
  804. return value;
  805. }
  806. }
  807. }
  808. if (xml.parent != nullptr)
  809. return getStyleAttribute (*xml.parent, attributeName, defaultValue);
  810. return defaultValue;
  811. }
  812. String getInheritedAttribute (const XmlPath& xml, StringRef attributeName) const
  813. {
  814. if (xml->hasAttribute (attributeName))
  815. return xml->getStringAttribute (attributeName);
  816. if (xml.parent != nullptr)
  817. return getInheritedAttribute (*xml.parent, attributeName);
  818. return String();
  819. }
  820. static int parsePlacementFlags (const String& align) noexcept
  821. {
  822. if (align.isEmpty())
  823. return 0;
  824. if (align.containsIgnoreCase ("none"))
  825. return RectanglePlacement::stretchToFit;
  826. return (align.containsIgnoreCase ("slice") ? RectanglePlacement::fillDestination : 0)
  827. | (align.containsIgnoreCase ("xMin") ? RectanglePlacement::xLeft
  828. : (align.containsIgnoreCase ("xMax") ? RectanglePlacement::xRight
  829. : RectanglePlacement::xMid))
  830. | (align.containsIgnoreCase ("yMin") ? RectanglePlacement::yTop
  831. : (align.containsIgnoreCase ("yMax") ? RectanglePlacement::yBottom
  832. : RectanglePlacement::yMid));
  833. }
  834. //==============================================================================
  835. static bool isIdentifierChar (const juce_wchar c)
  836. {
  837. return CharacterFunctions::isLetter (c) || c == '-';
  838. }
  839. static String getAttributeFromStyleList (const String& list, StringRef attributeName, const String& defaultValue)
  840. {
  841. int i = 0;
  842. for (;;)
  843. {
  844. i = list.indexOf (i, attributeName);
  845. if (i < 0)
  846. break;
  847. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  848. && ! isIdentifierChar (list [i + attributeName.length()]))
  849. {
  850. i = list.indexOfChar (i, ':');
  851. if (i < 0)
  852. break;
  853. int end = list.indexOfChar (i, ';');
  854. if (end < 0)
  855. end = 0x7ffff;
  856. return list.substring (i + 1, end).trim();
  857. }
  858. ++i;
  859. }
  860. return defaultValue;
  861. }
  862. //==============================================================================
  863. static bool isStartOfNumber (juce_wchar c) noexcept
  864. {
  865. return CharacterFunctions::isDigit (c) || c == '-' || c == '+';
  866. }
  867. static bool parseNextNumber (String::CharPointerType& text, String& value, const bool allowUnits)
  868. {
  869. String::CharPointerType s (text);
  870. while (s.isWhitespace() || *s == ',')
  871. ++s;
  872. String::CharPointerType start (s);
  873. if (isStartOfNumber (*s))
  874. ++s;
  875. while (s.isDigit())
  876. ++s;
  877. if (*s == '.')
  878. {
  879. ++s;
  880. while (s.isDigit())
  881. ++s;
  882. }
  883. if ((*s == 'e' || *s == 'E') && isStartOfNumber (s[1]))
  884. {
  885. s += 2;
  886. while (s.isDigit())
  887. ++s;
  888. }
  889. if (allowUnits)
  890. while (s.isLetter())
  891. ++s;
  892. if (s == start)
  893. {
  894. text = s;
  895. return false;
  896. }
  897. value = String (start, s);
  898. while (s.isWhitespace() || *s == ',')
  899. ++s;
  900. text = s;
  901. return true;
  902. }
  903. //==============================================================================
  904. static Colour parseColour (const String& s, int& index, const Colour defaultColour)
  905. {
  906. if (s [index] == '#')
  907. {
  908. uint32 hex[6] = { 0 };
  909. int numChars = 0;
  910. for (int i = 6; --i >= 0;)
  911. {
  912. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  913. if (hexValue >= 0)
  914. hex [numChars++] = (uint32) hexValue;
  915. else
  916. break;
  917. }
  918. if (numChars <= 3)
  919. return Colour ((uint8) (hex [0] * 0x11),
  920. (uint8) (hex [1] * 0x11),
  921. (uint8) (hex [2] * 0x11));
  922. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  923. (uint8) ((hex [2] << 4) + hex [3]),
  924. (uint8) ((hex [4] << 4) + hex [5]));
  925. }
  926. if (s [index] == 'r'
  927. && s [index + 1] == 'g'
  928. && s [index + 2] == 'b')
  929. {
  930. const int openBracket = s.indexOfChar (index, '(');
  931. const int closeBracket = s.indexOfChar (openBracket, ')');
  932. if (openBracket >= 3 && closeBracket > openBracket)
  933. {
  934. index = closeBracket;
  935. StringArray tokens;
  936. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  937. tokens.trim();
  938. tokens.removeEmptyStrings();
  939. if (tokens[0].containsChar ('%'))
  940. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  941. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  942. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  943. else
  944. return Colour ((uint8) tokens[0].getIntValue(),
  945. (uint8) tokens[1].getIntValue(),
  946. (uint8) tokens[2].getIntValue());
  947. }
  948. }
  949. return Colours::findColourForName (s, defaultColour);
  950. }
  951. static AffineTransform parseTransform (String t)
  952. {
  953. AffineTransform result;
  954. while (t.isNotEmpty())
  955. {
  956. StringArray tokens;
  957. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  958. .upToFirstOccurrenceOf (")", false, false),
  959. ", ", "");
  960. tokens.removeEmptyStrings (true);
  961. float numbers[6];
  962. for (int i = 0; i < numElementsInArray (numbers); ++i)
  963. numbers[i] = tokens[i].getFloatValue();
  964. AffineTransform trans;
  965. if (t.startsWithIgnoreCase ("matrix"))
  966. {
  967. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  968. numbers[1], numbers[3], numbers[5]);
  969. }
  970. else if (t.startsWithIgnoreCase ("translate"))
  971. {
  972. trans = AffineTransform::translation (numbers[0], numbers[1]);
  973. }
  974. else if (t.startsWithIgnoreCase ("scale"))
  975. {
  976. trans = AffineTransform::scale (numbers[0], numbers[tokens.size() > 1 ? 1 : 0]);
  977. }
  978. else if (t.startsWithIgnoreCase ("rotate"))
  979. {
  980. trans = AffineTransform::rotation (degreesToRadians (numbers[0]), numbers[1], numbers[2]);
  981. }
  982. else if (t.startsWithIgnoreCase ("skewX"))
  983. {
  984. trans = AffineTransform::shear (std::tan (degreesToRadians (numbers[0])), 0.0f);
  985. }
  986. else if (t.startsWithIgnoreCase ("skewY"))
  987. {
  988. trans = AffineTransform::shear (0.0f, std::tan (degreesToRadians (numbers[0])));
  989. }
  990. result = trans.followedBy (result);
  991. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  992. }
  993. return result;
  994. }
  995. static void endpointToCentreParameters (const double x1, const double y1,
  996. const double x2, const double y2,
  997. const double angle,
  998. const bool largeArc, const bool sweep,
  999. double& rx, double& ry,
  1000. double& centreX, double& centreY,
  1001. double& startAngle, double& deltaAngle) noexcept
  1002. {
  1003. const double midX = (x1 - x2) * 0.5;
  1004. const double midY = (y1 - y2) * 0.5;
  1005. const double cosAngle = std::cos (angle);
  1006. const double sinAngle = std::sin (angle);
  1007. const double xp = cosAngle * midX + sinAngle * midY;
  1008. const double yp = cosAngle * midY - sinAngle * midX;
  1009. const double xp2 = xp * xp;
  1010. const double yp2 = yp * yp;
  1011. double rx2 = rx * rx;
  1012. double ry2 = ry * ry;
  1013. const double s = (xp2 / rx2) + (yp2 / ry2);
  1014. double c;
  1015. if (s <= 1.0)
  1016. {
  1017. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  1018. / (( rx2 * yp2) + (ry2 * xp2))));
  1019. if (largeArc == sweep)
  1020. c = -c;
  1021. }
  1022. else
  1023. {
  1024. const double s2 = std::sqrt (s);
  1025. rx *= s2;
  1026. ry *= s2;
  1027. c = 0;
  1028. }
  1029. const double cpx = ((rx * yp) / ry) * c;
  1030. const double cpy = ((-ry * xp) / rx) * c;
  1031. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  1032. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  1033. const double ux = (xp - cpx) / rx;
  1034. const double uy = (yp - cpy) / ry;
  1035. const double vx = (-xp - cpx) / rx;
  1036. const double vy = (-yp - cpy) / ry;
  1037. const double length = juce_hypot (ux, uy);
  1038. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  1039. if (uy < 0)
  1040. startAngle = -startAngle;
  1041. startAngle += double_Pi * 0.5;
  1042. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  1043. / (length * juce_hypot (vx, vy))));
  1044. if ((ux * vy) - (uy * vx) < 0)
  1045. deltaAngle = -deltaAngle;
  1046. if (sweep)
  1047. {
  1048. if (deltaAngle < 0)
  1049. deltaAngle += double_Pi * 2.0;
  1050. }
  1051. else
  1052. {
  1053. if (deltaAngle > 0)
  1054. deltaAngle -= double_Pi * 2.0;
  1055. }
  1056. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  1057. }
  1058. template <typename OperationType>
  1059. static bool findElementForId (const XmlPath& parent, const String& id, OperationType& op)
  1060. {
  1061. forEachXmlChildElement (*parent, e)
  1062. {
  1063. if (e->compareAttribute ("id", id))
  1064. {
  1065. op (parent.getChild (e));
  1066. return true;
  1067. }
  1068. if (findElementForId (parent.getChild (e), id, op))
  1069. return true;
  1070. }
  1071. return false;
  1072. }
  1073. SVGState& operator= (const SVGState&) JUCE_DELETED_FUNCTION;
  1074. };
  1075. //==============================================================================
  1076. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  1077. {
  1078. SVGState state (&svgDocument);
  1079. return state.parseSVGElement (SVGState::XmlPath (&svgDocument, nullptr));
  1080. }
  1081. Path Drawable::parseSVGPath (const String& svgPath)
  1082. {
  1083. SVGState state (nullptr);
  1084. Path p;
  1085. state.parsePathString (p, svgPath);
  1086. return p;
  1087. }