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.

1731 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. 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 UseTextOp
  61. {
  62. const SVGState* state;
  63. AffineTransform* transform;
  64. Drawable* target;
  65. bool operator() (const XmlPath& xmlPath)
  66. {
  67. target = state->parseText (xmlPath, true, transform);
  68. return target != nullptr;
  69. }
  70. };
  71. struct UseImageOp
  72. {
  73. const SVGState* state;
  74. AffineTransform* transform;
  75. Drawable* target;
  76. bool operator() (const XmlPath& xmlPath)
  77. {
  78. target = state->parseImage (xmlPath, true, transform);
  79. return target != nullptr;
  80. }
  81. };
  82. struct GetClipPathOp
  83. {
  84. SVGState* state;
  85. Drawable* target;
  86. bool operator() (const XmlPath& xmlPath)
  87. {
  88. return state->applyClipPath (*target, xmlPath);
  89. }
  90. };
  91. struct SetGradientStopsOp
  92. {
  93. const SVGState* state;
  94. ColourGradient* gradient;
  95. bool operator() (const XmlPath& xml) const
  96. {
  97. return state->addGradientStopsIn (*gradient, xml);
  98. }
  99. };
  100. struct GetFillTypeOp
  101. {
  102. const SVGState* state;
  103. const Path* path;
  104. float opacity;
  105. FillType fillType;
  106. bool operator() (const XmlPath& xml)
  107. {
  108. if (xml->hasTagNameIgnoringNamespace ("linearGradient")
  109. || xml->hasTagNameIgnoringNamespace ("radialGradient"))
  110. {
  111. fillType = state->getGradientFillType (xml, *path, opacity);
  112. return true;
  113. }
  114. return false;
  115. }
  116. };
  117. //==============================================================================
  118. Drawable* parseSVGElement (const XmlPath& xml)
  119. {
  120. auto drawable = new DrawableComposite();
  121. setCommonAttributes (*drawable, xml);
  122. SVGState newState (*this);
  123. if (xml->hasAttribute ("transform"))
  124. newState.addTransform (xml);
  125. newState.width = getCoordLength (xml->getStringAttribute ("width", String (newState.width)), viewBoxW);
  126. newState.height = getCoordLength (xml->getStringAttribute ("height", String (newState.height)), viewBoxH);
  127. if (newState.width <= 0) newState.width = 100;
  128. if (newState.height <= 0) newState.height = 100;
  129. Point<float> viewboxXY;
  130. if (xml->hasAttribute ("viewBox"))
  131. {
  132. auto viewBoxAtt = xml->getStringAttribute ("viewBox");
  133. auto viewParams = viewBoxAtt.getCharPointer();
  134. Point<float> vwh;
  135. if (parseCoords (viewParams, viewboxXY, true)
  136. && parseCoords (viewParams, vwh, true)
  137. && vwh.x > 0
  138. && vwh.y > 0)
  139. {
  140. newState.viewBoxW = vwh.x;
  141. newState.viewBoxH = vwh.y;
  142. auto placementFlags = parsePlacementFlags (xml->getStringAttribute ("preserveAspectRatio").trim());
  143. if (placementFlags != 0)
  144. newState.transform = RectanglePlacement (placementFlags)
  145. .getTransformToFit (Rectangle<float> (viewboxXY.x, viewboxXY.y, vwh.x, vwh.y),
  146. Rectangle<float> (newState.width, newState.height))
  147. .followedBy (newState.transform);
  148. }
  149. }
  150. else
  151. {
  152. if (viewBoxW == 0.0f) newState.viewBoxW = newState.width;
  153. if (viewBoxH == 0.0f) newState.viewBoxH = newState.height;
  154. }
  155. newState.parseSubElements (xml, *drawable);
  156. drawable->setContentArea (RelativeRectangle (RelativeCoordinate (viewboxXY.x),
  157. RelativeCoordinate (viewboxXY.x + newState.viewBoxW),
  158. RelativeCoordinate (viewboxXY.y),
  159. RelativeCoordinate (viewboxXY.y + newState.viewBoxH)));
  160. drawable->resetBoundingBoxToContentArea();
  161. return drawable;
  162. }
  163. //==============================================================================
  164. void parsePathString (Path& path, const String& pathString) const
  165. {
  166. auto d = pathString.getCharPointer().findEndOfWhitespace();
  167. Point<float> subpathStart, last, last2, p1, p2, p3;
  168. juce_wchar currentCommand = 0, previousCommand = 0;
  169. bool isRelative = true;
  170. bool carryOn = true;
  171. while (! d.isEmpty())
  172. {
  173. if (CharPointer_ASCII ("MmLlHhVvCcSsQqTtAaZz").indexOf (*d) >= 0)
  174. {
  175. currentCommand = d.getAndAdvance();
  176. isRelative = currentCommand >= 'a';
  177. }
  178. switch (currentCommand)
  179. {
  180. case 'M':
  181. case 'm':
  182. case 'L':
  183. case 'l':
  184. if (parseCoordsOrSkip (d, p1, false))
  185. {
  186. if (isRelative)
  187. p1 += last;
  188. if (currentCommand == 'M' || currentCommand == 'm')
  189. {
  190. subpathStart = p1;
  191. path.startNewSubPath (p1);
  192. currentCommand = 'l';
  193. }
  194. else
  195. path.lineTo (p1);
  196. last2 = last;
  197. last = p1;
  198. }
  199. break;
  200. case 'H':
  201. case 'h':
  202. if (parseCoord (d, p1.x, false, true))
  203. {
  204. if (isRelative)
  205. p1.x += last.x;
  206. path.lineTo (p1.x, last.y);
  207. last2.x = last.x;
  208. last.x = p1.x;
  209. }
  210. else
  211. {
  212. ++d;
  213. }
  214. break;
  215. case 'V':
  216. case 'v':
  217. if (parseCoord (d, p1.y, false, false))
  218. {
  219. if (isRelative)
  220. p1.y += last.y;
  221. path.lineTo (last.x, p1.y);
  222. last2.y = last.y;
  223. last.y = p1.y;
  224. }
  225. else
  226. {
  227. ++d;
  228. }
  229. break;
  230. case 'C':
  231. case 'c':
  232. if (parseCoordsOrSkip (d, p1, false)
  233. && parseCoordsOrSkip (d, p2, false)
  234. && parseCoordsOrSkip (d, p3, false))
  235. {
  236. if (isRelative)
  237. {
  238. p1 += last;
  239. p2 += last;
  240. p3 += last;
  241. }
  242. path.cubicTo (p1, p2, p3);
  243. last2 = p2;
  244. last = p3;
  245. }
  246. break;
  247. case 'S':
  248. case 's':
  249. if (parseCoordsOrSkip (d, p1, false)
  250. && parseCoordsOrSkip (d, p3, false))
  251. {
  252. if (isRelative)
  253. {
  254. p1 += last;
  255. p3 += last;
  256. }
  257. p2 = last + (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 = CharPointer_ASCII ("QqTt").indexOf (previousCommand) >= 0 ? last + (last - last2)
  285. : p1;
  286. path.quadraticTo (p2, p1);
  287. last2 = p2;
  288. last = p1;
  289. }
  290. break;
  291. case 'A':
  292. case 'a':
  293. if (parseCoordsOrSkip (d, p1, false))
  294. {
  295. String num;
  296. if (parseNextNumber (d, num, false))
  297. {
  298. const float angle = degreesToRadians (num.getFloatValue());
  299. if (parseNextNumber (d, num, false))
  300. {
  301. const bool largeArc = num.getIntValue() != 0;
  302. if (parseNextNumber (d, num, false))
  303. {
  304. const bool sweep = num.getIntValue() != 0;
  305. if (parseCoordsOrSkip (d, p2, false))
  306. {
  307. if (isRelative)
  308. p2 += last;
  309. if (last != p2)
  310. {
  311. double centreX, centreY, startAngle, deltaAngle;
  312. double rx = p1.x, ry = p1.y;
  313. endpointToCentreParameters (last.x, last.y, p2.x, p2.y,
  314. angle, largeArc, sweep,
  315. rx, ry, centreX, centreY,
  316. startAngle, deltaAngle);
  317. path.addCentredArc ((float) centreX, (float) centreY,
  318. (float) rx, (float) ry,
  319. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  320. false);
  321. path.lineTo (p2);
  322. }
  323. last2 = last;
  324. last = p2;
  325. }
  326. }
  327. }
  328. }
  329. }
  330. break;
  331. case 'Z':
  332. case 'z':
  333. path.closeSubPath();
  334. last = last2 = subpathStart;
  335. d = d.findEndOfWhitespace();
  336. currentCommand = 'M';
  337. break;
  338. default:
  339. carryOn = false;
  340. break;
  341. }
  342. if (! carryOn)
  343. break;
  344. previousCommand = currentCommand;
  345. }
  346. // paths that finish back at their start position often seem to be
  347. // left without a 'z', so need to be closed explicitly..
  348. if (path.getCurrentPosition() == subpathStart)
  349. path.closeSubPath();
  350. }
  351. private:
  352. //==============================================================================
  353. const File originalFile;
  354. const XmlPath topLevelXml;
  355. float width = 512, height = 512, viewBoxW = 0, viewBoxH = 0;
  356. AffineTransform transform;
  357. String cssStyleText;
  358. static bool isNone (const String& s) noexcept
  359. {
  360. return s.equalsIgnoreCase ("none");
  361. }
  362. static void setCommonAttributes (Drawable& d, const XmlPath& xml)
  363. {
  364. auto compID = xml->getStringAttribute ("id");
  365. d.setName (compID);
  366. d.setComponentID (compID);
  367. if (isNone (xml->getStringAttribute ("display")))
  368. d.setVisible (false);
  369. }
  370. //==============================================================================
  371. void parseSubElements (const XmlPath& xml, DrawableComposite& parentDrawable, const bool shouldParseClip = true)
  372. {
  373. forEachXmlChildElement (*xml, e)
  374. {
  375. const XmlPath child (xml.getChild (e));
  376. if (auto* drawable = parseSubElement (child))
  377. {
  378. parentDrawable.addChildComponent (drawable);
  379. if (! isNone (getStyleAttribute (child, "display")))
  380. drawable->setVisible (true);
  381. if (shouldParseClip)
  382. parseClipPath (child, *drawable);
  383. }
  384. }
  385. }
  386. Drawable* parseSubElement (const XmlPath& xml)
  387. {
  388. {
  389. Path path;
  390. if (parsePathElement (xml, path))
  391. return parseShape (xml, path);
  392. }
  393. auto tag = xml->getTagNameWithoutNamespace();
  394. if (tag == "g") return parseGroupElement (xml, true);
  395. if (tag == "svg") return parseSVGElement (xml);
  396. if (tag == "text") return parseText (xml, true);
  397. if (tag == "image") return parseImage (xml, true);
  398. if (tag == "switch") return parseSwitch (xml);
  399. if (tag == "a") return parseLinkElement (xml);
  400. if (tag == "use") return parseUseOther (xml);
  401. if (tag == "style") parseCSSStyle (xml);
  402. if (tag == "defs") parseDefs (xml);
  403. return nullptr;
  404. }
  405. bool parsePathElement (const XmlPath& xml, Path& path) const
  406. {
  407. auto tag = xml->getTagNameWithoutNamespace();
  408. if (tag == "path") { parsePath (xml, path); return true; }
  409. if (tag == "rect") { parseRect (xml, path); return true; }
  410. if (tag == "circle") { parseCircle (xml, path); return true; }
  411. if (tag == "ellipse") { parseEllipse (xml, path); return true; }
  412. if (tag == "line") { parseLine (xml, path); return true; }
  413. if (tag == "polyline") { parsePolygon (xml, true, path); return true; }
  414. if (tag == "polygon") { parsePolygon (xml, false, path); return true; }
  415. if (tag == "use") { return parseUsePath (xml, path); }
  416. return false;
  417. }
  418. DrawableComposite* parseSwitch (const XmlPath& xml)
  419. {
  420. if (auto* group = xml->getChildByName ("g"))
  421. return parseGroupElement (xml.getChild (group), true);
  422. return nullptr;
  423. }
  424. DrawableComposite* parseGroupElement (const XmlPath& xml, bool shouldParseTransform)
  425. {
  426. if (shouldParseTransform && xml->hasAttribute ("transform"))
  427. {
  428. SVGState newState (*this);
  429. newState.addTransform (xml);
  430. return newState.parseGroupElement (xml, false);
  431. }
  432. auto* drawable = new DrawableComposite();
  433. setCommonAttributes (*drawable, xml);
  434. parseSubElements (xml, *drawable);
  435. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  436. return drawable;
  437. }
  438. DrawableComposite* parseLinkElement (const XmlPath& xml)
  439. {
  440. return parseGroupElement (xml, true); // TODO: support for making this clickable
  441. }
  442. //==============================================================================
  443. void parsePath (const XmlPath& xml, Path& path) const
  444. {
  445. parsePathString (path, xml->getStringAttribute ("d"));
  446. if (getStyleAttribute (xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  447. path.setUsingNonZeroWinding (false);
  448. }
  449. void parseRect (const XmlPath& xml, Path& rect) const
  450. {
  451. const bool hasRX = xml->hasAttribute ("rx");
  452. const bool hasRY = xml->hasAttribute ("ry");
  453. if (hasRX || hasRY)
  454. {
  455. float rx = getCoordLength (xml, "rx", viewBoxW);
  456. float ry = getCoordLength (xml, "ry", viewBoxH);
  457. if (! hasRX)
  458. rx = ry;
  459. else if (! hasRY)
  460. ry = rx;
  461. rect.addRoundedRectangle (getCoordLength (xml, "x", viewBoxW),
  462. getCoordLength (xml, "y", viewBoxH),
  463. getCoordLength (xml, "width", viewBoxW),
  464. getCoordLength (xml, "height", viewBoxH),
  465. rx, ry);
  466. }
  467. else
  468. {
  469. rect.addRectangle (getCoordLength (xml, "x", viewBoxW),
  470. getCoordLength (xml, "y", viewBoxH),
  471. getCoordLength (xml, "width", viewBoxW),
  472. getCoordLength (xml, "height", viewBoxH));
  473. }
  474. }
  475. void parseCircle (const XmlPath& xml, Path& circle) const
  476. {
  477. auto cx = getCoordLength (xml, "cx", viewBoxW);
  478. auto cy = getCoordLength (xml, "cy", viewBoxH);
  479. auto radius = getCoordLength (xml, "r", viewBoxW);
  480. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  481. }
  482. void parseEllipse (const XmlPath& xml, Path& ellipse) const
  483. {
  484. auto cx = getCoordLength (xml, "cx", viewBoxW);
  485. auto cy = getCoordLength (xml, "cy", viewBoxH);
  486. auto radiusX = getCoordLength (xml, "rx", viewBoxW);
  487. auto radiusY = getCoordLength (xml, "ry", viewBoxH);
  488. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  489. }
  490. void parseLine (const XmlPath& xml, Path& line) const
  491. {
  492. auto x1 = getCoordLength (xml, "x1", viewBoxW);
  493. auto y1 = getCoordLength (xml, "y1", viewBoxH);
  494. auto x2 = getCoordLength (xml, "x2", viewBoxW);
  495. auto y2 = getCoordLength (xml, "y2", viewBoxH);
  496. line.startNewSubPath (x1, y1);
  497. line.lineTo (x2, y2);
  498. }
  499. void parsePolygon (const XmlPath& xml, const bool isPolyline, Path& path) const
  500. {
  501. auto pointsAtt = xml->getStringAttribute ("points");
  502. auto points = pointsAtt.getCharPointer();
  503. Point<float> p;
  504. if (parseCoords (points, p, true))
  505. {
  506. Point<float> first (p), last;
  507. path.startNewSubPath (first);
  508. while (parseCoords (points, p, true))
  509. {
  510. last = p;
  511. path.lineTo (p);
  512. }
  513. if ((! isPolyline) || first == last)
  514. path.closeSubPath();
  515. }
  516. }
  517. static String getLinkedID (const XmlPath& xml)
  518. {
  519. auto link = xml->getStringAttribute ("xlink:href");
  520. if (link.startsWithChar ('#'))
  521. return link.substring (1);
  522. return {};
  523. }
  524. bool parseUsePath (const XmlPath& xml, Path& path) const
  525. {
  526. auto linkedID = getLinkedID (xml);
  527. if (linkedID.isNotEmpty())
  528. {
  529. UsePathOp op = { this, &path };
  530. return topLevelXml.applyOperationToChildWithID (linkedID, op);
  531. }
  532. return false;
  533. }
  534. Drawable* parseUseOther (const XmlPath& xml) const
  535. {
  536. if (auto* drawableText = parseText (xml, false)) return drawableText;
  537. if (auto* drawableImage = parseImage (xml, false)) return drawableImage;
  538. return nullptr;
  539. }
  540. static String parseURL (const String& str)
  541. {
  542. if (str.startsWithIgnoreCase ("url"))
  543. return str.fromFirstOccurrenceOf ("#", false, false)
  544. .upToLastOccurrenceOf (")", false, false).trim();
  545. return {};
  546. }
  547. //==============================================================================
  548. Drawable* parseShape (const XmlPath& xml, Path& path,
  549. const bool shouldParseTransform = true,
  550. AffineTransform* additonalTransform = nullptr) const
  551. {
  552. if (shouldParseTransform && xml->hasAttribute ("transform"))
  553. {
  554. SVGState newState (*this);
  555. newState.addTransform (xml);
  556. return newState.parseShape (xml, path, false, additonalTransform);
  557. }
  558. auto dp = new DrawablePath();
  559. setCommonAttributes (*dp, xml);
  560. dp->setFill (Colours::transparentBlack);
  561. path.applyTransform (transform);
  562. if (additonalTransform != nullptr)
  563. path.applyTransform (*additonalTransform);
  564. dp->setPath (path);
  565. dp->setFill (getPathFillType (path, xml, "fill",
  566. getStyleAttribute (xml, "fill-opacity"),
  567. getStyleAttribute (xml, "opacity"),
  568. pathContainsClosedSubPath (path) ? Colours::black
  569. : Colours::transparentBlack));
  570. auto strokeType = getStyleAttribute (xml, "stroke");
  571. if (strokeType.isNotEmpty() && ! isNone (strokeType))
  572. {
  573. dp->setStrokeFill (getPathFillType (path, xml, "stroke",
  574. getStyleAttribute (xml, "stroke-opacity"),
  575. getStyleAttribute (xml, "opacity"),
  576. Colours::transparentBlack));
  577. dp->setStrokeType (getStrokeFor (xml));
  578. }
  579. auto strokeDashArray = getStyleAttribute (xml, "stroke-dasharray");
  580. if (strokeDashArray.isNotEmpty())
  581. parseDashArray (strokeDashArray, *dp);
  582. return dp;
  583. }
  584. static bool pathContainsClosedSubPath (const Path& path) noexcept
  585. {
  586. for (Path::Iterator iter (path); iter.next();)
  587. if (iter.elementType == Path::Iterator::closePath)
  588. return true;
  589. return false;
  590. }
  591. void parseDashArray (const String& dashList, DrawablePath& dp) const
  592. {
  593. if (dashList.equalsIgnoreCase ("null") || isNone (dashList))
  594. return;
  595. Array<float> dashLengths;
  596. for (auto t = dashList.getCharPointer();;)
  597. {
  598. float value;
  599. if (! parseCoord (t, value, true, true))
  600. break;
  601. dashLengths.add (value);
  602. t = t.findEndOfWhitespace();
  603. if (*t == ',')
  604. ++t;
  605. }
  606. if (dashLengths.size() > 0)
  607. {
  608. auto* dashes = dashLengths.getRawDataPointer();
  609. for (int i = 0; i < dashLengths.size(); ++i)
  610. {
  611. if (dashes[i] <= 0) // SVG uses zero-length dashes to mean a dotted line
  612. {
  613. if (dashLengths.size() == 1)
  614. return;
  615. const float nonZeroLength = 0.001f;
  616. dashes[i] = nonZeroLength;
  617. const int pairedIndex = i ^ 1;
  618. if (isPositiveAndBelow (pairedIndex, dashLengths.size())
  619. && dashes[pairedIndex] > nonZeroLength)
  620. dashes[pairedIndex] -= nonZeroLength;
  621. }
  622. }
  623. dp.setDashLengths (dashLengths);
  624. }
  625. }
  626. bool parseClipPath (const XmlPath& xml, Drawable& d)
  627. {
  628. const String clipPath (getStyleAttribute (xml, "clip-path"));
  629. if (clipPath.isNotEmpty())
  630. {
  631. auto urlID = parseURL (clipPath);
  632. if (urlID.isNotEmpty())
  633. {
  634. GetClipPathOp op = { this, &d };
  635. return topLevelXml.applyOperationToChildWithID (urlID, op);
  636. }
  637. }
  638. return false;
  639. }
  640. bool applyClipPath (Drawable& target, const XmlPath& xmlPath)
  641. {
  642. if (xmlPath->hasTagNameIgnoringNamespace ("clipPath"))
  643. {
  644. ScopedPointer<DrawableComposite> drawableClipPath (new DrawableComposite());
  645. parseSubElements (xmlPath, *drawableClipPath, false);
  646. if (drawableClipPath->getNumChildComponents() > 0)
  647. {
  648. setCommonAttributes (*drawableClipPath, xmlPath);
  649. target.setClipPath (drawableClipPath.release());
  650. return true;
  651. }
  652. }
  653. return false;
  654. }
  655. bool addGradientStopsIn (ColourGradient& cg, const XmlPath& fillXml) const
  656. {
  657. bool result = false;
  658. if (fillXml.xml != nullptr)
  659. {
  660. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  661. {
  662. auto col = parseColour (fillXml.getChild (e), "stop-color", Colours::black);
  663. auto opacity = getStyleAttribute (fillXml.getChild (e), "stop-opacity", "1");
  664. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  665. double offset = e->getDoubleAttribute ("offset");
  666. if (e->getStringAttribute ("offset").containsChar ('%'))
  667. offset *= 0.01;
  668. cg.addColour (jlimit (0.0, 1.0, offset), col);
  669. result = true;
  670. }
  671. }
  672. return result;
  673. }
  674. FillType getGradientFillType (const XmlPath& fillXml,
  675. const Path& path,
  676. const float opacity) const
  677. {
  678. ColourGradient gradient;
  679. {
  680. auto linkedID = getLinkedID (fillXml);
  681. if (linkedID.isNotEmpty())
  682. {
  683. SetGradientStopsOp op = { this, &gradient, };
  684. topLevelXml.applyOperationToChildWithID (linkedID, op);
  685. }
  686. }
  687. addGradientStopsIn (gradient, fillXml);
  688. if (int numColours = gradient.getNumColours())
  689. {
  690. if (gradient.getColourPosition (0) > 0)
  691. gradient.addColour (0.0, gradient.getColour (0));
  692. if (gradient.getColourPosition (numColours - 1) < 1.0)
  693. gradient.addColour (1.0, gradient.getColour (numColours - 1));
  694. }
  695. else
  696. {
  697. gradient.addColour (0.0, Colours::black);
  698. gradient.addColour (1.0, Colours::black);
  699. }
  700. if (opacity < 1.0f)
  701. gradient.multiplyOpacity (opacity);
  702. jassert (gradient.getNumColours() > 0);
  703. gradient.isRadial = fillXml->hasTagNameIgnoringNamespace ("radialGradient");
  704. float gradientWidth = viewBoxW;
  705. float gradientHeight = viewBoxH;
  706. float dx = 0.0f;
  707. float dy = 0.0f;
  708. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  709. if (! userSpace)
  710. {
  711. auto bounds = path.getBounds();
  712. dx = bounds.getX();
  713. dy = bounds.getY();
  714. gradientWidth = bounds.getWidth();
  715. gradientHeight = bounds.getHeight();
  716. }
  717. if (gradient.isRadial)
  718. {
  719. if (userSpace)
  720. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  721. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  722. else
  723. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  724. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  725. auto radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  726. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  727. //xxx (the fx, fy focal point isn't handled properly here..)
  728. }
  729. else
  730. {
  731. if (userSpace)
  732. {
  733. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  734. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  735. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  736. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  737. }
  738. else
  739. {
  740. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  741. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  742. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  743. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  744. }
  745. if (gradient.point1 == gradient.point2)
  746. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  747. }
  748. FillType type (gradient);
  749. auto gradientTransform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  750. .followedBy (transform);
  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. ScopedPointer<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. const 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. const String base64text = link.substring (indexOfComma + 1).removeCharacters ("\t\n\r ");
  930. if (Base64::convertFromBase64 (imageStream, base64text))
  931. inputStream = 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 = 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. di->setImage (image);
  949. if (additionalTransform != nullptr)
  950. di->setTransform (transform.followedBy (*additionalTransform));
  951. else
  952. di->setTransform (transform);
  953. return di;
  954. }
  955. }
  956. return nullptr;
  957. }
  958. //==============================================================================
  959. void addTransform (const XmlPath& xml)
  960. {
  961. transform = parseTransform (xml->getStringAttribute ("transform"))
  962. .followedBy (transform);
  963. }
  964. //==============================================================================
  965. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  966. {
  967. String number;
  968. if (! parseNextNumber (s, number, allowUnits))
  969. {
  970. value = 0;
  971. return false;
  972. }
  973. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  974. return true;
  975. }
  976. bool parseCoords (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  977. {
  978. return parseCoord (s, p.x, allowUnits, true)
  979. && parseCoord (s, p.y, allowUnits, false);
  980. }
  981. bool parseCoordsOrSkip (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  982. {
  983. if (parseCoords (s, p, allowUnits))
  984. return true;
  985. if (! s.isEmpty()) ++s;
  986. return false;
  987. }
  988. float getCoordLength (const String& s, const float sizeForProportions) const noexcept
  989. {
  990. float n = s.getFloatValue();
  991. const int len = s.length();
  992. if (len > 2)
  993. {
  994. const float dpi = 96.0f;
  995. const juce_wchar n1 = s [len - 2];
  996. const juce_wchar n2 = s [len - 1];
  997. if (n1 == 'i' && n2 == 'n') n *= dpi;
  998. else if (n1 == 'm' && n2 == 'm') n *= dpi / 25.4f;
  999. else if (n1 == 'c' && n2 == 'm') n *= dpi / 2.54f;
  1000. else if (n1 == 'p' && n2 == 'c') n *= 15.0f;
  1001. else if (n2 == '%') n *= 0.01f * sizeForProportions;
  1002. }
  1003. return n;
  1004. }
  1005. float getCoordLength (const XmlPath& xml, const char* attName, const float sizeForProportions) const noexcept
  1006. {
  1007. return getCoordLength (xml->getStringAttribute (attName), sizeForProportions);
  1008. }
  1009. void getCoordList (Array<float>& coords, const String& list, bool allowUnits, const bool isX) const
  1010. {
  1011. auto text = list.getCharPointer();
  1012. float value;
  1013. while (parseCoord (text, value, allowUnits, isX))
  1014. coords.add (value);
  1015. }
  1016. //==============================================================================
  1017. void parseCSSStyle (const XmlPath& xml)
  1018. {
  1019. cssStyleText = xml->getAllSubText() + "\n" + cssStyleText;
  1020. }
  1021. void parseDefs (const XmlPath& xml)
  1022. {
  1023. if (auto* style = xml->getChildByName ("style"))
  1024. parseCSSStyle (xml.getChild (style));
  1025. }
  1026. static String::CharPointerType findStyleItem (String::CharPointerType source, String::CharPointerType name)
  1027. {
  1028. auto nameLength = (int) name.length();
  1029. while (! source.isEmpty())
  1030. {
  1031. if (source.getAndAdvance() == '.'
  1032. && CharacterFunctions::compareIgnoreCaseUpTo (source, name, nameLength) == 0)
  1033. {
  1034. auto endOfName = (source + nameLength).findEndOfWhitespace();
  1035. if (*endOfName == '{')
  1036. return endOfName;
  1037. if (*endOfName == ',')
  1038. return CharacterFunctions::find (endOfName, (juce_wchar) '{');
  1039. }
  1040. }
  1041. return source;
  1042. }
  1043. String getStyleAttribute (const XmlPath& xml, StringRef attributeName, const String& defaultValue = String()) const
  1044. {
  1045. if (xml->hasAttribute (attributeName))
  1046. return xml->getStringAttribute (attributeName, defaultValue);
  1047. auto styleAtt = xml->getStringAttribute ("style");
  1048. if (styleAtt.isNotEmpty())
  1049. {
  1050. auto value = getAttributeFromStyleList (styleAtt, attributeName, {});
  1051. if (value.isNotEmpty())
  1052. return value;
  1053. }
  1054. else if (xml->hasAttribute ("class"))
  1055. {
  1056. for (auto i = cssStyleText.getCharPointer();;)
  1057. {
  1058. auto openBrace = findStyleItem (i, xml->getStringAttribute ("class").getCharPointer());
  1059. if (openBrace.isEmpty())
  1060. break;
  1061. auto closeBrace = CharacterFunctions::find (openBrace, (juce_wchar) '}');
  1062. if (closeBrace.isEmpty())
  1063. break;
  1064. auto value = getAttributeFromStyleList (String (openBrace + 1, closeBrace),
  1065. attributeName, defaultValue);
  1066. if (value.isNotEmpty())
  1067. return value;
  1068. i = closeBrace + 1;
  1069. }
  1070. }
  1071. if (xml.parent != nullptr)
  1072. return getStyleAttribute (*xml.parent, attributeName, defaultValue);
  1073. return defaultValue;
  1074. }
  1075. String getInheritedAttribute (const XmlPath& xml, StringRef attributeName) const
  1076. {
  1077. if (xml->hasAttribute (attributeName))
  1078. return xml->getStringAttribute (attributeName);
  1079. if (xml.parent != nullptr)
  1080. return getInheritedAttribute (*xml.parent, attributeName);
  1081. return {};
  1082. }
  1083. static int parsePlacementFlags (const String& align) noexcept
  1084. {
  1085. if (align.isEmpty())
  1086. return 0;
  1087. if (isNone (align))
  1088. return RectanglePlacement::stretchToFit;
  1089. return (align.containsIgnoreCase ("slice") ? RectanglePlacement::fillDestination : 0)
  1090. | (align.containsIgnoreCase ("xMin") ? RectanglePlacement::xLeft
  1091. : (align.containsIgnoreCase ("xMax") ? RectanglePlacement::xRight
  1092. : RectanglePlacement::xMid))
  1093. | (align.containsIgnoreCase ("yMin") ? RectanglePlacement::yTop
  1094. : (align.containsIgnoreCase ("yMax") ? RectanglePlacement::yBottom
  1095. : RectanglePlacement::yMid));
  1096. }
  1097. //==============================================================================
  1098. static bool isIdentifierChar (const juce_wchar c)
  1099. {
  1100. return CharacterFunctions::isLetter (c) || c == '-';
  1101. }
  1102. static String getAttributeFromStyleList (const String& list, StringRef attributeName, const String& defaultValue)
  1103. {
  1104. int i = 0;
  1105. for (;;)
  1106. {
  1107. i = list.indexOf (i, attributeName);
  1108. if (i < 0)
  1109. break;
  1110. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  1111. && ! isIdentifierChar (list [i + attributeName.length()]))
  1112. {
  1113. i = list.indexOfChar (i, ':');
  1114. if (i < 0)
  1115. break;
  1116. int end = list.indexOfChar (i, ';');
  1117. if (end < 0)
  1118. end = 0x7ffff;
  1119. return list.substring (i + 1, end).trim();
  1120. }
  1121. ++i;
  1122. }
  1123. return defaultValue;
  1124. }
  1125. //==============================================================================
  1126. static bool isStartOfNumber (juce_wchar c) noexcept
  1127. {
  1128. return CharacterFunctions::isDigit (c) || c == '-' || c == '+';
  1129. }
  1130. static bool parseNextNumber (String::CharPointerType& text, String& value, const bool allowUnits)
  1131. {
  1132. String::CharPointerType s (text);
  1133. while (s.isWhitespace() || *s == ',')
  1134. ++s;
  1135. auto start = s;
  1136. if (isStartOfNumber (*s))
  1137. ++s;
  1138. while (s.isDigit())
  1139. ++s;
  1140. if (*s == '.')
  1141. {
  1142. ++s;
  1143. while (s.isDigit())
  1144. ++s;
  1145. }
  1146. if ((*s == 'e' || *s == 'E') && isStartOfNumber (s[1]))
  1147. {
  1148. s += 2;
  1149. while (s.isDigit())
  1150. ++s;
  1151. }
  1152. if (allowUnits)
  1153. while (s.isLetter())
  1154. ++s;
  1155. if (s == start)
  1156. {
  1157. text = s;
  1158. return false;
  1159. }
  1160. value = String (start, s);
  1161. while (s.isWhitespace() || *s == ',')
  1162. ++s;
  1163. text = s;
  1164. return true;
  1165. }
  1166. //==============================================================================
  1167. Colour parseColour (const XmlPath& xml, StringRef attributeName, const Colour defaultColour) const
  1168. {
  1169. auto text = getStyleAttribute (xml, attributeName);
  1170. if (text.startsWithChar ('#'))
  1171. {
  1172. uint32 hex[6] = { 0 };
  1173. int numChars = 0;
  1174. auto s = text.getCharPointer();
  1175. while (numChars < 6)
  1176. {
  1177. auto hexValue = CharacterFunctions::getHexDigitValue (*++s);
  1178. if (hexValue >= 0)
  1179. hex [numChars++] = (uint32) hexValue;
  1180. else
  1181. break;
  1182. }
  1183. if (numChars <= 3)
  1184. return Colour ((uint8) (hex[0] * 0x11),
  1185. (uint8) (hex[1] * 0x11),
  1186. (uint8) (hex[2] * 0x11));
  1187. return Colour ((uint8) ((hex[0] << 4) + hex[1]),
  1188. (uint8) ((hex[2] << 4) + hex[3]),
  1189. (uint8) ((hex[4] << 4) + hex[5]));
  1190. }
  1191. if (text.startsWith ("rgb"))
  1192. {
  1193. auto openBracket = text.indexOfChar ('(');
  1194. auto closeBracket = text.indexOfChar (openBracket, ')');
  1195. if (openBracket >= 3 && closeBracket > openBracket)
  1196. {
  1197. StringArray tokens;
  1198. tokens.addTokens (text.substring (openBracket + 1, closeBracket), ",", "");
  1199. tokens.trim();
  1200. tokens.removeEmptyStrings();
  1201. if (tokens[0].containsChar ('%'))
  1202. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  1203. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  1204. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  1205. return Colour ((uint8) tokens[0].getIntValue(),
  1206. (uint8) tokens[1].getIntValue(),
  1207. (uint8) tokens[2].getIntValue());
  1208. }
  1209. }
  1210. if (text == "inherit")
  1211. {
  1212. for (const XmlPath* p = xml.parent; p != nullptr; p = p->parent)
  1213. if (getStyleAttribute (*p, attributeName).isNotEmpty())
  1214. return parseColour (*p, attributeName, defaultColour);
  1215. }
  1216. return Colours::findColourForName (text, defaultColour);
  1217. }
  1218. static AffineTransform parseTransform (String t)
  1219. {
  1220. AffineTransform result;
  1221. while (t.isNotEmpty())
  1222. {
  1223. StringArray tokens;
  1224. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  1225. .upToFirstOccurrenceOf (")", false, false),
  1226. ", ", "");
  1227. tokens.removeEmptyStrings (true);
  1228. float numbers[6];
  1229. for (int i = 0; i < numElementsInArray (numbers); ++i)
  1230. numbers[i] = tokens[i].getFloatValue();
  1231. AffineTransform trans;
  1232. if (t.startsWithIgnoreCase ("matrix"))
  1233. {
  1234. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  1235. numbers[1], numbers[3], numbers[5]);
  1236. }
  1237. else if (t.startsWithIgnoreCase ("translate"))
  1238. {
  1239. trans = AffineTransform::translation (numbers[0], numbers[1]);
  1240. }
  1241. else if (t.startsWithIgnoreCase ("scale"))
  1242. {
  1243. trans = AffineTransform::scale (numbers[0], numbers[tokens.size() > 1 ? 1 : 0]);
  1244. }
  1245. else if (t.startsWithIgnoreCase ("rotate"))
  1246. {
  1247. trans = AffineTransform::rotation (degreesToRadians (numbers[0]), numbers[1], numbers[2]);
  1248. }
  1249. else if (t.startsWithIgnoreCase ("skewX"))
  1250. {
  1251. trans = AffineTransform::shear (std::tan (degreesToRadians (numbers[0])), 0.0f);
  1252. }
  1253. else if (t.startsWithIgnoreCase ("skewY"))
  1254. {
  1255. trans = AffineTransform::shear (0.0f, std::tan (degreesToRadians (numbers[0])));
  1256. }
  1257. result = trans.followedBy (result);
  1258. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  1259. }
  1260. return result;
  1261. }
  1262. static void endpointToCentreParameters (const double x1, const double y1,
  1263. const double x2, const double y2,
  1264. const double angle,
  1265. const bool largeArc, const bool sweep,
  1266. double& rx, double& ry,
  1267. double& centreX, double& centreY,
  1268. double& startAngle, double& deltaAngle) noexcept
  1269. {
  1270. const double midX = (x1 - x2) * 0.5;
  1271. const double midY = (y1 - y2) * 0.5;
  1272. const double cosAngle = std::cos (angle);
  1273. const double sinAngle = std::sin (angle);
  1274. const double xp = cosAngle * midX + sinAngle * midY;
  1275. const double yp = cosAngle * midY - sinAngle * midX;
  1276. const double xp2 = xp * xp;
  1277. const double yp2 = yp * yp;
  1278. double rx2 = rx * rx;
  1279. double ry2 = ry * ry;
  1280. const double s = (xp2 / rx2) + (yp2 / ry2);
  1281. double c;
  1282. if (s <= 1.0)
  1283. {
  1284. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  1285. / (( rx2 * yp2) + (ry2 * xp2))));
  1286. if (largeArc == sweep)
  1287. c = -c;
  1288. }
  1289. else
  1290. {
  1291. const double s2 = std::sqrt (s);
  1292. rx *= s2;
  1293. ry *= s2;
  1294. c = 0;
  1295. }
  1296. const double cpx = ((rx * yp) / ry) * c;
  1297. const double cpy = ((-ry * xp) / rx) * c;
  1298. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  1299. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  1300. const double ux = (xp - cpx) / rx;
  1301. const double uy = (yp - cpy) / ry;
  1302. const double vx = (-xp - cpx) / rx;
  1303. const double vy = (-yp - cpy) / ry;
  1304. const double length = juce_hypot (ux, uy);
  1305. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  1306. if (uy < 0)
  1307. startAngle = -startAngle;
  1308. startAngle += double_Pi * 0.5;
  1309. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  1310. / (length * juce_hypot (vx, vy))));
  1311. if ((ux * vy) - (uy * vx) < 0)
  1312. deltaAngle = -deltaAngle;
  1313. if (sweep)
  1314. {
  1315. if (deltaAngle < 0)
  1316. deltaAngle += double_Pi * 2.0;
  1317. }
  1318. else
  1319. {
  1320. if (deltaAngle > 0)
  1321. deltaAngle -= double_Pi * 2.0;
  1322. }
  1323. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  1324. }
  1325. SVGState& operator= (const SVGState&) JUCE_DELETED_FUNCTION;
  1326. };
  1327. //==============================================================================
  1328. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  1329. {
  1330. if (! svgDocument.hasTagNameIgnoringNamespace ("svg"))
  1331. return nullptr;
  1332. SVGState state (&svgDocument);
  1333. return state.parseSVGElement (SVGState::XmlPath (&svgDocument, nullptr));
  1334. }
  1335. Drawable* Drawable::createFromSVGFile (const File& svgFile)
  1336. {
  1337. XmlDocument doc (svgFile);
  1338. ScopedPointer<XmlElement> outer (doc.getDocumentElement (true));
  1339. if (outer != nullptr && outer->hasTagName ("svg"))
  1340. {
  1341. ScopedPointer<XmlElement> svgDocument (doc.getDocumentElement());
  1342. if (svgDocument != nullptr)
  1343. {
  1344. SVGState state (svgDocument, svgFile);
  1345. return state.parseSVGElement (SVGState::XmlPath (svgDocument, nullptr));
  1346. }
  1347. }
  1348. return nullptr;
  1349. }
  1350. Path Drawable::parseSVGPath (const String& svgPath)
  1351. {
  1352. SVGState state (nullptr);
  1353. Path p;
  1354. state.parsePathString (p, svgPath);
  1355. return p;
  1356. }