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.

1355 lines
48KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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. setDrawableID (*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 = num.getFloatValue() * (180.0f / float_Pi);
  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 setDrawableID (Drawable& d, const XmlPath& xml)
  281. {
  282. String compID (xml->getStringAttribute ("id"));
  283. d.setName (compID);
  284. d.setComponentID (compID);
  285. }
  286. //==============================================================================
  287. void parseSubElements (const XmlPath& xml, DrawableComposite& parentDrawable)
  288. {
  289. forEachXmlChildElement (*xml, e)
  290. parentDrawable.addAndMakeVisible (parseSubElement (xml.getChild (e)));
  291. }
  292. Drawable* parseSubElement (const XmlPath& xml)
  293. {
  294. const String tag (xml->getTagNameWithoutNamespace());
  295. if (tag == "g") return parseGroupElement (xml);
  296. if (tag == "svg") return parseSVGElement (xml);
  297. if (tag == "path") return parsePath (xml);
  298. if (tag == "rect") return parseRect (xml);
  299. if (tag == "circle") return parseCircle (xml);
  300. if (tag == "ellipse") return parseEllipse (xml);
  301. if (tag == "line") return parseLine (xml);
  302. if (tag == "polyline") return parsePolygon (xml, true);
  303. if (tag == "polygon") return parsePolygon (xml, false);
  304. if (tag == "text") return parseText (xml, true);
  305. if (tag == "switch") return parseSwitch (xml);
  306. if (tag == "style") parseCSSStyle (xml);
  307. return nullptr;
  308. }
  309. DrawableComposite* parseSwitch (const XmlPath& xml)
  310. {
  311. if (const XmlElement* const group = xml->getChildByName ("g"))
  312. return parseGroupElement (xml.getChild (group));
  313. return nullptr;
  314. }
  315. DrawableComposite* parseGroupElement (const XmlPath& xml)
  316. {
  317. DrawableComposite* const drawable = new DrawableComposite();
  318. setDrawableID (*drawable, xml);
  319. if (xml->hasAttribute ("transform"))
  320. {
  321. SVGState newState (*this);
  322. newState.addTransform (xml);
  323. newState.parseSubElements (xml, *drawable);
  324. }
  325. else
  326. {
  327. parseSubElements (xml, *drawable);
  328. }
  329. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  330. return drawable;
  331. }
  332. //==============================================================================
  333. Drawable* parsePath (const XmlPath& xml) const
  334. {
  335. Path path;
  336. parsePathString (path, xml->getStringAttribute ("d"));
  337. if (getStyleAttribute (xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  338. path.setUsingNonZeroWinding (false);
  339. return parseShape (xml, path);
  340. }
  341. Drawable* parseRect (const XmlPath& xml) const
  342. {
  343. Path rect;
  344. const bool hasRX = xml->hasAttribute ("rx");
  345. const bool hasRY = xml->hasAttribute ("ry");
  346. if (hasRX || hasRY)
  347. {
  348. float rx = getCoordLength (xml, "rx", viewBoxW);
  349. float ry = getCoordLength (xml, "ry", viewBoxH);
  350. if (! hasRX)
  351. rx = ry;
  352. else if (! hasRY)
  353. ry = rx;
  354. rect.addRoundedRectangle (getCoordLength (xml, "x", viewBoxW),
  355. getCoordLength (xml, "y", viewBoxH),
  356. getCoordLength (xml, "width", viewBoxW),
  357. getCoordLength (xml, "height", viewBoxH),
  358. rx, ry);
  359. }
  360. else
  361. {
  362. rect.addRectangle (getCoordLength (xml, "x", viewBoxW),
  363. getCoordLength (xml, "y", viewBoxH),
  364. getCoordLength (xml, "width", viewBoxW),
  365. getCoordLength (xml, "height", viewBoxH));
  366. }
  367. return parseShape (xml, rect);
  368. }
  369. Drawable* parseCircle (const XmlPath& xml) const
  370. {
  371. Path circle;
  372. const float cx = getCoordLength (xml, "cx", viewBoxW);
  373. const float cy = getCoordLength (xml, "cy", viewBoxH);
  374. const float radius = getCoordLength (xml, "r", viewBoxW);
  375. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  376. return parseShape (xml, circle);
  377. }
  378. Drawable* parseEllipse (const XmlPath& xml) const
  379. {
  380. Path ellipse;
  381. const float cx = getCoordLength (xml, "cx", viewBoxW);
  382. const float cy = getCoordLength (xml, "cy", viewBoxH);
  383. const float radiusX = getCoordLength (xml, "rx", viewBoxW);
  384. const float radiusY = getCoordLength (xml, "ry", viewBoxH);
  385. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  386. return parseShape (xml, ellipse);
  387. }
  388. Drawable* parseLine (const XmlPath& xml) const
  389. {
  390. Path line;
  391. const float x1 = getCoordLength (xml, "x1", viewBoxW);
  392. const float y1 = getCoordLength (xml, "y1", viewBoxH);
  393. const float x2 = getCoordLength (xml, "x2", viewBoxW);
  394. const float y2 = getCoordLength (xml, "y2", viewBoxH);
  395. line.startNewSubPath (x1, y1);
  396. line.lineTo (x2, y2);
  397. return parseShape (xml, line);
  398. }
  399. Drawable* parsePolygon (const XmlPath& xml, const bool isPolyline) const
  400. {
  401. const String pointsAtt (xml->getStringAttribute ("points"));
  402. String::CharPointerType points (pointsAtt.getCharPointer());
  403. Path path;
  404. Point<float> p;
  405. if (parseCoords (points, p, true))
  406. {
  407. Point<float> first (p), last;
  408. path.startNewSubPath (first);
  409. while (parseCoords (points, p, true))
  410. {
  411. last = p;
  412. path.lineTo (p);
  413. }
  414. if ((! isPolyline) || first == last)
  415. path.closeSubPath();
  416. }
  417. return parseShape (xml, path);
  418. }
  419. //==============================================================================
  420. Drawable* parseShape (const XmlPath& xml, Path& path,
  421. const bool shouldParseTransform = true) const
  422. {
  423. if (shouldParseTransform && xml->hasAttribute ("transform"))
  424. {
  425. SVGState newState (*this);
  426. newState.addTransform (xml);
  427. return newState.parseShape (xml, path, false);
  428. }
  429. DrawablePath* dp = new DrawablePath();
  430. setDrawableID (*dp, xml);
  431. dp->setFill (Colours::transparentBlack);
  432. path.applyTransform (transform);
  433. dp->setPath (path);
  434. dp->setFill (getPathFillType (path,
  435. getStyleAttribute (xml, "fill"),
  436. getStyleAttribute (xml, "fill-opacity"),
  437. getStyleAttribute (xml, "opacity"),
  438. pathContainsClosedSubPath (path) ? Colours::black
  439. : Colours::transparentBlack));
  440. const String strokeType (getStyleAttribute (xml, "stroke"));
  441. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  442. {
  443. dp->setStrokeFill (getPathFillType (path, strokeType,
  444. getStyleAttribute (xml, "stroke-opacity"),
  445. getStyleAttribute (xml, "opacity"),
  446. Colours::transparentBlack));
  447. dp->setStrokeType (getStrokeFor (xml));
  448. }
  449. return dp;
  450. }
  451. static bool pathContainsClosedSubPath (const Path& path) noexcept
  452. {
  453. for (Path::Iterator iter (path); iter.next();)
  454. if (iter.elementType == Path::Iterator::closePath)
  455. return true;
  456. return false;
  457. }
  458. struct SetGradientStopsOp
  459. {
  460. const SVGState* state;
  461. ColourGradient* gradient;
  462. void operator() (const XmlPath& xml)
  463. {
  464. state->addGradientStopsIn (*gradient, xml);
  465. }
  466. };
  467. void addGradientStopsIn (ColourGradient& cg, const XmlPath& fillXml) const
  468. {
  469. if (fillXml.xml != nullptr)
  470. {
  471. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  472. {
  473. int index = 0;
  474. Colour col (parseColour (getStyleAttribute (fillXml.getChild (e), "stop-color"), index, Colours::black));
  475. const String opacity (getStyleAttribute (fillXml.getChild (e), "stop-opacity", "1"));
  476. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  477. double offset = e->getDoubleAttribute ("offset");
  478. if (e->getStringAttribute ("offset").containsChar ('%'))
  479. offset *= 0.01;
  480. cg.addColour (jlimit (0.0, 1.0, offset), col);
  481. }
  482. }
  483. }
  484. FillType getGradientFillType (const XmlPath& fillXml,
  485. const Path& path,
  486. const float opacity) const
  487. {
  488. ColourGradient gradient;
  489. {
  490. const String id (fillXml->getStringAttribute ("xlink:href"));
  491. if (id.startsWithChar ('#'))
  492. {
  493. SetGradientStopsOp op = { this, &gradient, };
  494. findElementForId (topLevelXml, id.substring (1), op);
  495. }
  496. }
  497. addGradientStopsIn (gradient, fillXml);
  498. if (gradient.getNumColours() > 0)
  499. {
  500. gradient.addColour (0.0, gradient.getColour (0));
  501. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  502. }
  503. else
  504. {
  505. gradient.addColour (0.0, Colours::black);
  506. gradient.addColour (1.0, Colours::black);
  507. }
  508. if (opacity < 1.0f)
  509. gradient.multiplyOpacity (opacity);
  510. jassert (gradient.getNumColours() > 0);
  511. gradient.isRadial = fillXml->hasTagNameIgnoringNamespace ("radialGradient");
  512. float gradientWidth = viewBoxW;
  513. float gradientHeight = viewBoxH;
  514. float dx = 0.0f;
  515. float dy = 0.0f;
  516. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  517. if (! userSpace)
  518. {
  519. const Rectangle<float> bounds (path.getBounds());
  520. dx = bounds.getX();
  521. dy = bounds.getY();
  522. gradientWidth = bounds.getWidth();
  523. gradientHeight = bounds.getHeight();
  524. }
  525. if (gradient.isRadial)
  526. {
  527. if (userSpace)
  528. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  529. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  530. else
  531. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  532. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  533. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  534. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  535. //xxx (the fx, fy focal point isn't handled properly here..)
  536. }
  537. else
  538. {
  539. if (userSpace)
  540. {
  541. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  542. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  543. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  544. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  545. }
  546. else
  547. {
  548. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  549. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  550. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  551. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  552. }
  553. if (gradient.point1 == gradient.point2)
  554. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  555. }
  556. FillType type (gradient);
  557. const AffineTransform gradientTransform (parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  558. .followedBy (transform));
  559. if (gradient.isRadial)
  560. {
  561. type.transform = gradientTransform;
  562. }
  563. else
  564. {
  565. // Transform the perpendicular vector into the new coordinate space for the gradient.
  566. // This vector is now the slope of the linear gradient as it should appear in the new coord space
  567. const Point<float> perpendicular (Point<float> (gradient.point2.y - gradient.point1.y,
  568. gradient.point1.x - gradient.point2.x)
  569. .transformedBy (gradientTransform.withAbsoluteTranslation (0, 0)));
  570. const Point<float> newGradPoint1 (gradient.point1.transformedBy (gradientTransform));
  571. const Point<float> newGradPoint2 (gradient.point2.transformedBy (gradientTransform));
  572. // Project the transformed gradient vector onto the transformed slope of the linear
  573. // gradient as it should appear in the new coordinate space
  574. const float scale = perpendicular.getDotProduct (newGradPoint2 - newGradPoint1)
  575. / perpendicular.getDotProduct (perpendicular);
  576. type.gradient->point1 = newGradPoint1;
  577. type.gradient->point2 = newGradPoint2 - perpendicular * scale;
  578. }
  579. return type;
  580. }
  581. struct GetFillTypeOp
  582. {
  583. const SVGState* state;
  584. FillType* dest;
  585. const Path* path;
  586. float opacity;
  587. void operator() (const XmlPath& xml)
  588. {
  589. if (xml->hasTagNameIgnoringNamespace ("linearGradient")
  590. || xml->hasTagNameIgnoringNamespace ("radialGradient"))
  591. *dest = state->getGradientFillType (xml, *path, opacity);
  592. }
  593. };
  594. FillType getPathFillType (const Path& path,
  595. const String& fill,
  596. const String& fillOpacity,
  597. const String& overallOpacity,
  598. const Colour defaultColour) const
  599. {
  600. float opacity = 1.0f;
  601. if (overallOpacity.isNotEmpty())
  602. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  603. if (fillOpacity.isNotEmpty())
  604. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  605. if (fill.startsWithIgnoreCase ("url"))
  606. {
  607. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  608. .upToLastOccurrenceOf (")", false, false).trim());
  609. FillType result;
  610. GetFillTypeOp op = { this, &result, &path, opacity };
  611. if (findElementForId (topLevelXml, id, op))
  612. return result;
  613. }
  614. if (fill.equalsIgnoreCase ("none"))
  615. return Colours::transparentBlack;
  616. int i = 0;
  617. return parseColour (fill, i, defaultColour).withMultipliedAlpha (opacity);
  618. }
  619. static PathStrokeType::JointStyle getJointStyle (const String& join) noexcept
  620. {
  621. if (join.equalsIgnoreCase ("round")) return PathStrokeType::curved;
  622. if (join.equalsIgnoreCase ("bevel")) return PathStrokeType::beveled;
  623. return PathStrokeType::mitered;
  624. }
  625. static PathStrokeType::EndCapStyle getEndCapStyle (const String& cap) noexcept
  626. {
  627. if (cap.equalsIgnoreCase ("round")) return PathStrokeType::rounded;
  628. if (cap.equalsIgnoreCase ("square")) return PathStrokeType::square;
  629. return PathStrokeType::butt;
  630. }
  631. float getStrokeWidth (const String& strokeWidth) const noexcept
  632. {
  633. return transform.getScaleFactor() * getCoordLength (strokeWidth, viewBoxW);
  634. }
  635. PathStrokeType getStrokeFor (const XmlPath& xml) const
  636. {
  637. return PathStrokeType (getStrokeWidth (getStyleAttribute (xml, "stroke-width", "1")),
  638. getJointStyle (getStyleAttribute (xml, "stroke-linejoin")),
  639. getEndCapStyle (getStyleAttribute (xml, "stroke-linecap")));
  640. }
  641. //==============================================================================
  642. Drawable* parseText (const XmlPath& xml, bool shouldParseTransform)
  643. {
  644. if (shouldParseTransform && xml->hasAttribute ("transform"))
  645. {
  646. SVGState newState (*this);
  647. newState.addTransform (xml);
  648. return newState.parseText (xml, false);
  649. }
  650. Array<float> xCoords, yCoords, dxCoords, dyCoords;
  651. getCoordList (xCoords, getInheritedAttribute (xml, "x"), true, true);
  652. getCoordList (yCoords, getInheritedAttribute (xml, "y"), true, false);
  653. getCoordList (dxCoords, getInheritedAttribute (xml, "dx"), true, true);
  654. getCoordList (dyCoords, getInheritedAttribute (xml, "dy"), true, false);
  655. const Font font (getFont (xml));
  656. const String anchorStr = getStyleAttribute(xml, "text-anchor");
  657. DrawableComposite* dc = new DrawableComposite();
  658. setDrawableID (*dc, xml);
  659. forEachXmlChildElement (*xml, e)
  660. {
  661. if (e->isTextElement())
  662. {
  663. const String text (e->getText().trim());
  664. DrawableText* dt = new DrawableText();
  665. dc->addAndMakeVisible (dt);
  666. dt->setText (text);
  667. dt->setFont (font, true);
  668. dt->setTransform (transform);
  669. int i = 0;
  670. dt->setColour (parseColour (getStyleAttribute (xml, "fill"), i, Colours::black)
  671. .withMultipliedAlpha (getStyleAttribute (xml, "fill-opacity", "1").getFloatValue()));
  672. Rectangle<float> bounds (xCoords[0], yCoords[0] - font.getAscent(),
  673. font.getStringWidthFloat (text), font.getHeight());
  674. if (anchorStr == "middle") bounds.setX (bounds.getX() - bounds.getWidth() / 2.0f);
  675. else if (anchorStr == "end") bounds.setX (bounds.getX() - bounds.getWidth());
  676. dt->setBoundingBox (bounds);
  677. }
  678. else if (e->hasTagNameIgnoringNamespace ("tspan"))
  679. {
  680. dc->addAndMakeVisible (parseText (xml.getChild (e), true));
  681. }
  682. }
  683. return dc;
  684. }
  685. Font getFont (const XmlPath& xml) const
  686. {
  687. const float fontSize = getCoordLength (getStyleAttribute (xml, "font-size"), 1.0f);
  688. int style = getStyleAttribute (xml, "font-style").containsIgnoreCase ("italic") ? Font::italic : Font::plain;
  689. if (getStyleAttribute (xml, "font-weight").containsIgnoreCase ("bold"))
  690. style |= Font::bold;
  691. const String family (getStyleAttribute (xml, "font-family"));
  692. return family.isEmpty() ? Font (fontSize, style)
  693. : Font (family, fontSize, style);
  694. }
  695. //==============================================================================
  696. void addTransform (const XmlPath& xml)
  697. {
  698. transform = parseTransform (xml->getStringAttribute ("transform"))
  699. .followedBy (transform);
  700. }
  701. //==============================================================================
  702. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  703. {
  704. String number;
  705. if (! parseNextNumber (s, number, allowUnits))
  706. {
  707. value = 0;
  708. return false;
  709. }
  710. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  711. return true;
  712. }
  713. bool parseCoords (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  714. {
  715. return parseCoord (s, p.x, allowUnits, true)
  716. && parseCoord (s, p.y, allowUnits, false);
  717. }
  718. bool parseCoordsOrSkip (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  719. {
  720. if (parseCoords (s, p, allowUnits))
  721. return true;
  722. if (! s.isEmpty()) ++s;
  723. return false;
  724. }
  725. float getCoordLength (const String& s, const float sizeForProportions) const noexcept
  726. {
  727. float n = s.getFloatValue();
  728. const int len = s.length();
  729. if (len > 2)
  730. {
  731. const float dpi = 96.0f;
  732. const juce_wchar n1 = s [len - 2];
  733. const juce_wchar n2 = s [len - 1];
  734. if (n1 == 'i' && n2 == 'n') n *= dpi;
  735. else if (n1 == 'm' && n2 == 'm') n *= dpi / 25.4f;
  736. else if (n1 == 'c' && n2 == 'm') n *= dpi / 2.54f;
  737. else if (n1 == 'p' && n2 == 'c') n *= 15.0f;
  738. else if (n2 == '%') n *= 0.01f * sizeForProportions;
  739. }
  740. return n;
  741. }
  742. float getCoordLength (const XmlPath& xml, const char* attName, const float sizeForProportions) const noexcept
  743. {
  744. return getCoordLength (xml->getStringAttribute (attName), sizeForProportions);
  745. }
  746. void getCoordList (Array<float>& coords, const String& list, bool allowUnits, const bool isX) const
  747. {
  748. String::CharPointerType text (list.getCharPointer());
  749. float value;
  750. while (parseCoord (text, value, allowUnits, isX))
  751. coords.add (value);
  752. }
  753. //==============================================================================
  754. void parseCSSStyle (const XmlPath& xml)
  755. {
  756. cssStyleText = xml->getAllSubText() + "\n" + cssStyleText;
  757. }
  758. static String::CharPointerType findStyleItem (String::CharPointerType source, String::CharPointerType name)
  759. {
  760. const int nameLength = (int) name.length();
  761. while (! source.isEmpty())
  762. {
  763. if (source.getAndAdvance() == '.'
  764. && CharacterFunctions::compareIgnoreCaseUpTo (source, name, nameLength) == 0)
  765. {
  766. String::CharPointerType endOfName ((source + nameLength).findEndOfWhitespace());
  767. if (*endOfName == '{')
  768. return endOfName;
  769. }
  770. }
  771. return source;
  772. }
  773. String getStyleAttribute (const XmlPath& xml, StringRef attributeName,
  774. const String& defaultValue = String()) const
  775. {
  776. if (xml->hasAttribute (attributeName))
  777. return xml->getStringAttribute (attributeName, defaultValue);
  778. const String styleAtt (xml->getStringAttribute ("style"));
  779. if (styleAtt.isNotEmpty())
  780. {
  781. const String value (getAttributeFromStyleList (styleAtt, attributeName, String()));
  782. if (value.isNotEmpty())
  783. return value;
  784. }
  785. else if (xml->hasAttribute ("class"))
  786. {
  787. String::CharPointerType openBrace = findStyleItem (cssStyleText.getCharPointer(),
  788. xml->getStringAttribute ("class").getCharPointer());
  789. if (! openBrace.isEmpty())
  790. {
  791. String::CharPointerType closeBrace = CharacterFunctions::find (openBrace, (juce_wchar) '}');
  792. if (closeBrace != openBrace)
  793. {
  794. const String value (getAttributeFromStyleList (String (openBrace + 1, closeBrace),
  795. attributeName, defaultValue));
  796. if (value.isNotEmpty())
  797. return value;
  798. }
  799. }
  800. }
  801. if (xml.parent != nullptr)
  802. return getStyleAttribute (*xml.parent, attributeName, defaultValue);
  803. return defaultValue;
  804. }
  805. String getInheritedAttribute (const XmlPath& xml, StringRef attributeName) const
  806. {
  807. if (xml->hasAttribute (attributeName))
  808. return xml->getStringAttribute (attributeName);
  809. if (xml.parent != nullptr)
  810. return getInheritedAttribute (*xml.parent, attributeName);
  811. return String();
  812. }
  813. static int parsePlacementFlags (const String& align) noexcept
  814. {
  815. if (align.isEmpty())
  816. return 0;
  817. if (align.containsIgnoreCase ("none"))
  818. return RectanglePlacement::stretchToFit;
  819. return (align.containsIgnoreCase ("slice") ? RectanglePlacement::fillDestination : 0)
  820. | (align.containsIgnoreCase ("xMin") ? RectanglePlacement::xLeft
  821. : (align.containsIgnoreCase ("xMax") ? RectanglePlacement::xRight
  822. : RectanglePlacement::xMid))
  823. | (align.containsIgnoreCase ("yMin") ? RectanglePlacement::yTop
  824. : (align.containsIgnoreCase ("yMax") ? RectanglePlacement::yBottom
  825. : RectanglePlacement::yMid));
  826. }
  827. //==============================================================================
  828. static bool isIdentifierChar (const juce_wchar c)
  829. {
  830. return CharacterFunctions::isLetter (c) || c == '-';
  831. }
  832. static String getAttributeFromStyleList (const String& list, StringRef attributeName, const String& defaultValue)
  833. {
  834. int i = 0;
  835. for (;;)
  836. {
  837. i = list.indexOf (i, attributeName);
  838. if (i < 0)
  839. break;
  840. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  841. && ! isIdentifierChar (list [i + attributeName.length()]))
  842. {
  843. i = list.indexOfChar (i, ':');
  844. if (i < 0)
  845. break;
  846. int end = list.indexOfChar (i, ';');
  847. if (end < 0)
  848. end = 0x7ffff;
  849. return list.substring (i + 1, end).trim();
  850. }
  851. ++i;
  852. }
  853. return defaultValue;
  854. }
  855. //==============================================================================
  856. static bool parseNextNumber (String::CharPointerType& text, String& value, const bool allowUnits)
  857. {
  858. String::CharPointerType s (text);
  859. while (s.isWhitespace() || *s == ',')
  860. ++s;
  861. String::CharPointerType start (s);
  862. if (s.isDigit() || *s == '.' || *s == '-')
  863. ++s;
  864. while (s.isDigit() || *s == '.')
  865. ++s;
  866. if ((*s == 'e' || *s == 'E')
  867. && ((s + 1).isDigit() || s[1] == '-' || s[1] == '+'))
  868. {
  869. s += 2;
  870. while (s.isDigit())
  871. ++s;
  872. }
  873. if (allowUnits)
  874. while (s.isLetter())
  875. ++s;
  876. if (s == start)
  877. {
  878. text = s;
  879. return false;
  880. }
  881. value = String (start, s);
  882. while (s.isWhitespace() || *s == ',')
  883. ++s;
  884. text = s;
  885. return true;
  886. }
  887. //==============================================================================
  888. static Colour parseColour (const String& s, int& index, const Colour defaultColour)
  889. {
  890. if (s [index] == '#')
  891. {
  892. uint32 hex[6] = { 0 };
  893. int numChars = 0;
  894. for (int i = 6; --i >= 0;)
  895. {
  896. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  897. if (hexValue >= 0)
  898. hex [numChars++] = (uint32) hexValue;
  899. else
  900. break;
  901. }
  902. if (numChars <= 3)
  903. return Colour ((uint8) (hex [0] * 0x11),
  904. (uint8) (hex [1] * 0x11),
  905. (uint8) (hex [2] * 0x11));
  906. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  907. (uint8) ((hex [2] << 4) + hex [3]),
  908. (uint8) ((hex [4] << 4) + hex [5]));
  909. }
  910. if (s [index] == 'r'
  911. && s [index + 1] == 'g'
  912. && s [index + 2] == 'b')
  913. {
  914. const int openBracket = s.indexOfChar (index, '(');
  915. const int closeBracket = s.indexOfChar (openBracket, ')');
  916. if (openBracket >= 3 && closeBracket > openBracket)
  917. {
  918. index = closeBracket;
  919. StringArray tokens;
  920. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  921. tokens.trim();
  922. tokens.removeEmptyStrings();
  923. if (tokens[0].containsChar ('%'))
  924. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  925. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  926. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  927. else
  928. return Colour ((uint8) tokens[0].getIntValue(),
  929. (uint8) tokens[1].getIntValue(),
  930. (uint8) tokens[2].getIntValue());
  931. }
  932. }
  933. return Colours::findColourForName (s, defaultColour);
  934. }
  935. static AffineTransform parseTransform (String t)
  936. {
  937. AffineTransform result;
  938. while (t.isNotEmpty())
  939. {
  940. StringArray tokens;
  941. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  942. .upToFirstOccurrenceOf (")", false, false),
  943. ", ", "");
  944. tokens.removeEmptyStrings (true);
  945. float numbers[6];
  946. for (int i = 0; i < numElementsInArray (numbers); ++i)
  947. numbers[i] = tokens[i].getFloatValue();
  948. AffineTransform trans;
  949. if (t.startsWithIgnoreCase ("matrix"))
  950. {
  951. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  952. numbers[1], numbers[3], numbers[5]);
  953. }
  954. else if (t.startsWithIgnoreCase ("translate"))
  955. {
  956. trans = AffineTransform::translation (numbers[0], numbers[1]);
  957. }
  958. else if (t.startsWithIgnoreCase ("scale"))
  959. {
  960. trans = AffineTransform::scale (numbers[0], numbers[tokens.size() > 1 ? 1 : 0]);
  961. }
  962. else if (t.startsWithIgnoreCase ("rotate"))
  963. {
  964. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi), numbers[1], numbers[2]);
  965. }
  966. else if (t.startsWithIgnoreCase ("skewX"))
  967. {
  968. trans = AffineTransform::shear (std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f);
  969. }
  970. else if (t.startsWithIgnoreCase ("skewY"))
  971. {
  972. trans = AffineTransform::shear (0.0f, std::tan (numbers[0] * (float_Pi / 180.0f)));
  973. }
  974. result = trans.followedBy (result);
  975. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  976. }
  977. return result;
  978. }
  979. static void endpointToCentreParameters (const double x1, const double y1,
  980. const double x2, const double y2,
  981. const double angle,
  982. const bool largeArc, const bool sweep,
  983. double& rx, double& ry,
  984. double& centreX, double& centreY,
  985. double& startAngle, double& deltaAngle) noexcept
  986. {
  987. const double midX = (x1 - x2) * 0.5;
  988. const double midY = (y1 - y2) * 0.5;
  989. const double cosAngle = std::cos (angle);
  990. const double sinAngle = std::sin (angle);
  991. const double xp = cosAngle * midX + sinAngle * midY;
  992. const double yp = cosAngle * midY - sinAngle * midX;
  993. const double xp2 = xp * xp;
  994. const double yp2 = yp * yp;
  995. double rx2 = rx * rx;
  996. double ry2 = ry * ry;
  997. const double s = (xp2 / rx2) + (yp2 / ry2);
  998. double c;
  999. if (s <= 1.0)
  1000. {
  1001. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  1002. / (( rx2 * yp2) + (ry2 * xp2))));
  1003. if (largeArc == sweep)
  1004. c = -c;
  1005. }
  1006. else
  1007. {
  1008. const double s2 = std::sqrt (s);
  1009. rx *= s2;
  1010. ry *= s2;
  1011. c = 0;
  1012. }
  1013. const double cpx = ((rx * yp) / ry) * c;
  1014. const double cpy = ((-ry * xp) / rx) * c;
  1015. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  1016. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  1017. const double ux = (xp - cpx) / rx;
  1018. const double uy = (yp - cpy) / ry;
  1019. const double vx = (-xp - cpx) / rx;
  1020. const double vy = (-yp - cpy) / ry;
  1021. const double length = juce_hypot (ux, uy);
  1022. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  1023. if (uy < 0)
  1024. startAngle = -startAngle;
  1025. startAngle += double_Pi * 0.5;
  1026. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  1027. / (length * juce_hypot (vx, vy))));
  1028. if ((ux * vy) - (uy * vx) < 0)
  1029. deltaAngle = -deltaAngle;
  1030. if (sweep)
  1031. {
  1032. if (deltaAngle < 0)
  1033. deltaAngle += double_Pi * 2.0;
  1034. }
  1035. else
  1036. {
  1037. if (deltaAngle > 0)
  1038. deltaAngle -= double_Pi * 2.0;
  1039. }
  1040. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  1041. }
  1042. template <typename OperationType>
  1043. static bool findElementForId (const XmlPath& parent, const String& id, OperationType& op)
  1044. {
  1045. forEachXmlChildElement (*parent, e)
  1046. {
  1047. if (e->compareAttribute ("id", id))
  1048. {
  1049. op (parent.getChild (e));
  1050. return true;
  1051. }
  1052. if (findElementForId (parent.getChild (e), id, op))
  1053. return true;
  1054. }
  1055. return false;
  1056. }
  1057. SVGState& operator= (const SVGState&) JUCE_DELETED_FUNCTION;
  1058. };
  1059. //==============================================================================
  1060. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  1061. {
  1062. SVGState state (&svgDocument);
  1063. return state.parseSVGElement (SVGState::XmlPath (&svgDocument, nullptr));
  1064. }
  1065. Path Drawable::parseSVGPath (const String& svgPath)
  1066. {
  1067. SVGState state (nullptr);
  1068. Path p;
  1069. state.parsePathString (p, svgPath);
  1070. return p;
  1071. }