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.

1483 lines
52KB

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