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. 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. .followedBy (transform);
  749. if (gradient.isRadial)
  750. {
  751. type.transform = gradientTransform;
  752. }
  753. else
  754. {
  755. // Transform the perpendicular vector into the new coordinate space for the gradient.
  756. // This vector is now the slope of the linear gradient as it should appear in the new coord space
  757. auto perpendicular = Point<float> (gradient.point2.y - gradient.point1.y,
  758. gradient.point1.x - gradient.point2.x)
  759. .transformedBy (gradientTransform.withAbsoluteTranslation (0, 0));
  760. auto newGradPoint1 = gradient.point1.transformedBy (gradientTransform);
  761. auto newGradPoint2 = gradient.point2.transformedBy (gradientTransform);
  762. // Project the transformed gradient vector onto the transformed slope of the linear
  763. // gradient as it should appear in the new coordinate space
  764. const float scale = perpendicular.getDotProduct (newGradPoint2 - newGradPoint1)
  765. / perpendicular.getDotProduct (perpendicular);
  766. type.gradient->point1 = newGradPoint1;
  767. type.gradient->point2 = newGradPoint2 - perpendicular * scale;
  768. }
  769. return type;
  770. }
  771. FillType getPathFillType (const Path& path,
  772. const XmlPath& xml,
  773. StringRef fillAttribute,
  774. const String& fillOpacity,
  775. const String& overallOpacity,
  776. const Colour defaultColour) const
  777. {
  778. float opacity = 1.0f;
  779. if (overallOpacity.isNotEmpty())
  780. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  781. if (fillOpacity.isNotEmpty())
  782. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  783. String fill (getStyleAttribute (xml, fillAttribute));
  784. String urlID = parseURL (fill);
  785. if (urlID.isNotEmpty())
  786. {
  787. GetFillTypeOp op = { this, &path, opacity, FillType() };
  788. if (topLevelXml.applyOperationToChildWithID (urlID, op))
  789. return op.fillType;
  790. }
  791. if (isNone (fill))
  792. return Colours::transparentBlack;
  793. return parseColour (xml, fillAttribute, defaultColour).withMultipliedAlpha (opacity);
  794. }
  795. static PathStrokeType::JointStyle getJointStyle (const String& join) noexcept
  796. {
  797. if (join.equalsIgnoreCase ("round")) return PathStrokeType::curved;
  798. if (join.equalsIgnoreCase ("bevel")) return PathStrokeType::beveled;
  799. return PathStrokeType::mitered;
  800. }
  801. static PathStrokeType::EndCapStyle getEndCapStyle (const String& cap) noexcept
  802. {
  803. if (cap.equalsIgnoreCase ("round")) return PathStrokeType::rounded;
  804. if (cap.equalsIgnoreCase ("square")) return PathStrokeType::square;
  805. return PathStrokeType::butt;
  806. }
  807. float getStrokeWidth (const String& strokeWidth) const noexcept
  808. {
  809. return transform.getScaleFactor() * getCoordLength (strokeWidth, viewBoxW);
  810. }
  811. PathStrokeType getStrokeFor (const XmlPath& xml) const
  812. {
  813. return PathStrokeType (getStrokeWidth (getStyleAttribute (xml, "stroke-width", "1")),
  814. getJointStyle (getStyleAttribute (xml, "stroke-linejoin")),
  815. getEndCapStyle (getStyleAttribute (xml, "stroke-linecap")));
  816. }
  817. //==============================================================================
  818. Drawable* useText (const XmlPath& xml) const
  819. {
  820. auto translation = AffineTransform::translation ((float) xml->getDoubleAttribute ("x", 0.0),
  821. (float) xml->getDoubleAttribute ("y", 0.0));
  822. UseTextOp op = { this, &translation, nullptr };
  823. auto linkedID = getLinkedID (xml);
  824. if (linkedID.isNotEmpty())
  825. topLevelXml.applyOperationToChildWithID (linkedID, op);
  826. return op.target;
  827. }
  828. Drawable* parseText (const XmlPath& xml, bool shouldParseTransform,
  829. AffineTransform* additonalTransform = nullptr) const
  830. {
  831. if (shouldParseTransform && xml->hasAttribute ("transform"))
  832. {
  833. SVGState newState (*this);
  834. newState.addTransform (xml);
  835. return newState.parseText (xml, false, additonalTransform);
  836. }
  837. if (xml->hasTagName ("use"))
  838. return useText (xml);
  839. if (! xml->hasTagName ("text"))
  840. return nullptr;
  841. Array<float> xCoords, yCoords, dxCoords, dyCoords;
  842. getCoordList (xCoords, getInheritedAttribute (xml, "x"), true, true);
  843. getCoordList (yCoords, getInheritedAttribute (xml, "y"), true, false);
  844. getCoordList (dxCoords, getInheritedAttribute (xml, "dx"), true, true);
  845. getCoordList (dyCoords, getInheritedAttribute (xml, "dy"), true, false);
  846. auto font = getFont (xml);
  847. auto anchorStr = getStyleAttribute (xml, "text-anchor");
  848. auto dc = new DrawableComposite();
  849. setCommonAttributes (*dc, xml);
  850. forEachXmlChildElement (*xml, e)
  851. {
  852. if (e->isTextElement())
  853. {
  854. auto text = e->getText().trim();
  855. auto dt = new DrawableText();
  856. dc->addAndMakeVisible (dt);
  857. dt->setText (text);
  858. dt->setFont (font, true);
  859. if (additonalTransform != nullptr)
  860. dt->setTransform (transform.followedBy (*additonalTransform));
  861. else
  862. dt->setTransform (transform);
  863. dt->setColour (parseColour (xml, "fill", Colours::black)
  864. .withMultipliedAlpha (getStyleAttribute (xml, "fill-opacity", "1").getFloatValue()));
  865. Rectangle<float> bounds (xCoords[0], yCoords[0] - font.getAscent(),
  866. font.getStringWidthFloat (text), font.getHeight());
  867. if (anchorStr == "middle") bounds.setX (bounds.getX() - bounds.getWidth() / 2.0f);
  868. else if (anchorStr == "end") bounds.setX (bounds.getX() - bounds.getWidth());
  869. dt->setBoundingBox (bounds);
  870. }
  871. else if (e->hasTagNameIgnoringNamespace ("tspan"))
  872. {
  873. dc->addAndMakeVisible (parseText (xml.getChild (e), true));
  874. }
  875. }
  876. return dc;
  877. }
  878. Font getFont (const XmlPath& xml) const
  879. {
  880. Font f;
  881. auto family = getStyleAttribute (xml, "font-family").unquoted();
  882. if (family.isNotEmpty())
  883. f.setTypefaceName (family);
  884. if (getStyleAttribute (xml, "font-style").containsIgnoreCase ("italic"))
  885. f.setItalic (true);
  886. if (getStyleAttribute (xml, "font-weight").containsIgnoreCase ("bold"))
  887. f.setBold (true);
  888. return f.withPointHeight (getCoordLength (getStyleAttribute (xml, "font-size", "15"), 1.0f));
  889. }
  890. //==============================================================================
  891. Drawable* useImage (const XmlPath& xml) const
  892. {
  893. auto translation = AffineTransform::translation ((float) xml->getDoubleAttribute ("x", 0.0),
  894. (float) xml->getDoubleAttribute ("y", 0.0));
  895. UseImageOp op = { this, &translation, nullptr };
  896. auto linkedID = getLinkedID (xml);
  897. if (linkedID.isNotEmpty())
  898. topLevelXml.applyOperationToChildWithID (linkedID, op);
  899. return op.target;
  900. }
  901. Drawable* parseImage (const XmlPath& xml, bool shouldParseTransform,
  902. AffineTransform* additionalTransform = nullptr) const
  903. {
  904. if (shouldParseTransform && xml->hasAttribute ("transform"))
  905. {
  906. SVGState newState (*this);
  907. newState.addTransform (xml);
  908. return newState.parseImage (xml, false, additionalTransform);
  909. }
  910. if (xml->hasTagName ("use"))
  911. return useImage (xml);
  912. if (! xml->hasTagName ("image"))
  913. return nullptr;
  914. auto link = xml->getStringAttribute ("xlink:href");
  915. std::unique_ptr<InputStream> inputStream;
  916. MemoryOutputStream imageStream;
  917. if (link.startsWith ("data:"))
  918. {
  919. const auto indexOfComma = link.indexOf (",");
  920. auto format = link.substring (5, indexOfComma).trim();
  921. auto indexOfSemi = format.indexOf (";");
  922. if (format.substring (indexOfSemi + 1).trim().equalsIgnoreCase ("base64"))
  923. {
  924. auto mime = format.substring (0, indexOfSemi).trim();
  925. if (mime.equalsIgnoreCase ("image/png") || mime.equalsIgnoreCase ("image/jpeg"))
  926. {
  927. auto base64text = link.substring (indexOfComma + 1).removeCharacters ("\t\n\r ");
  928. if (Base64::convertFromBase64 (imageStream, base64text))
  929. inputStream.reset (new MemoryInputStream (imageStream.getData(), imageStream.getDataSize(), false));
  930. }
  931. }
  932. }
  933. else
  934. {
  935. auto linkedFile = originalFile.getParentDirectory().getChildFile (link);
  936. if (linkedFile.existsAsFile())
  937. inputStream.reset (linkedFile.createInputStream());
  938. }
  939. if (inputStream != nullptr)
  940. {
  941. auto image = ImageFileFormat::loadFrom (*inputStream);
  942. if (image.isValid())
  943. {
  944. auto* di = new DrawableImage();
  945. setCommonAttributes (*di, xml);
  946. di->setImage (image);
  947. if (additionalTransform != nullptr)
  948. di->setTransform (transform.followedBy (*additionalTransform));
  949. else
  950. di->setTransform (transform);
  951. return di;
  952. }
  953. }
  954. return nullptr;
  955. }
  956. //==============================================================================
  957. void addTransform (const XmlPath& xml)
  958. {
  959. transform = parseTransform (xml->getStringAttribute ("transform"))
  960. .followedBy (transform);
  961. }
  962. //==============================================================================
  963. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  964. {
  965. String number;
  966. if (! parseNextNumber (s, number, allowUnits))
  967. {
  968. value = 0;
  969. return false;
  970. }
  971. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  972. return true;
  973. }
  974. bool parseCoords (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  975. {
  976. return parseCoord (s, p.x, allowUnits, true)
  977. && parseCoord (s, p.y, allowUnits, false);
  978. }
  979. bool parseCoordsOrSkip (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  980. {
  981. if (parseCoords (s, p, allowUnits))
  982. return true;
  983. if (! s.isEmpty()) ++s;
  984. return false;
  985. }
  986. float getCoordLength (const String& s, const float sizeForProportions) const noexcept
  987. {
  988. float n = s.getFloatValue();
  989. const int len = s.length();
  990. if (len > 2)
  991. {
  992. auto dpi = 96.0f;
  993. auto n1 = s[len - 2];
  994. auto n2 = s[len - 1];
  995. if (n1 == 'i' && n2 == 'n') n *= dpi;
  996. else if (n1 == 'm' && n2 == 'm') n *= dpi / 25.4f;
  997. else if (n1 == 'c' && n2 == 'm') n *= dpi / 2.54f;
  998. else if (n1 == 'p' && n2 == 'c') n *= 15.0f;
  999. else if (n2 == '%') n *= 0.01f * sizeForProportions;
  1000. }
  1001. return n;
  1002. }
  1003. float getCoordLength (const XmlPath& xml, const char* attName, const float sizeForProportions) const noexcept
  1004. {
  1005. return getCoordLength (xml->getStringAttribute (attName), sizeForProportions);
  1006. }
  1007. void getCoordList (Array<float>& coords, const String& list, bool allowUnits, const bool isX) const
  1008. {
  1009. auto text = list.getCharPointer();
  1010. float value;
  1011. while (parseCoord (text, value, allowUnits, isX))
  1012. coords.add (value);
  1013. }
  1014. //==============================================================================
  1015. void parseCSSStyle (const XmlPath& xml)
  1016. {
  1017. cssStyleText = xml->getAllSubText() + "\n" + cssStyleText;
  1018. }
  1019. void parseDefs (const XmlPath& xml)
  1020. {
  1021. if (auto* style = xml->getChildByName ("style"))
  1022. parseCSSStyle (xml.getChild (style));
  1023. }
  1024. static String::CharPointerType findStyleItem (String::CharPointerType source, String::CharPointerType name)
  1025. {
  1026. auto nameLength = (int) name.length();
  1027. while (! source.isEmpty())
  1028. {
  1029. if (source.getAndAdvance() == '.'
  1030. && CharacterFunctions::compareIgnoreCaseUpTo (source, name, nameLength) == 0)
  1031. {
  1032. auto endOfName = (source + nameLength).findEndOfWhitespace();
  1033. if (*endOfName == '{')
  1034. return endOfName;
  1035. if (*endOfName == ',')
  1036. return CharacterFunctions::find (endOfName, (juce_wchar) '{');
  1037. }
  1038. }
  1039. return source;
  1040. }
  1041. String getStyleAttribute (const XmlPath& xml, StringRef attributeName, const String& defaultValue = String()) const
  1042. {
  1043. if (xml->hasAttribute (attributeName))
  1044. return xml->getStringAttribute (attributeName, defaultValue);
  1045. auto styleAtt = xml->getStringAttribute ("style");
  1046. if (styleAtt.isNotEmpty())
  1047. {
  1048. auto value = getAttributeFromStyleList (styleAtt, attributeName, {});
  1049. if (value.isNotEmpty())
  1050. return value;
  1051. }
  1052. else if (xml->hasAttribute ("class"))
  1053. {
  1054. for (auto i = cssStyleText.getCharPointer();;)
  1055. {
  1056. auto openBrace = findStyleItem (i, xml->getStringAttribute ("class").getCharPointer());
  1057. if (openBrace.isEmpty())
  1058. break;
  1059. auto closeBrace = CharacterFunctions::find (openBrace, (juce_wchar) '}');
  1060. if (closeBrace.isEmpty())
  1061. break;
  1062. auto value = getAttributeFromStyleList (String (openBrace + 1, closeBrace),
  1063. attributeName, defaultValue);
  1064. if (value.isNotEmpty())
  1065. return value;
  1066. i = closeBrace + 1;
  1067. }
  1068. }
  1069. if (xml.parent != nullptr)
  1070. return getStyleAttribute (*xml.parent, attributeName, defaultValue);
  1071. return defaultValue;
  1072. }
  1073. String getInheritedAttribute (const XmlPath& xml, StringRef attributeName) const
  1074. {
  1075. if (xml->hasAttribute (attributeName))
  1076. return xml->getStringAttribute (attributeName);
  1077. if (xml.parent != nullptr)
  1078. return getInheritedAttribute (*xml.parent, attributeName);
  1079. return {};
  1080. }
  1081. static int parsePlacementFlags (const String& align) noexcept
  1082. {
  1083. if (align.isEmpty())
  1084. return 0;
  1085. if (isNone (align))
  1086. return RectanglePlacement::stretchToFit;
  1087. return (align.containsIgnoreCase ("slice") ? RectanglePlacement::fillDestination : 0)
  1088. | (align.containsIgnoreCase ("xMin") ? RectanglePlacement::xLeft
  1089. : (align.containsIgnoreCase ("xMax") ? RectanglePlacement::xRight
  1090. : RectanglePlacement::xMid))
  1091. | (align.containsIgnoreCase ("yMin") ? RectanglePlacement::yTop
  1092. : (align.containsIgnoreCase ("yMax") ? RectanglePlacement::yBottom
  1093. : RectanglePlacement::yMid));
  1094. }
  1095. //==============================================================================
  1096. static bool isIdentifierChar (juce_wchar c)
  1097. {
  1098. return CharacterFunctions::isLetter (c) || c == '-';
  1099. }
  1100. static String getAttributeFromStyleList (const String& list, StringRef attributeName, const String& defaultValue)
  1101. {
  1102. int i = 0;
  1103. for (;;)
  1104. {
  1105. i = list.indexOf (i, attributeName);
  1106. if (i < 0)
  1107. break;
  1108. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  1109. && ! isIdentifierChar (list [i + attributeName.length()]))
  1110. {
  1111. i = list.indexOfChar (i, ':');
  1112. if (i < 0)
  1113. break;
  1114. int end = list.indexOfChar (i, ';');
  1115. if (end < 0)
  1116. end = 0x7ffff;
  1117. return list.substring (i + 1, end).trim();
  1118. }
  1119. ++i;
  1120. }
  1121. return defaultValue;
  1122. }
  1123. //==============================================================================
  1124. static bool isStartOfNumber (juce_wchar c) noexcept
  1125. {
  1126. return CharacterFunctions::isDigit (c) || c == '-' || c == '+';
  1127. }
  1128. static bool parseNextNumber (String::CharPointerType& text, String& value, const bool allowUnits)
  1129. {
  1130. auto s = text;
  1131. while (s.isWhitespace() || *s == ',')
  1132. ++s;
  1133. auto start = s;
  1134. if (isStartOfNumber (*s))
  1135. ++s;
  1136. while (s.isDigit())
  1137. ++s;
  1138. if (*s == '.')
  1139. {
  1140. ++s;
  1141. while (s.isDigit())
  1142. ++s;
  1143. }
  1144. if ((*s == 'e' || *s == 'E') && isStartOfNumber (s[1]))
  1145. {
  1146. s += 2;
  1147. while (s.isDigit())
  1148. ++s;
  1149. }
  1150. if (allowUnits)
  1151. while (s.isLetter())
  1152. ++s;
  1153. if (s == start)
  1154. {
  1155. text = s;
  1156. return false;
  1157. }
  1158. value = String (start, s);
  1159. while (s.isWhitespace() || *s == ',')
  1160. ++s;
  1161. text = s;
  1162. return true;
  1163. }
  1164. //==============================================================================
  1165. Colour parseColour (const XmlPath& xml, StringRef attributeName, const Colour defaultColour) const
  1166. {
  1167. auto text = getStyleAttribute (xml, attributeName);
  1168. if (text.startsWithChar ('#'))
  1169. {
  1170. uint32 hex[6] = { 0 };
  1171. int numChars = 0;
  1172. auto s = text.getCharPointer();
  1173. while (numChars < 6)
  1174. {
  1175. auto hexValue = CharacterFunctions::getHexDigitValue (*++s);
  1176. if (hexValue >= 0)
  1177. hex [numChars++] = (uint32) hexValue;
  1178. else
  1179. break;
  1180. }
  1181. if (numChars <= 3)
  1182. return Colour ((uint8) (hex[0] * 0x11),
  1183. (uint8) (hex[1] * 0x11),
  1184. (uint8) (hex[2] * 0x11));
  1185. return Colour ((uint8) ((hex[0] << 4) + hex[1]),
  1186. (uint8) ((hex[2] << 4) + hex[3]),
  1187. (uint8) ((hex[4] << 4) + hex[5]));
  1188. }
  1189. if (text.startsWith ("rgb"))
  1190. {
  1191. auto openBracket = text.indexOfChar ('(');
  1192. auto closeBracket = text.indexOfChar (openBracket, ')');
  1193. if (openBracket >= 3 && closeBracket > openBracket)
  1194. {
  1195. StringArray tokens;
  1196. tokens.addTokens (text.substring (openBracket + 1, closeBracket), ",", "");
  1197. tokens.trim();
  1198. tokens.removeEmptyStrings();
  1199. if (tokens[0].containsChar ('%'))
  1200. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  1201. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  1202. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  1203. return Colour ((uint8) tokens[0].getIntValue(),
  1204. (uint8) tokens[1].getIntValue(),
  1205. (uint8) tokens[2].getIntValue());
  1206. }
  1207. }
  1208. if (text == "inherit")
  1209. {
  1210. for (const XmlPath* p = xml.parent; p != nullptr; p = p->parent)
  1211. if (getStyleAttribute (*p, attributeName).isNotEmpty())
  1212. return parseColour (*p, attributeName, defaultColour);
  1213. }
  1214. return Colours::findColourForName (text, defaultColour);
  1215. }
  1216. static AffineTransform parseTransform (String t)
  1217. {
  1218. AffineTransform result;
  1219. while (t.isNotEmpty())
  1220. {
  1221. StringArray tokens;
  1222. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  1223. .upToFirstOccurrenceOf (")", false, false),
  1224. ", ", "");
  1225. tokens.removeEmptyStrings (true);
  1226. float numbers[6];
  1227. for (int i = 0; i < numElementsInArray (numbers); ++i)
  1228. numbers[i] = tokens[i].getFloatValue();
  1229. AffineTransform trans;
  1230. if (t.startsWithIgnoreCase ("matrix"))
  1231. {
  1232. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  1233. numbers[1], numbers[3], numbers[5]);
  1234. }
  1235. else if (t.startsWithIgnoreCase ("translate"))
  1236. {
  1237. trans = AffineTransform::translation (numbers[0], numbers[1]);
  1238. }
  1239. else if (t.startsWithIgnoreCase ("scale"))
  1240. {
  1241. trans = AffineTransform::scale (numbers[0], numbers[tokens.size() > 1 ? 1 : 0]);
  1242. }
  1243. else if (t.startsWithIgnoreCase ("rotate"))
  1244. {
  1245. trans = AffineTransform::rotation (degreesToRadians (numbers[0]), numbers[1], numbers[2]);
  1246. }
  1247. else if (t.startsWithIgnoreCase ("skewX"))
  1248. {
  1249. trans = AffineTransform::shear (std::tan (degreesToRadians (numbers[0])), 0.0f);
  1250. }
  1251. else if (t.startsWithIgnoreCase ("skewY"))
  1252. {
  1253. trans = AffineTransform::shear (0.0f, std::tan (degreesToRadians (numbers[0])));
  1254. }
  1255. result = trans.followedBy (result);
  1256. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  1257. }
  1258. return result;
  1259. }
  1260. static void endpointToCentreParameters (double x1, double y1,
  1261. double x2, double y2,
  1262. double angle,
  1263. bool largeArc, bool sweep,
  1264. double& rx, double& ry,
  1265. double& centreX, double& centreY,
  1266. double& startAngle, double& deltaAngle) noexcept
  1267. {
  1268. const double midX = (x1 - x2) * 0.5;
  1269. const double midY = (y1 - y2) * 0.5;
  1270. const double cosAngle = std::cos (angle);
  1271. const double sinAngle = std::sin (angle);
  1272. const double xp = cosAngle * midX + sinAngle * midY;
  1273. const double yp = cosAngle * midY - sinAngle * midX;
  1274. const double xp2 = xp * xp;
  1275. const double yp2 = yp * yp;
  1276. double rx2 = rx * rx;
  1277. double ry2 = ry * ry;
  1278. const double s = (xp2 / rx2) + (yp2 / ry2);
  1279. double c;
  1280. if (s <= 1.0)
  1281. {
  1282. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  1283. / (( rx2 * yp2) + (ry2 * xp2))));
  1284. if (largeArc == sweep)
  1285. c = -c;
  1286. }
  1287. else
  1288. {
  1289. const double s2 = std::sqrt (s);
  1290. rx *= s2;
  1291. ry *= s2;
  1292. c = 0;
  1293. }
  1294. const double cpx = ((rx * yp) / ry) * c;
  1295. const double cpy = ((-ry * xp) / rx) * c;
  1296. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  1297. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  1298. const double ux = (xp - cpx) / rx;
  1299. const double uy = (yp - cpy) / ry;
  1300. const double vx = (-xp - cpx) / rx;
  1301. const double vy = (-yp - cpy) / ry;
  1302. const double length = juce_hypot (ux, uy);
  1303. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  1304. if (uy < 0)
  1305. startAngle = -startAngle;
  1306. startAngle += MathConstants<double>::halfPi;
  1307. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  1308. / (length * juce_hypot (vx, vy))));
  1309. if ((ux * vy) - (uy * vx) < 0)
  1310. deltaAngle = -deltaAngle;
  1311. if (sweep)
  1312. {
  1313. if (deltaAngle < 0)
  1314. deltaAngle += MathConstants<double>::twoPi;
  1315. }
  1316. else
  1317. {
  1318. if (deltaAngle > 0)
  1319. deltaAngle -= MathConstants<double>::twoPi;
  1320. }
  1321. deltaAngle = fmod (deltaAngle, MathConstants<double>::twoPi);
  1322. }
  1323. SVGState& operator= (const SVGState&) = delete;
  1324. };
  1325. //==============================================================================
  1326. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  1327. {
  1328. if (! svgDocument.hasTagNameIgnoringNamespace ("svg"))
  1329. return nullptr;
  1330. SVGState state (&svgDocument);
  1331. return state.parseSVGElement (SVGState::XmlPath (&svgDocument, nullptr));
  1332. }
  1333. Drawable* Drawable::createFromSVGFile (const File& svgFile)
  1334. {
  1335. XmlDocument doc (svgFile);
  1336. std::unique_ptr<XmlElement> outer (doc.getDocumentElement (true));
  1337. if (outer != nullptr && outer->hasTagName ("svg"))
  1338. {
  1339. std::unique_ptr<XmlElement> svgDocument (doc.getDocumentElement());
  1340. if (svgDocument != nullptr)
  1341. {
  1342. SVGState state (svgDocument.get(), svgFile);
  1343. return state.parseSVGElement (SVGState::XmlPath (svgDocument.get(), nullptr));
  1344. }
  1345. }
  1346. return nullptr;
  1347. }
  1348. Path Drawable::parseSVGPath (const String& svgPath)
  1349. {
  1350. SVGState state (nullptr);
  1351. Path p;
  1352. state.parsePathString (p, svgPath);
  1353. return p;
  1354. }
  1355. } // namespace juce