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.

1736 lines
58KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. class SVGState
  22. {
  23. public:
  24. //==============================================================================
  25. explicit SVGState (const XmlElement* topLevel, const File& svgFile = {})
  26. : originalFile (svgFile), topLevelXml (topLevel, nullptr)
  27. {
  28. }
  29. struct XmlPath
  30. {
  31. XmlPath (const XmlElement* e, const XmlPath* p) noexcept : xml (e), parent (p) {}
  32. const XmlElement& operator*() const noexcept { jassert (xml != nullptr); return *xml; }
  33. const XmlElement* operator->() const noexcept { return xml; }
  34. XmlPath getChild (const XmlElement* e) const noexcept { return XmlPath (e, this); }
  35. template <typename OperationType>
  36. bool applyOperationToChildWithID (const String& id, OperationType& op) const
  37. {
  38. forEachXmlChildElement (*xml, e)
  39. {
  40. XmlPath child (e, this);
  41. if (e->compareAttribute ("id", id)
  42. && ! child->hasTagName ("defs"))
  43. return op (child);
  44. if (child.applyOperationToChildWithID (id, op))
  45. return true;
  46. }
  47. return false;
  48. }
  49. const XmlElement* xml;
  50. const XmlPath* parent;
  51. };
  52. //==============================================================================
  53. struct UsePathOp
  54. {
  55. const SVGState* state;
  56. Path* targetPath;
  57. bool operator() (const XmlPath& xmlPath) const
  58. {
  59. return state->parsePathElement (xmlPath, *targetPath);
  60. }
  61. };
  62. struct UseTextOp
  63. {
  64. const SVGState* state;
  65. AffineTransform* transform;
  66. Drawable* target;
  67. bool operator() (const XmlPath& xmlPath)
  68. {
  69. target = state->parseText (xmlPath, true, transform);
  70. return target != nullptr;
  71. }
  72. };
  73. struct UseImageOp
  74. {
  75. const SVGState* state;
  76. AffineTransform* transform;
  77. Drawable* target;
  78. bool operator() (const XmlPath& xmlPath)
  79. {
  80. target = state->parseImage (xmlPath, true, transform);
  81. return target != nullptr;
  82. }
  83. };
  84. struct GetClipPathOp
  85. {
  86. SVGState* state;
  87. Drawable* target;
  88. bool operator() (const XmlPath& xmlPath)
  89. {
  90. return state->applyClipPath (*target, xmlPath);
  91. }
  92. };
  93. struct SetGradientStopsOp
  94. {
  95. const SVGState* state;
  96. ColourGradient* gradient;
  97. bool operator() (const XmlPath& xml) const
  98. {
  99. return state->addGradientStopsIn (*gradient, xml);
  100. }
  101. };
  102. struct GetFillTypeOp
  103. {
  104. const SVGState* state;
  105. const Path* path;
  106. float opacity;
  107. FillType fillType;
  108. bool operator() (const XmlPath& xml)
  109. {
  110. if (xml->hasTagNameIgnoringNamespace ("linearGradient")
  111. || xml->hasTagNameIgnoringNamespace ("radialGradient"))
  112. {
  113. fillType = state->getGradientFillType (xml, *path, opacity);
  114. return true;
  115. }
  116. return false;
  117. }
  118. };
  119. //==============================================================================
  120. Drawable* parseSVGElement (const XmlPath& xml)
  121. {
  122. auto drawable = new DrawableComposite();
  123. setCommonAttributes (*drawable, xml);
  124. SVGState newState (*this);
  125. if (xml->hasAttribute ("transform"))
  126. newState.addTransform (xml);
  127. newState.width = getCoordLength (xml->getStringAttribute ("width", String (newState.width)), viewBoxW);
  128. newState.height = getCoordLength (xml->getStringAttribute ("height", String (newState.height)), viewBoxH);
  129. if (newState.width <= 0) newState.width = 100;
  130. if (newState.height <= 0) newState.height = 100;
  131. Point<float> viewboxXY;
  132. if (xml->hasAttribute ("viewBox"))
  133. {
  134. auto viewBoxAtt = xml->getStringAttribute ("viewBox");
  135. auto viewParams = viewBoxAtt.getCharPointer();
  136. Point<float> vwh;
  137. if (parseCoords (viewParams, viewboxXY, true)
  138. && parseCoords (viewParams, vwh, true)
  139. && vwh.x > 0
  140. && vwh.y > 0)
  141. {
  142. newState.viewBoxW = vwh.x;
  143. newState.viewBoxH = vwh.y;
  144. auto placementFlags = parsePlacementFlags (xml->getStringAttribute ("preserveAspectRatio").trim());
  145. if (placementFlags != 0)
  146. newState.transform = RectanglePlacement (placementFlags)
  147. .getTransformToFit (Rectangle<float> (viewboxXY.x, viewboxXY.y, vwh.x, vwh.y),
  148. Rectangle<float> (newState.width, newState.height))
  149. .followedBy (newState.transform);
  150. }
  151. }
  152. else
  153. {
  154. if (viewBoxW == 0.0f) newState.viewBoxW = newState.width;
  155. if (viewBoxH == 0.0f) newState.viewBoxH = newState.height;
  156. }
  157. newState.parseSubElements (xml, *drawable);
  158. drawable->setContentArea ({ viewboxXY.x, viewboxXY.y, newState.viewBoxW, newState.viewBoxH });
  159. drawable->resetBoundingBoxToContentArea();
  160. return drawable;
  161. }
  162. //==============================================================================
  163. void parsePathString (Path& path, const String& pathString) const
  164. {
  165. auto d = pathString.getCharPointer().findEndOfWhitespace();
  166. Point<float> subpathStart, last, last2, p1, p2, p3;
  167. juce_wchar currentCommand = 0, previousCommand = 0;
  168. bool isRelative = true;
  169. bool carryOn = true;
  170. while (! d.isEmpty())
  171. {
  172. if (CharPointer_ASCII ("MmLlHhVvCcSsQqTtAaZz").indexOf (*d) >= 0)
  173. {
  174. currentCommand = d.getAndAdvance();
  175. isRelative = currentCommand >= 'a';
  176. }
  177. switch (currentCommand)
  178. {
  179. case 'M':
  180. case 'm':
  181. case 'L':
  182. case 'l':
  183. if (parseCoordsOrSkip (d, p1, false))
  184. {
  185. if (isRelative)
  186. p1 += last;
  187. if (currentCommand == 'M' || currentCommand == 'm')
  188. {
  189. subpathStart = p1;
  190. path.startNewSubPath (p1);
  191. currentCommand = 'l';
  192. }
  193. else
  194. path.lineTo (p1);
  195. last2 = last = p1;
  196. }
  197. break;
  198. case 'H':
  199. case 'h':
  200. if (parseCoord (d, p1.x, false, true))
  201. {
  202. if (isRelative)
  203. p1.x += last.x;
  204. path.lineTo (p1.x, last.y);
  205. last2.x = last.x;
  206. last.x = p1.x;
  207. }
  208. else
  209. {
  210. ++d;
  211. }
  212. break;
  213. case 'V':
  214. case 'v':
  215. if (parseCoord (d, p1.y, false, false))
  216. {
  217. if (isRelative)
  218. p1.y += last.y;
  219. path.lineTo (last.x, p1.y);
  220. last2.y = last.y;
  221. last.y = p1.y;
  222. }
  223. else
  224. {
  225. ++d;
  226. }
  227. break;
  228. case 'C':
  229. case 'c':
  230. if (parseCoordsOrSkip (d, p1, false)
  231. && parseCoordsOrSkip (d, p2, false)
  232. && parseCoordsOrSkip (d, p3, false))
  233. {
  234. if (isRelative)
  235. {
  236. p1 += last;
  237. p2 += last;
  238. p3 += last;
  239. }
  240. path.cubicTo (p1, p2, p3);
  241. last2 = p2;
  242. last = p3;
  243. }
  244. break;
  245. case 'S':
  246. case 's':
  247. if (parseCoordsOrSkip (d, p1, false)
  248. && parseCoordsOrSkip (d, p3, false))
  249. {
  250. if (isRelative)
  251. {
  252. p1 += last;
  253. p3 += last;
  254. }
  255. p2 = last + (last - last2);
  256. path.cubicTo (p2, p1, p3);
  257. last2 = p1;
  258. last = p3;
  259. }
  260. break;
  261. case 'Q':
  262. case 'q':
  263. if (parseCoordsOrSkip (d, p1, false)
  264. && parseCoordsOrSkip (d, p2, false))
  265. {
  266. if (isRelative)
  267. {
  268. p1 += last;
  269. p2 += last;
  270. }
  271. path.quadraticTo (p1, p2);
  272. last2 = p1;
  273. last = p2;
  274. }
  275. break;
  276. case 'T':
  277. case 't':
  278. if (parseCoordsOrSkip (d, p1, false))
  279. {
  280. if (isRelative)
  281. p1 += last;
  282. p2 = CharPointer_ASCII ("QqTt").indexOf (previousCommand) >= 0 ? last + (last - last2)
  283. : p1;
  284. path.quadraticTo (p2, p1);
  285. last2 = p2;
  286. last = p1;
  287. }
  288. break;
  289. case 'A':
  290. case 'a':
  291. if (parseCoordsOrSkip (d, p1, false))
  292. {
  293. String num;
  294. if (parseNextNumber (d, num, false))
  295. {
  296. const float angle = degreesToRadians (num.getFloatValue());
  297. if (parseNextNumber (d, num, false))
  298. {
  299. const bool largeArc = num.getIntValue() != 0;
  300. if (parseNextNumber (d, num, false))
  301. {
  302. const bool sweep = num.getIntValue() != 0;
  303. if (parseCoordsOrSkip (d, p2, false))
  304. {
  305. if (isRelative)
  306. p2 += last;
  307. if (last != p2)
  308. {
  309. double centreX, centreY, startAngle, deltaAngle;
  310. double rx = p1.x, ry = p1.y;
  311. endpointToCentreParameters (last.x, last.y, p2.x, p2.y,
  312. angle, largeArc, sweep,
  313. rx, ry, centreX, centreY,
  314. startAngle, deltaAngle);
  315. path.addCentredArc ((float) centreX, (float) centreY,
  316. (float) rx, (float) ry,
  317. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  318. false);
  319. path.lineTo (p2);
  320. }
  321. last2 = last;
  322. last = p2;
  323. }
  324. }
  325. }
  326. }
  327. }
  328. break;
  329. case 'Z':
  330. case 'z':
  331. path.closeSubPath();
  332. last = last2 = subpathStart;
  333. d = d.findEndOfWhitespace();
  334. currentCommand = 'M';
  335. break;
  336. default:
  337. carryOn = false;
  338. break;
  339. }
  340. if (! carryOn)
  341. break;
  342. previousCommand = currentCommand;
  343. }
  344. // paths that finish back at their start position often seem to be
  345. // left without a 'z', so need to be closed explicitly..
  346. if (path.getCurrentPosition() == subpathStart)
  347. path.closeSubPath();
  348. }
  349. private:
  350. //==============================================================================
  351. const File originalFile;
  352. const XmlPath topLevelXml;
  353. float width = 512, height = 512, viewBoxW = 0, viewBoxH = 0;
  354. AffineTransform transform;
  355. String cssStyleText;
  356. static bool isNone (const String& s) noexcept
  357. {
  358. return s.equalsIgnoreCase ("none");
  359. }
  360. static void setCommonAttributes (Drawable& d, const XmlPath& xml)
  361. {
  362. auto compID = xml->getStringAttribute ("id");
  363. d.setName (compID);
  364. d.setComponentID (compID);
  365. if (isNone (xml->getStringAttribute ("display")))
  366. d.setVisible (false);
  367. }
  368. //==============================================================================
  369. void parseSubElements (const XmlPath& xml, DrawableComposite& parentDrawable, const bool shouldParseClip = true)
  370. {
  371. forEachXmlChildElement (*xml, e)
  372. {
  373. const XmlPath child (xml.getChild (e));
  374. if (auto* drawable = parseSubElement (child))
  375. {
  376. parentDrawable.addChildComponent (drawable);
  377. if (! isNone (getStyleAttribute (child, "display")))
  378. drawable->setVisible (true);
  379. if (shouldParseClip)
  380. parseClipPath (child, *drawable);
  381. }
  382. }
  383. }
  384. Drawable* parseSubElement (const XmlPath& xml)
  385. {
  386. {
  387. Path path;
  388. if (parsePathElement (xml, path))
  389. return parseShape (xml, path);
  390. }
  391. auto tag = xml->getTagNameWithoutNamespace();
  392. if (tag == "g") return parseGroupElement (xml, true);
  393. if (tag == "svg") return parseSVGElement (xml);
  394. if (tag == "text") return parseText (xml, true);
  395. if (tag == "image") return parseImage (xml, true);
  396. if (tag == "switch") return parseSwitch (xml);
  397. if (tag == "a") return parseLinkElement (xml);
  398. if (tag == "use") return parseUseOther (xml);
  399. if (tag == "style") parseCSSStyle (xml);
  400. if (tag == "defs") parseDefs (xml);
  401. return nullptr;
  402. }
  403. bool parsePathElement (const XmlPath& xml, Path& path) const
  404. {
  405. auto tag = xml->getTagNameWithoutNamespace();
  406. if (tag == "path") { parsePath (xml, path); return true; }
  407. if (tag == "rect") { parseRect (xml, path); return true; }
  408. if (tag == "circle") { parseCircle (xml, path); return true; }
  409. if (tag == "ellipse") { parseEllipse (xml, path); return true; }
  410. if (tag == "line") { parseLine (xml, path); return true; }
  411. if (tag == "polyline") { parsePolygon (xml, true, path); return true; }
  412. if (tag == "polygon") { parsePolygon (xml, false, path); return true; }
  413. if (tag == "use") { return parseUsePath (xml, path); }
  414. return false;
  415. }
  416. DrawableComposite* parseSwitch (const XmlPath& xml)
  417. {
  418. if (auto* group = xml->getChildByName ("g"))
  419. return parseGroupElement (xml.getChild (group), true);
  420. return nullptr;
  421. }
  422. DrawableComposite* parseGroupElement (const XmlPath& xml, bool shouldParseTransform)
  423. {
  424. if (shouldParseTransform && xml->hasAttribute ("transform"))
  425. {
  426. SVGState newState (*this);
  427. newState.addTransform (xml);
  428. return newState.parseGroupElement (xml, false);
  429. }
  430. auto* drawable = new DrawableComposite();
  431. setCommonAttributes (*drawable, xml);
  432. parseSubElements (xml, *drawable);
  433. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  434. return drawable;
  435. }
  436. DrawableComposite* parseLinkElement (const XmlPath& xml)
  437. {
  438. return parseGroupElement (xml, true); // TODO: support for making this clickable
  439. }
  440. //==============================================================================
  441. void parsePath (const XmlPath& xml, Path& path) const
  442. {
  443. parsePathString (path, xml->getStringAttribute ("d"));
  444. if (getStyleAttribute (xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  445. path.setUsingNonZeroWinding (false);
  446. }
  447. void parseRect (const XmlPath& xml, Path& rect) const
  448. {
  449. const bool hasRX = xml->hasAttribute ("rx");
  450. const bool hasRY = xml->hasAttribute ("ry");
  451. if (hasRX || hasRY)
  452. {
  453. float rx = getCoordLength (xml, "rx", viewBoxW);
  454. float ry = getCoordLength (xml, "ry", viewBoxH);
  455. if (! hasRX)
  456. rx = ry;
  457. else if (! hasRY)
  458. ry = rx;
  459. rect.addRoundedRectangle (getCoordLength (xml, "x", viewBoxW),
  460. getCoordLength (xml, "y", viewBoxH),
  461. getCoordLength (xml, "width", viewBoxW),
  462. getCoordLength (xml, "height", viewBoxH),
  463. rx, ry);
  464. }
  465. else
  466. {
  467. rect.addRectangle (getCoordLength (xml, "x", viewBoxW),
  468. getCoordLength (xml, "y", viewBoxH),
  469. getCoordLength (xml, "width", viewBoxW),
  470. getCoordLength (xml, "height", viewBoxH));
  471. }
  472. }
  473. void parseCircle (const XmlPath& xml, Path& circle) const
  474. {
  475. auto cx = getCoordLength (xml, "cx", viewBoxW);
  476. auto cy = getCoordLength (xml, "cy", viewBoxH);
  477. auto radius = getCoordLength (xml, "r", viewBoxW);
  478. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  479. }
  480. void parseEllipse (const XmlPath& xml, Path& ellipse) const
  481. {
  482. auto cx = getCoordLength (xml, "cx", viewBoxW);
  483. auto cy = getCoordLength (xml, "cy", viewBoxH);
  484. auto radiusX = getCoordLength (xml, "rx", viewBoxW);
  485. auto radiusY = getCoordLength (xml, "ry", viewBoxH);
  486. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  487. }
  488. void parseLine (const XmlPath& xml, Path& line) const
  489. {
  490. auto x1 = getCoordLength (xml, "x1", viewBoxW);
  491. auto y1 = getCoordLength (xml, "y1", viewBoxH);
  492. auto x2 = getCoordLength (xml, "x2", viewBoxW);
  493. auto y2 = getCoordLength (xml, "y2", viewBoxH);
  494. line.startNewSubPath (x1, y1);
  495. line.lineTo (x2, y2);
  496. }
  497. void parsePolygon (const XmlPath& xml, const bool isPolyline, Path& path) const
  498. {
  499. auto pointsAtt = xml->getStringAttribute ("points");
  500. auto points = pointsAtt.getCharPointer();
  501. Point<float> p;
  502. if (parseCoords (points, p, true))
  503. {
  504. Point<float> first (p), last;
  505. path.startNewSubPath (first);
  506. while (parseCoords (points, p, true))
  507. {
  508. last = p;
  509. path.lineTo (p);
  510. }
  511. if ((! isPolyline) || first == last)
  512. path.closeSubPath();
  513. }
  514. }
  515. static String getLinkedID (const XmlPath& xml)
  516. {
  517. auto link = xml->getStringAttribute ("xlink:href");
  518. if (link.startsWithChar ('#'))
  519. return link.substring (1);
  520. return {};
  521. }
  522. bool parseUsePath (const XmlPath& xml, Path& path) const
  523. {
  524. auto linkedID = getLinkedID (xml);
  525. if (linkedID.isNotEmpty())
  526. {
  527. UsePathOp op = { this, &path };
  528. return topLevelXml.applyOperationToChildWithID (linkedID, op);
  529. }
  530. return false;
  531. }
  532. Drawable* parseUseOther (const XmlPath& xml) const
  533. {
  534. if (auto* drawableText = parseText (xml, false)) return drawableText;
  535. if (auto* drawableImage = parseImage (xml, false)) return drawableImage;
  536. return nullptr;
  537. }
  538. static String parseURL (const String& str)
  539. {
  540. if (str.startsWithIgnoreCase ("url"))
  541. return str.fromFirstOccurrenceOf ("#", false, false)
  542. .upToLastOccurrenceOf (")", false, false).trim();
  543. return {};
  544. }
  545. //==============================================================================
  546. Drawable* parseShape (const XmlPath& xml, Path& path,
  547. const bool shouldParseTransform = true,
  548. AffineTransform* additonalTransform = nullptr) const
  549. {
  550. if (shouldParseTransform && xml->hasAttribute ("transform"))
  551. {
  552. SVGState newState (*this);
  553. newState.addTransform (xml);
  554. return newState.parseShape (xml, path, false, additonalTransform);
  555. }
  556. auto dp = new DrawablePath();
  557. setCommonAttributes (*dp, xml);
  558. dp->setFill (Colours::transparentBlack);
  559. path.applyTransform (transform);
  560. if (additonalTransform != nullptr)
  561. path.applyTransform (*additonalTransform);
  562. dp->setPath (path);
  563. dp->setFill (getPathFillType (path, xml, "fill",
  564. getStyleAttribute (xml, "fill-opacity"),
  565. getStyleAttribute (xml, "opacity"),
  566. pathContainsClosedSubPath (path) ? Colours::black
  567. : Colours::transparentBlack));
  568. auto strokeType = getStyleAttribute (xml, "stroke");
  569. if (strokeType.isNotEmpty() && ! isNone (strokeType))
  570. {
  571. dp->setStrokeFill (getPathFillType (path, xml, "stroke",
  572. getStyleAttribute (xml, "stroke-opacity"),
  573. getStyleAttribute (xml, "opacity"),
  574. Colours::transparentBlack));
  575. dp->setStrokeType (getStrokeFor (xml));
  576. }
  577. auto strokeDashArray = getStyleAttribute (xml, "stroke-dasharray");
  578. if (strokeDashArray.isNotEmpty())
  579. parseDashArray (strokeDashArray, *dp);
  580. return dp;
  581. }
  582. static bool pathContainsClosedSubPath (const Path& path) noexcept
  583. {
  584. for (Path::Iterator iter (path); iter.next();)
  585. if (iter.elementType == Path::Iterator::closePath)
  586. return true;
  587. return false;
  588. }
  589. void parseDashArray (const String& dashList, DrawablePath& dp) const
  590. {
  591. if (dashList.equalsIgnoreCase ("null") || isNone (dashList))
  592. return;
  593. Array<float> dashLengths;
  594. for (auto t = dashList.getCharPointer();;)
  595. {
  596. float value;
  597. if (! parseCoord (t, value, true, true))
  598. break;
  599. dashLengths.add (value);
  600. t = t.findEndOfWhitespace();
  601. if (*t == ',')
  602. ++t;
  603. }
  604. if (dashLengths.size() > 0)
  605. {
  606. auto* dashes = dashLengths.getRawDataPointer();
  607. for (int i = 0; i < dashLengths.size(); ++i)
  608. {
  609. if (dashes[i] <= 0) // SVG uses zero-length dashes to mean a dotted line
  610. {
  611. if (dashLengths.size() == 1)
  612. return;
  613. const float nonZeroLength = 0.001f;
  614. dashes[i] = nonZeroLength;
  615. const int pairedIndex = i ^ 1;
  616. if (isPositiveAndBelow (pairedIndex, dashLengths.size())
  617. && dashes[pairedIndex] > nonZeroLength)
  618. dashes[pairedIndex] -= nonZeroLength;
  619. }
  620. }
  621. dp.setDashLengths (dashLengths);
  622. }
  623. }
  624. bool parseClipPath (const XmlPath& xml, Drawable& d)
  625. {
  626. const String clipPath (getStyleAttribute (xml, "clip-path"));
  627. if (clipPath.isNotEmpty())
  628. {
  629. auto urlID = parseURL (clipPath);
  630. if (urlID.isNotEmpty())
  631. {
  632. GetClipPathOp op = { this, &d };
  633. return topLevelXml.applyOperationToChildWithID (urlID, op);
  634. }
  635. }
  636. return false;
  637. }
  638. bool applyClipPath (Drawable& target, const XmlPath& xmlPath)
  639. {
  640. if (xmlPath->hasTagNameIgnoringNamespace ("clipPath"))
  641. {
  642. std::unique_ptr<DrawableComposite> drawableClipPath (new DrawableComposite());
  643. parseSubElements (xmlPath, *drawableClipPath, false);
  644. if (drawableClipPath->getNumChildComponents() > 0)
  645. {
  646. setCommonAttributes (*drawableClipPath, xmlPath);
  647. target.setClipPath (drawableClipPath.release());
  648. return true;
  649. }
  650. }
  651. return false;
  652. }
  653. bool addGradientStopsIn (ColourGradient& cg, const XmlPath& fillXml) const
  654. {
  655. bool result = false;
  656. if (fillXml.xml != nullptr)
  657. {
  658. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  659. {
  660. auto col = parseColour (fillXml.getChild (e), "stop-color", Colours::black);
  661. auto opacity = getStyleAttribute (fillXml.getChild (e), "stop-opacity", "1");
  662. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  663. double offset = e->getDoubleAttribute ("offset");
  664. if (e->getStringAttribute ("offset").containsChar ('%'))
  665. offset *= 0.01;
  666. cg.addColour (jlimit (0.0, 1.0, offset), col);
  667. result = true;
  668. }
  669. }
  670. return result;
  671. }
  672. FillType getGradientFillType (const XmlPath& fillXml,
  673. const Path& path,
  674. const float opacity) const
  675. {
  676. ColourGradient gradient;
  677. {
  678. auto linkedID = getLinkedID (fillXml);
  679. if (linkedID.isNotEmpty())
  680. {
  681. SetGradientStopsOp op = { this, &gradient, };
  682. topLevelXml.applyOperationToChildWithID (linkedID, op);
  683. }
  684. }
  685. addGradientStopsIn (gradient, fillXml);
  686. if (int numColours = gradient.getNumColours())
  687. {
  688. if (gradient.getColourPosition (0) > 0)
  689. gradient.addColour (0.0, gradient.getColour (0));
  690. if (gradient.getColourPosition (numColours - 1) < 1.0)
  691. gradient.addColour (1.0, gradient.getColour (numColours - 1));
  692. }
  693. else
  694. {
  695. gradient.addColour (0.0, Colours::black);
  696. gradient.addColour (1.0, Colours::black);
  697. }
  698. if (opacity < 1.0f)
  699. gradient.multiplyOpacity (opacity);
  700. jassert (gradient.getNumColours() > 0);
  701. gradient.isRadial = fillXml->hasTagNameIgnoringNamespace ("radialGradient");
  702. float gradientWidth = viewBoxW;
  703. float gradientHeight = viewBoxH;
  704. float dx = 0.0f;
  705. float dy = 0.0f;
  706. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  707. if (! userSpace)
  708. {
  709. auto bounds = path.getBounds();
  710. dx = bounds.getX();
  711. dy = bounds.getY();
  712. gradientWidth = bounds.getWidth();
  713. gradientHeight = bounds.getHeight();
  714. }
  715. if (gradient.isRadial)
  716. {
  717. if (userSpace)
  718. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  719. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  720. else
  721. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  722. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  723. auto radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  724. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  725. //xxx (the fx, fy focal point isn't handled properly here..)
  726. }
  727. else
  728. {
  729. if (userSpace)
  730. {
  731. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  732. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  733. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  734. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  735. }
  736. else
  737. {
  738. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  739. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  740. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  741. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  742. }
  743. if (gradient.point1 == gradient.point2)
  744. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  745. }
  746. FillType type (gradient);
  747. auto gradientTransform = parseTransform (fillXml->getStringAttribute ("gradientTransform"));
  748. if (gradient.isRadial)
  749. {
  750. type.transform = gradientTransform;
  751. }
  752. else
  753. {
  754. // Transform the perpendicular vector into the new coordinate space for the gradient.
  755. // This vector is now the slope of the linear gradient as it should appear in the new coord space
  756. auto perpendicular = Point<float> (gradient.point2.y - gradient.point1.y,
  757. gradient.point1.x - gradient.point2.x)
  758. .transformedBy (gradientTransform.withAbsoluteTranslation (0, 0));
  759. auto newGradPoint1 = gradient.point1.transformedBy (gradientTransform);
  760. auto newGradPoint2 = gradient.point2.transformedBy (gradientTransform);
  761. // Project the transformed gradient vector onto the transformed slope of the linear
  762. // gradient as it should appear in the new coordinate space
  763. const float scale = perpendicular.getDotProduct (newGradPoint2 - newGradPoint1)
  764. / perpendicular.getDotProduct (perpendicular);
  765. type.gradient->point1 = newGradPoint1;
  766. type.gradient->point2 = newGradPoint2 - perpendicular * scale;
  767. }
  768. return type;
  769. }
  770. FillType getPathFillType (const Path& path,
  771. const XmlPath& xml,
  772. StringRef fillAttribute,
  773. const String& fillOpacity,
  774. const String& overallOpacity,
  775. const Colour defaultColour) const
  776. {
  777. float opacity = 1.0f;
  778. if (overallOpacity.isNotEmpty())
  779. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  780. if (fillOpacity.isNotEmpty())
  781. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  782. String fill (getStyleAttribute (xml, fillAttribute));
  783. String urlID = parseURL (fill);
  784. if (urlID.isNotEmpty())
  785. {
  786. GetFillTypeOp op = { this, &path, opacity, FillType() };
  787. if (topLevelXml.applyOperationToChildWithID (urlID, op))
  788. return op.fillType;
  789. }
  790. if (isNone (fill))
  791. return Colours::transparentBlack;
  792. return parseColour (xml, fillAttribute, defaultColour).withMultipliedAlpha (opacity);
  793. }
  794. static PathStrokeType::JointStyle getJointStyle (const String& join) noexcept
  795. {
  796. if (join.equalsIgnoreCase ("round")) return PathStrokeType::curved;
  797. if (join.equalsIgnoreCase ("bevel")) return PathStrokeType::beveled;
  798. return PathStrokeType::mitered;
  799. }
  800. static PathStrokeType::EndCapStyle getEndCapStyle (const String& cap) noexcept
  801. {
  802. if (cap.equalsIgnoreCase ("round")) return PathStrokeType::rounded;
  803. if (cap.equalsIgnoreCase ("square")) return PathStrokeType::square;
  804. return PathStrokeType::butt;
  805. }
  806. float getStrokeWidth (const String& strokeWidth) const noexcept
  807. {
  808. return transform.getScaleFactor() * getCoordLength (strokeWidth, viewBoxW);
  809. }
  810. PathStrokeType getStrokeFor (const XmlPath& xml) const
  811. {
  812. return PathStrokeType (getStrokeWidth (getStyleAttribute (xml, "stroke-width", "1")),
  813. getJointStyle (getStyleAttribute (xml, "stroke-linejoin")),
  814. getEndCapStyle (getStyleAttribute (xml, "stroke-linecap")));
  815. }
  816. //==============================================================================
  817. Drawable* useText (const XmlPath& xml) const
  818. {
  819. auto translation = AffineTransform::translation ((float) xml->getDoubleAttribute ("x", 0.0),
  820. (float) xml->getDoubleAttribute ("y", 0.0));
  821. UseTextOp op = { this, &translation, nullptr };
  822. auto linkedID = getLinkedID (xml);
  823. if (linkedID.isNotEmpty())
  824. topLevelXml.applyOperationToChildWithID (linkedID, op);
  825. return op.target;
  826. }
  827. Drawable* parseText (const XmlPath& xml, bool shouldParseTransform,
  828. AffineTransform* additonalTransform = nullptr) const
  829. {
  830. if (shouldParseTransform && xml->hasAttribute ("transform"))
  831. {
  832. SVGState newState (*this);
  833. newState.addTransform (xml);
  834. return newState.parseText (xml, false, additonalTransform);
  835. }
  836. if (xml->hasTagName ("use"))
  837. return useText (xml);
  838. if (! xml->hasTagName ("text"))
  839. return nullptr;
  840. Array<float> xCoords, yCoords, dxCoords, dyCoords;
  841. getCoordList (xCoords, getInheritedAttribute (xml, "x"), true, true);
  842. getCoordList (yCoords, getInheritedAttribute (xml, "y"), true, false);
  843. getCoordList (dxCoords, getInheritedAttribute (xml, "dx"), true, true);
  844. getCoordList (dyCoords, getInheritedAttribute (xml, "dy"), true, false);
  845. auto font = getFont (xml);
  846. auto anchorStr = getStyleAttribute (xml, "text-anchor");
  847. auto dc = new DrawableComposite();
  848. setCommonAttributes (*dc, xml);
  849. forEachXmlChildElement (*xml, e)
  850. {
  851. if (e->isTextElement())
  852. {
  853. auto text = e->getText().trim();
  854. auto dt = new DrawableText();
  855. dc->addAndMakeVisible (dt);
  856. dt->setText (text);
  857. dt->setFont (font, true);
  858. if (additonalTransform != nullptr)
  859. dt->setTransform (transform.followedBy (*additonalTransform));
  860. else
  861. dt->setTransform (transform);
  862. dt->setColour (parseColour (xml, "fill", Colours::black)
  863. .withMultipliedAlpha (getStyleAttribute (xml, "fill-opacity", "1").getFloatValue()));
  864. Rectangle<float> bounds (xCoords[0], yCoords[0] - font.getAscent(),
  865. font.getStringWidthFloat (text), font.getHeight());
  866. if (anchorStr == "middle") bounds.setX (bounds.getX() - bounds.getWidth() / 2.0f);
  867. else if (anchorStr == "end") bounds.setX (bounds.getX() - bounds.getWidth());
  868. dt->setBoundingBox (bounds);
  869. }
  870. else if (e->hasTagNameIgnoringNamespace ("tspan"))
  871. {
  872. dc->addAndMakeVisible (parseText (xml.getChild (e), true));
  873. }
  874. }
  875. return dc;
  876. }
  877. Font getFont (const XmlPath& xml) const
  878. {
  879. Font f;
  880. auto family = getStyleAttribute (xml, "font-family").unquoted();
  881. if (family.isNotEmpty())
  882. f.setTypefaceName (family);
  883. if (getStyleAttribute (xml, "font-style").containsIgnoreCase ("italic"))
  884. f.setItalic (true);
  885. if (getStyleAttribute (xml, "font-weight").containsIgnoreCase ("bold"))
  886. f.setBold (true);
  887. return f.withPointHeight (getCoordLength (getStyleAttribute (xml, "font-size", "15"), 1.0f));
  888. }
  889. //==============================================================================
  890. Drawable* useImage (const XmlPath& xml) const
  891. {
  892. auto translation = AffineTransform::translation ((float) xml->getDoubleAttribute ("x", 0.0),
  893. (float) xml->getDoubleAttribute ("y", 0.0));
  894. UseImageOp op = { this, &translation, nullptr };
  895. auto linkedID = getLinkedID (xml);
  896. if (linkedID.isNotEmpty())
  897. topLevelXml.applyOperationToChildWithID (linkedID, op);
  898. return op.target;
  899. }
  900. Drawable* parseImage (const XmlPath& xml, bool shouldParseTransform,
  901. AffineTransform* additionalTransform = nullptr) const
  902. {
  903. if (shouldParseTransform && xml->hasAttribute ("transform"))
  904. {
  905. SVGState newState (*this);
  906. newState.addTransform (xml);
  907. return newState.parseImage (xml, false, additionalTransform);
  908. }
  909. if (xml->hasTagName ("use"))
  910. return useImage (xml);
  911. if (! xml->hasTagName ("image"))
  912. return nullptr;
  913. auto link = xml->getStringAttribute ("xlink:href");
  914. std::unique_ptr<InputStream> inputStream;
  915. MemoryOutputStream imageStream;
  916. if (link.startsWith ("data:"))
  917. {
  918. const auto indexOfComma = link.indexOf (",");
  919. auto format = link.substring (5, indexOfComma).trim();
  920. auto indexOfSemi = format.indexOf (";");
  921. if (format.substring (indexOfSemi + 1).trim().equalsIgnoreCase ("base64"))
  922. {
  923. auto mime = format.substring (0, indexOfSemi).trim();
  924. if (mime.equalsIgnoreCase ("image/png") || mime.equalsIgnoreCase ("image/jpeg"))
  925. {
  926. auto base64text = link.substring (indexOfComma + 1).removeCharacters ("\t\n\r ");
  927. if (Base64::convertFromBase64 (imageStream, base64text))
  928. inputStream.reset (new MemoryInputStream (imageStream.getData(), imageStream.getDataSize(), false));
  929. }
  930. }
  931. }
  932. else
  933. {
  934. auto linkedFile = originalFile.getParentDirectory().getChildFile (link);
  935. if (linkedFile.existsAsFile())
  936. inputStream.reset (linkedFile.createInputStream());
  937. }
  938. if (inputStream != nullptr)
  939. {
  940. auto image = ImageFileFormat::loadFrom (*inputStream);
  941. if (image.isValid())
  942. {
  943. auto* di = new DrawableImage();
  944. setCommonAttributes (*di, xml);
  945. Rectangle<float> imageBounds ((float) xml->getDoubleAttribute ("x", 0.0), (float) xml->getDoubleAttribute ("y", 0.0),
  946. (float) xml->getDoubleAttribute ("width", image.getWidth()), (float) xml->getDoubleAttribute ("height", image.getHeight()));
  947. di->setImage (image.rescaled ((int) imageBounds.getWidth(), (int) imageBounds.getHeight()));
  948. di->setTransformToFit (imageBounds, RectanglePlacement (parsePlacementFlags (xml->getStringAttribute ("preserveAspectRatio").trim())));
  949. if (additionalTransform != nullptr)
  950. di->setTransform (di->getTransform().followedBy (transform).followedBy (*additionalTransform));
  951. else
  952. di->setTransform (di->getTransform().followedBy (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. auto dpi = 96.0f;
  995. auto n1 = s[len - 2];
  996. auto 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 (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. auto 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 (double x1, double y1,
  1263. double x2, double y2,
  1264. double angle,
  1265. bool largeArc, 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 += MathConstants<double>::halfPi;
  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 += MathConstants<double>::twoPi;
  1317. }
  1318. else
  1319. {
  1320. if (deltaAngle > 0)
  1321. deltaAngle -= MathConstants<double>::twoPi;
  1322. }
  1323. deltaAngle = fmod (deltaAngle, MathConstants<double>::twoPi);
  1324. }
  1325. SVGState& operator= (const SVGState&) = delete;
  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. std::unique_ptr<XmlElement> outer (doc.getDocumentElement (true));
  1339. if (outer != nullptr && outer->hasTagName ("svg"))
  1340. {
  1341. std::unique_ptr<XmlElement> svgDocument (doc.getDocumentElement());
  1342. if (svgDocument != nullptr)
  1343. {
  1344. SVGState state (svgDocument.get(), svgFile);
  1345. return state.parseSVGElement (SVGState::XmlPath (svgDocument.get(), 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. }
  1357. } // namespace juce