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.

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