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.

1764 lines
59KB

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