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.

1732 lines
58KB

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