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.

1750 lines
59KB

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