Audio plugin host https://kx.studio/carla
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.

1317 lines
46KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. class SVGState
  18. {
  19. public:
  20. //==============================================================================
  21. explicit SVGState (const XmlElement* const topLevel)
  22. : topLevelXml (topLevel, nullptr),
  23. elementX (0), elementY (0),
  24. width (512), height (512),
  25. viewBoxW (0), viewBoxH (0)
  26. {
  27. }
  28. struct XmlPath
  29. {
  30. XmlPath (const XmlElement* e, const XmlPath* p) noexcept : xml (e), parent (p) {}
  31. const XmlElement& operator*() const noexcept { jassert (xml != nullptr); return *xml; }
  32. const XmlElement* operator->() const noexcept { return xml; }
  33. XmlPath getChild (const XmlElement* e) const noexcept { return XmlPath (e, this); }
  34. const XmlElement* xml;
  35. const XmlPath* parent;
  36. };
  37. //==============================================================================
  38. Drawable* parseSVGElement (const XmlPath& xml)
  39. {
  40. if (! xml->hasTagNameIgnoringNamespace ("svg"))
  41. return nullptr;
  42. DrawableComposite* const drawable = new DrawableComposite();
  43. drawable->setName (xml->getStringAttribute ("id"));
  44. SVGState newState (*this);
  45. if (xml->hasAttribute ("transform"))
  46. newState.addTransform (xml);
  47. newState.elementX = getCoordLength (xml->getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  48. newState.elementY = getCoordLength (xml->getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  49. newState.width = getCoordLength (xml->getStringAttribute ("width", String (newState.width)), viewBoxW);
  50. newState.height = getCoordLength (xml->getStringAttribute ("height", String (newState.height)), viewBoxH);
  51. if (newState.width <= 0) newState.width = 100;
  52. if (newState.height <= 0) newState.height = 100;
  53. if (xml->hasAttribute ("viewBox"))
  54. {
  55. const String viewBoxAtt (xml->getStringAttribute ("viewBox"));
  56. String::CharPointerType viewParams (viewBoxAtt.getCharPointer());
  57. Point<float> vxy, vwh;
  58. if (parseCoords (viewParams, vxy, true)
  59. && parseCoords (viewParams, vwh, true)
  60. && vwh.x > 0
  61. && vwh.y > 0)
  62. {
  63. newState.viewBoxW = vwh.x;
  64. newState.viewBoxH = vwh.y;
  65. int placementFlags = 0;
  66. const String aspect (xml->getStringAttribute ("preserveAspectRatio"));
  67. if (aspect.containsIgnoreCase ("none"))
  68. {
  69. placementFlags = RectanglePlacement::stretchToFit;
  70. }
  71. else
  72. {
  73. if (aspect.containsIgnoreCase ("slice")) placementFlags |= RectanglePlacement::fillDestination;
  74. if (aspect.containsIgnoreCase ("xMin")) placementFlags |= RectanglePlacement::xLeft;
  75. else if (aspect.containsIgnoreCase ("xMax")) placementFlags |= RectanglePlacement::xRight;
  76. else placementFlags |= RectanglePlacement::xMid;
  77. if (aspect.containsIgnoreCase ("yMin")) placementFlags |= RectanglePlacement::yTop;
  78. else if (aspect.containsIgnoreCase ("yMax")) placementFlags |= RectanglePlacement::yBottom;
  79. else placementFlags |= RectanglePlacement::yMid;
  80. }
  81. newState.transform = RectanglePlacement (placementFlags)
  82. .getTransformToFit (Rectangle<float> (vxy.x, vxy.y, vwh.x, vwh.y),
  83. Rectangle<float> (newState.width, newState.height))
  84. .followedBy (newState.transform);
  85. }
  86. }
  87. else
  88. {
  89. if (viewBoxW == 0) newState.viewBoxW = newState.width;
  90. if (viewBoxH == 0) newState.viewBoxH = newState.height;
  91. }
  92. newState.parseSubElements (xml, *drawable);
  93. drawable->setContentArea (RelativeRectangle (Rectangle<float> (newState.viewBoxW, newState.viewBoxH)));
  94. drawable->resetBoundingBoxToContentArea();
  95. return drawable;
  96. }
  97. //==============================================================================
  98. void parsePathString (Path& path, const String& pathString) const
  99. {
  100. String::CharPointerType d (pathString.getCharPointer().findEndOfWhitespace());
  101. Point<float> subpathStart, last, last2, p1, p2, p3;
  102. juce_wchar lastCommandChar = 0;
  103. bool isRelative = true;
  104. bool carryOn = true;
  105. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  106. while (! d.isEmpty())
  107. {
  108. if (validCommandChars.indexOf (*d) >= 0)
  109. {
  110. lastCommandChar = d.getAndAdvance();
  111. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  112. }
  113. switch (lastCommandChar)
  114. {
  115. case 'M':
  116. case 'm':
  117. case 'L':
  118. case 'l':
  119. if (parseCoordsOrSkip (d, p1, false))
  120. {
  121. if (isRelative)
  122. p1 += last;
  123. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  124. {
  125. subpathStart = p1;
  126. path.startNewSubPath (p1);
  127. lastCommandChar = 'l';
  128. }
  129. else
  130. path.lineTo (p1);
  131. last2 = last;
  132. last = p1;
  133. }
  134. break;
  135. case 'H':
  136. case 'h':
  137. if (parseCoord (d, p1.x, false, true))
  138. {
  139. if (isRelative)
  140. p1.x += last.x;
  141. path.lineTo (p1.x, last.y);
  142. last2.x = last.x;
  143. last.x = p1.x;
  144. }
  145. else
  146. {
  147. ++d;
  148. }
  149. break;
  150. case 'V':
  151. case 'v':
  152. if (parseCoord (d, p1.y, false, false))
  153. {
  154. if (isRelative)
  155. p1.y += last.y;
  156. path.lineTo (last.x, p1.y);
  157. last2.y = last.y;
  158. last.y = p1.y;
  159. }
  160. else
  161. {
  162. ++d;
  163. }
  164. break;
  165. case 'C':
  166. case 'c':
  167. if (parseCoordsOrSkip (d, p1, false)
  168. && parseCoordsOrSkip (d, p2, false)
  169. && parseCoordsOrSkip (d, p3, false))
  170. {
  171. if (isRelative)
  172. {
  173. p1 += last;
  174. p2 += last;
  175. p3 += last;
  176. }
  177. path.cubicTo (p1, p2, p3);
  178. last2 = p2;
  179. last = p3;
  180. }
  181. break;
  182. case 'S':
  183. case 's':
  184. if (parseCoordsOrSkip (d, p1, false)
  185. && parseCoordsOrSkip (d, p3, false))
  186. {
  187. if (isRelative)
  188. {
  189. p1 += last;
  190. p3 += last;
  191. }
  192. p2 = last + (last - last2);
  193. path.cubicTo (p2, p1, p3);
  194. last2 = p1;
  195. last = p3;
  196. }
  197. break;
  198. case 'Q':
  199. case 'q':
  200. if (parseCoordsOrSkip (d, p1, false)
  201. && parseCoordsOrSkip (d, p2, false))
  202. {
  203. if (isRelative)
  204. {
  205. p1 += last;
  206. p2 += last;
  207. }
  208. path.quadraticTo (p1, p2);
  209. last2 = p1;
  210. last = p2;
  211. }
  212. break;
  213. case 'T':
  214. case 't':
  215. if (parseCoordsOrSkip (d, p1, false))
  216. {
  217. if (isRelative)
  218. p1 += last;
  219. p2 = last + (last - last2);
  220. path.quadraticTo (p2, p1);
  221. last2 = p2;
  222. last = p1;
  223. }
  224. break;
  225. case 'A':
  226. case 'a':
  227. if (parseCoordsOrSkip (d, p1, false))
  228. {
  229. String num;
  230. if (parseNextNumber (d, num, false))
  231. {
  232. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  233. if (parseNextNumber (d, num, false))
  234. {
  235. const bool largeArc = num.getIntValue() != 0;
  236. if (parseNextNumber (d, num, false))
  237. {
  238. const bool sweep = num.getIntValue() != 0;
  239. if (parseCoordsOrSkip (d, p2, false))
  240. {
  241. if (isRelative)
  242. p2 += last;
  243. if (last != p2)
  244. {
  245. double centreX, centreY, startAngle, deltaAngle;
  246. double rx = p1.x, ry = p1.y;
  247. endpointToCentreParameters (last.x, last.y, p2.x, p2.y,
  248. angle, largeArc, sweep,
  249. rx, ry, centreX, centreY,
  250. startAngle, deltaAngle);
  251. path.addCentredArc ((float) centreX, (float) centreY,
  252. (float) rx, (float) ry,
  253. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  254. false);
  255. path.lineTo (p2);
  256. }
  257. last2 = last;
  258. last = p2;
  259. }
  260. }
  261. }
  262. }
  263. }
  264. break;
  265. case 'Z':
  266. case 'z':
  267. path.closeSubPath();
  268. last = last2 = subpathStart;
  269. d = d.findEndOfWhitespace();
  270. lastCommandChar = 'M';
  271. break;
  272. default:
  273. carryOn = false;
  274. break;
  275. }
  276. if (! carryOn)
  277. break;
  278. }
  279. }
  280. private:
  281. //==============================================================================
  282. const XmlPath topLevelXml;
  283. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  284. AffineTransform transform;
  285. String cssStyleText;
  286. //==============================================================================
  287. void parseSubElements (const XmlPath& xml, DrawableComposite& parentDrawable)
  288. {
  289. forEachXmlChildElement (*xml, e)
  290. parentDrawable.addAndMakeVisible (parseSubElement (xml.getChild (e)));
  291. }
  292. Drawable* parseSubElement (const XmlPath& xml)
  293. {
  294. const String tag (xml->getTagNameWithoutNamespace());
  295. if (tag == "g") return parseGroupElement (xml);
  296. if (tag == "svg") return parseSVGElement (xml);
  297. if (tag == "path") return parsePath (xml);
  298. if (tag == "rect") return parseRect (xml);
  299. if (tag == "circle") return parseCircle (xml);
  300. if (tag == "ellipse") return parseEllipse (xml);
  301. if (tag == "line") return parseLine (xml);
  302. if (tag == "polyline") return parsePolygon (xml, true);
  303. if (tag == "polygon") return parsePolygon (xml, false);
  304. if (tag == "text") return parseText (xml);
  305. if (tag == "switch") return parseSwitch (xml);
  306. if (tag == "style") parseCSSStyle (xml);
  307. return nullptr;
  308. }
  309. DrawableComposite* parseSwitch (const XmlPath& xml)
  310. {
  311. if (const XmlElement* const group = xml->getChildByName ("g"))
  312. return parseGroupElement (xml.getChild (group));
  313. return nullptr;
  314. }
  315. DrawableComposite* parseGroupElement (const XmlPath& xml)
  316. {
  317. DrawableComposite* const drawable = new DrawableComposite();
  318. drawable->setName (xml->getStringAttribute ("id"));
  319. if (xml->hasAttribute ("transform"))
  320. {
  321. SVGState newState (*this);
  322. newState.addTransform (xml);
  323. newState.parseSubElements (xml, *drawable);
  324. }
  325. else
  326. {
  327. parseSubElements (xml, *drawable);
  328. }
  329. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  330. return drawable;
  331. }
  332. //==============================================================================
  333. Drawable* parsePath (const XmlPath& xml) const
  334. {
  335. Path path;
  336. parsePathString (path, xml->getStringAttribute ("d"));
  337. if (getStyleAttribute (xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  338. path.setUsingNonZeroWinding (false);
  339. return parseShape (xml, path);
  340. }
  341. Drawable* parseRect (const XmlPath& xml) const
  342. {
  343. Path rect;
  344. const bool hasRX = xml->hasAttribute ("rx");
  345. const bool hasRY = xml->hasAttribute ("ry");
  346. if (hasRX || hasRY)
  347. {
  348. float rx = getCoordLength (xml, "rx", viewBoxW);
  349. float ry = getCoordLength (xml, "ry", viewBoxH);
  350. if (! hasRX)
  351. rx = ry;
  352. else if (! hasRY)
  353. ry = rx;
  354. rect.addRoundedRectangle (getCoordLength (xml, "x", viewBoxW),
  355. getCoordLength (xml, "y", viewBoxH),
  356. getCoordLength (xml, "width", viewBoxW),
  357. getCoordLength (xml, "height", viewBoxH),
  358. rx, ry);
  359. }
  360. else
  361. {
  362. rect.addRectangle (getCoordLength (xml, "x", viewBoxW),
  363. getCoordLength (xml, "y", viewBoxH),
  364. getCoordLength (xml, "width", viewBoxW),
  365. getCoordLength (xml, "height", viewBoxH));
  366. }
  367. return parseShape (xml, rect);
  368. }
  369. Drawable* parseCircle (const XmlPath& xml) const
  370. {
  371. Path circle;
  372. const float cx = getCoordLength (xml, "cx", viewBoxW);
  373. const float cy = getCoordLength (xml, "cy", viewBoxH);
  374. const float radius = getCoordLength (xml, "r", viewBoxW);
  375. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  376. return parseShape (xml, circle);
  377. }
  378. Drawable* parseEllipse (const XmlPath& xml) const
  379. {
  380. Path ellipse;
  381. const float cx = getCoordLength (xml, "cx", viewBoxW);
  382. const float cy = getCoordLength (xml, "cy", viewBoxH);
  383. const float radiusX = getCoordLength (xml, "rx", viewBoxW);
  384. const float radiusY = getCoordLength (xml, "ry", viewBoxH);
  385. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  386. return parseShape (xml, ellipse);
  387. }
  388. Drawable* parseLine (const XmlPath& xml) const
  389. {
  390. Path line;
  391. const float x1 = getCoordLength (xml, "x1", viewBoxW);
  392. const float y1 = getCoordLength (xml, "y1", viewBoxH);
  393. const float x2 = getCoordLength (xml, "x2", viewBoxW);
  394. const float y2 = getCoordLength (xml, "y2", viewBoxH);
  395. line.startNewSubPath (x1, y1);
  396. line.lineTo (x2, y2);
  397. return parseShape (xml, line);
  398. }
  399. Drawable* parsePolygon (const XmlPath& xml, const bool isPolyline) const
  400. {
  401. const String pointsAtt (xml->getStringAttribute ("points"));
  402. String::CharPointerType points (pointsAtt.getCharPointer());
  403. Path path;
  404. Point<float> p;
  405. if (parseCoords (points, p, true))
  406. {
  407. Point<float> first (p), last;
  408. path.startNewSubPath (first);
  409. while (parseCoords (points, p, true))
  410. {
  411. last = p;
  412. path.lineTo (p);
  413. }
  414. if ((! isPolyline) || first == last)
  415. path.closeSubPath();
  416. }
  417. return parseShape (xml, path);
  418. }
  419. //==============================================================================
  420. Drawable* parseShape (const XmlPath& xml, Path& path,
  421. const bool shouldParseTransform = true) const
  422. {
  423. if (shouldParseTransform && xml->hasAttribute ("transform"))
  424. {
  425. SVGState newState (*this);
  426. newState.addTransform (xml);
  427. return newState.parseShape (xml, path, false);
  428. }
  429. DrawablePath* dp = new DrawablePath();
  430. dp->setName (xml->getStringAttribute ("id"));
  431. dp->setFill (Colours::transparentBlack);
  432. path.applyTransform (transform);
  433. dp->setPath (path);
  434. Path::Iterator iter (path);
  435. bool containsClosedSubPath = false;
  436. while (iter.next())
  437. {
  438. if (iter.elementType == Path::Iterator::closePath)
  439. {
  440. containsClosedSubPath = true;
  441. break;
  442. }
  443. }
  444. dp->setFill (getPathFillType (path,
  445. getStyleAttribute (xml, "fill"),
  446. getStyleAttribute (xml, "fill-opacity"),
  447. getStyleAttribute (xml, "opacity"),
  448. containsClosedSubPath ? Colours::black
  449. : Colours::transparentBlack));
  450. const String strokeType (getStyleAttribute (xml, "stroke"));
  451. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  452. {
  453. dp->setStrokeFill (getPathFillType (path, strokeType,
  454. getStyleAttribute (xml, "stroke-opacity"),
  455. getStyleAttribute (xml, "opacity"),
  456. Colours::transparentBlack));
  457. dp->setStrokeType (getStrokeFor (xml));
  458. }
  459. return dp;
  460. }
  461. struct SetGradientStopsOp
  462. {
  463. const SVGState* state;
  464. ColourGradient* gradient;
  465. void operator() (const XmlPath& xml)
  466. {
  467. state->addGradientStopsIn (*gradient, xml);
  468. }
  469. };
  470. void addGradientStopsIn (ColourGradient& cg, const XmlPath& fillXml) const
  471. {
  472. if (fillXml.xml != nullptr)
  473. {
  474. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  475. {
  476. int index = 0;
  477. Colour col (parseColour (getStyleAttribute (fillXml.getChild (e), "stop-color"), index, Colours::black));
  478. const String opacity (getStyleAttribute (fillXml.getChild (e), "stop-opacity", "1"));
  479. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  480. double offset = e->getDoubleAttribute ("offset");
  481. if (e->getStringAttribute ("offset").containsChar ('%'))
  482. offset *= 0.01;
  483. cg.addColour (jlimit (0.0, 1.0, offset), col);
  484. }
  485. }
  486. }
  487. FillType getGradientFillType (const XmlPath& fillXml,
  488. const Path& path,
  489. const float opacity) const
  490. {
  491. ColourGradient gradient;
  492. {
  493. const String id (fillXml->getStringAttribute ("xlink:href"));
  494. if (id.startsWithChar ('#'))
  495. {
  496. SetGradientStopsOp op = { this, &gradient, };
  497. findElementForId (topLevelXml, id.substring (1), op);
  498. }
  499. }
  500. addGradientStopsIn (gradient, fillXml);
  501. if (gradient.getNumColours() > 0)
  502. {
  503. gradient.addColour (0.0, gradient.getColour (0));
  504. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  505. }
  506. else
  507. {
  508. gradient.addColour (0.0, Colours::black);
  509. gradient.addColour (1.0, Colours::black);
  510. }
  511. if (opacity < 1.0f)
  512. gradient.multiplyOpacity (opacity);
  513. jassert (gradient.getNumColours() > 0);
  514. gradient.isRadial = fillXml->hasTagNameIgnoringNamespace ("radialGradient");
  515. float gradientWidth = viewBoxW;
  516. float gradientHeight = viewBoxH;
  517. float dx = 0.0f;
  518. float dy = 0.0f;
  519. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  520. if (! userSpace)
  521. {
  522. const Rectangle<float> bounds (path.getBounds());
  523. dx = bounds.getX();
  524. dy = bounds.getY();
  525. gradientWidth = bounds.getWidth();
  526. gradientHeight = bounds.getHeight();
  527. }
  528. if (gradient.isRadial)
  529. {
  530. if (userSpace)
  531. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  532. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  533. else
  534. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  535. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  536. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  537. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  538. //xxx (the fx, fy focal point isn't handled properly here..)
  539. }
  540. else
  541. {
  542. if (userSpace)
  543. {
  544. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  545. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  546. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  547. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  548. }
  549. else
  550. {
  551. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  552. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  553. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  554. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  555. }
  556. if (gradient.point1 == gradient.point2)
  557. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  558. }
  559. FillType type (gradient);
  560. const AffineTransform gradientTransform (parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  561. .followedBy (transform));
  562. if (gradient.isRadial)
  563. {
  564. type.transform = gradientTransform;
  565. }
  566. else
  567. {
  568. // Transform the perpendicular vector into the new coordinate space for the gradient.
  569. // This vector is now the slope of the linear gradient as it should appear in the new coord space
  570. const Point<float> perpendicular (Point<float> (gradient.point2.y - gradient.point1.y,
  571. gradient.point1.x - gradient.point2.x)
  572. .transformedBy (gradientTransform.withAbsoluteTranslation (0, 0)));
  573. const Point<float> newGradPoint1 (gradient.point1.transformedBy (gradientTransform));
  574. const Point<float> newGradPoint2 (gradient.point2.transformedBy (gradientTransform));
  575. // Project the transformed gradient vector onto the transformed slope of the linear
  576. // gradient as it should appear in the new coordinate space
  577. const float scale = perpendicular.getDotProduct (newGradPoint2 - newGradPoint1)
  578. / perpendicular.getDotProduct (perpendicular);
  579. type.gradient->point1 = newGradPoint1;
  580. type.gradient->point2 = newGradPoint2 - perpendicular * scale;
  581. }
  582. return type;
  583. }
  584. struct GetFillTypeOp
  585. {
  586. const SVGState* state;
  587. FillType* dest;
  588. const Path* path;
  589. float opacity;
  590. void operator() (const XmlPath& xml)
  591. {
  592. if (xml->hasTagNameIgnoringNamespace ("linearGradient")
  593. || xml->hasTagNameIgnoringNamespace ("radialGradient"))
  594. *dest = state->getGradientFillType (xml, *path, opacity);
  595. }
  596. };
  597. FillType getPathFillType (const Path& path,
  598. const String& fill,
  599. const String& fillOpacity,
  600. const String& overallOpacity,
  601. const Colour defaultColour) const
  602. {
  603. float opacity = 1.0f;
  604. if (overallOpacity.isNotEmpty())
  605. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  606. if (fillOpacity.isNotEmpty())
  607. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  608. if (fill.startsWithIgnoreCase ("url"))
  609. {
  610. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  611. .upToLastOccurrenceOf (")", false, false).trim());
  612. FillType result;
  613. GetFillTypeOp op = { this, &result, &path, opacity };
  614. if (findElementForId (topLevelXml, id, op))
  615. return result;
  616. }
  617. if (fill.equalsIgnoreCase ("none"))
  618. return Colours::transparentBlack;
  619. int i = 0;
  620. return parseColour (fill, i, defaultColour).withMultipliedAlpha (opacity);
  621. }
  622. PathStrokeType getStrokeFor (const XmlPath& xml) const
  623. {
  624. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  625. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  626. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  627. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  628. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  629. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  630. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  631. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  632. if (join.equalsIgnoreCase ("round"))
  633. joinStyle = PathStrokeType::curved;
  634. else if (join.equalsIgnoreCase ("bevel"))
  635. joinStyle = PathStrokeType::beveled;
  636. if (cap.equalsIgnoreCase ("round"))
  637. capStyle = PathStrokeType::rounded;
  638. else if (cap.equalsIgnoreCase ("square"))
  639. capStyle = PathStrokeType::square;
  640. float ox = 0.0f, oy = 0.0f;
  641. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  642. transform.transformPoints (ox, oy, x, y);
  643. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  644. joinStyle, capStyle);
  645. }
  646. //==============================================================================
  647. Drawable* parseText (const XmlPath& xml)
  648. {
  649. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  650. getCoordList (xCoords, getInheritedAttribute (xml, "x"), true, true);
  651. getCoordList (yCoords, getInheritedAttribute (xml, "y"), true, false);
  652. getCoordList (dxCoords, getInheritedAttribute (xml, "dx"), true, true);
  653. getCoordList (dyCoords, getInheritedAttribute (xml, "dy"), true, false);
  654. //xxx not done text yet!
  655. forEachXmlChildElement (*xml, e)
  656. {
  657. if (e->isTextElement())
  658. {
  659. const String text (e->getText());
  660. Path path;
  661. Drawable* s = parseShape (xml.getChild (e), path);
  662. delete s; // xxx not finished!
  663. }
  664. else if (e->hasTagNameIgnoringNamespace ("tspan"))
  665. {
  666. Drawable* s = parseText (xml.getChild (e));
  667. delete s; // xxx not finished!
  668. }
  669. }
  670. return nullptr;
  671. }
  672. //==============================================================================
  673. void addTransform (const XmlPath& xml)
  674. {
  675. transform = parseTransform (xml->getStringAttribute ("transform"))
  676. .followedBy (transform);
  677. }
  678. //==============================================================================
  679. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  680. {
  681. String number;
  682. if (! parseNextNumber (s, number, allowUnits))
  683. {
  684. value = 0;
  685. return false;
  686. }
  687. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  688. return true;
  689. }
  690. bool parseCoords (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  691. {
  692. return parseCoord (s, p.x, allowUnits, true)
  693. && parseCoord (s, p.y, allowUnits, false);
  694. }
  695. bool parseCoordsOrSkip (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  696. {
  697. const bool b = parseCoords (s, p, allowUnits);
  698. if (! b)
  699. ++s;
  700. return b;
  701. }
  702. float getCoordLength (const String& s, const float sizeForProportions) const
  703. {
  704. float n = s.getFloatValue();
  705. const int len = s.length();
  706. if (len > 2)
  707. {
  708. const float dpi = 96.0f;
  709. const juce_wchar n1 = s [len - 2];
  710. const juce_wchar n2 = s [len - 1];
  711. if (n1 == 'i' && n2 == 'n') n *= dpi;
  712. else if (n1 == 'm' && n2 == 'm') n *= dpi / 25.4f;
  713. else if (n1 == 'c' && n2 == 'm') n *= dpi / 2.54f;
  714. else if (n1 == 'p' && n2 == 'c') n *= 15.0f;
  715. else if (n2 == '%') n *= 0.01f * sizeForProportions;
  716. }
  717. return n;
  718. }
  719. float getCoordLength (const XmlPath& xml, const char* attName, const float sizeForProportions) const
  720. {
  721. return getCoordLength (xml->getStringAttribute (attName), sizeForProportions);
  722. }
  723. void getCoordList (Array <float>& coords, const String& list,
  724. const bool allowUnits, const bool isX) const
  725. {
  726. String::CharPointerType text (list.getCharPointer());
  727. float value;
  728. while (parseCoord (text, value, allowUnits, isX))
  729. coords.add (value);
  730. }
  731. //==============================================================================
  732. void parseCSSStyle (const XmlPath& xml)
  733. {
  734. cssStyleText = xml->getAllSubText() + "\n" + cssStyleText;
  735. }
  736. static String::CharPointerType findStyleItem (String::CharPointerType source, String::CharPointerType name)
  737. {
  738. const int nameLength = (int) name.length();
  739. while (! source.isEmpty())
  740. {
  741. if (source.getAndAdvance() == '.'
  742. && CharacterFunctions::compareIgnoreCaseUpTo (source, name, nameLength) == 0)
  743. {
  744. String::CharPointerType endOfName ((source + nameLength).findEndOfWhitespace());
  745. if (*endOfName == '{')
  746. return endOfName;
  747. }
  748. }
  749. return source;
  750. }
  751. String getStyleAttribute (const XmlPath& xml, const String& attributeName,
  752. const String& defaultValue = String::empty) const
  753. {
  754. if (xml->hasAttribute (attributeName))
  755. return xml->getStringAttribute (attributeName, defaultValue);
  756. const String styleAtt (xml->getStringAttribute ("style"));
  757. if (styleAtt.isNotEmpty())
  758. {
  759. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  760. if (value.isNotEmpty())
  761. return value;
  762. }
  763. else if (xml->hasAttribute ("class"))
  764. {
  765. String::CharPointerType openBrace = findStyleItem (cssStyleText.getCharPointer(),
  766. xml->getStringAttribute ("class").getCharPointer());
  767. if (! openBrace.isEmpty())
  768. {
  769. String::CharPointerType closeBrace = CharacterFunctions::find (openBrace, (juce_wchar) '}');
  770. if (closeBrace != openBrace)
  771. {
  772. const String value (getAttributeFromStyleList (String (openBrace + 1, closeBrace),
  773. attributeName, defaultValue));
  774. if (value.isNotEmpty())
  775. return value;
  776. }
  777. }
  778. }
  779. if (xml.parent != nullptr)
  780. return getStyleAttribute (*xml.parent, attributeName, defaultValue);
  781. return defaultValue;
  782. }
  783. String getInheritedAttribute (const XmlPath& xml, const String& attributeName) const
  784. {
  785. if (xml->hasAttribute (attributeName))
  786. return xml->getStringAttribute (attributeName);
  787. if (xml.parent != nullptr)
  788. return getInheritedAttribute (*xml.parent, attributeName);
  789. return String::empty;
  790. }
  791. //==============================================================================
  792. static bool isIdentifierChar (const juce_wchar c)
  793. {
  794. return CharacterFunctions::isLetter (c) || c == '-';
  795. }
  796. static String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  797. {
  798. int i = 0;
  799. for (;;)
  800. {
  801. i = list.indexOf (i, attributeName);
  802. if (i < 0)
  803. break;
  804. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  805. && ! isIdentifierChar (list [i + attributeName.length()]))
  806. {
  807. i = list.indexOfChar (i, ':');
  808. if (i < 0)
  809. break;
  810. int end = list.indexOfChar (i, ';');
  811. if (end < 0)
  812. end = 0x7ffff;
  813. return list.substring (i + 1, end).trim();
  814. }
  815. ++i;
  816. }
  817. return defaultValue;
  818. }
  819. //==============================================================================
  820. static bool parseNextNumber (String::CharPointerType& text, String& value, const bool allowUnits)
  821. {
  822. String::CharPointerType s (text);
  823. while (s.isWhitespace() || *s == ',')
  824. ++s;
  825. String::CharPointerType start (s);
  826. if (s.isDigit() || *s == '.' || *s == '-')
  827. ++s;
  828. while (s.isDigit() || *s == '.')
  829. ++s;
  830. if ((*s == 'e' || *s == 'E')
  831. && ((s + 1).isDigit() || s[1] == '-' || s[1] == '+'))
  832. {
  833. s += 2;
  834. while (s.isDigit())
  835. ++s;
  836. }
  837. if (allowUnits)
  838. while (s.isLetter())
  839. ++s;
  840. if (s == start)
  841. {
  842. text = s;
  843. return false;
  844. }
  845. value = String (start, s);
  846. while (s.isWhitespace() || *s == ',')
  847. ++s;
  848. text = s;
  849. return true;
  850. }
  851. //==============================================================================
  852. static Colour parseColour (const String& s, int& index, const Colour defaultColour)
  853. {
  854. if (s [index] == '#')
  855. {
  856. uint32 hex[6] = { 0 };
  857. int numChars = 0;
  858. for (int i = 6; --i >= 0;)
  859. {
  860. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  861. if (hexValue >= 0)
  862. hex [numChars++] = (uint32) hexValue;
  863. else
  864. break;
  865. }
  866. if (numChars <= 3)
  867. return Colour ((uint8) (hex [0] * 0x11),
  868. (uint8) (hex [1] * 0x11),
  869. (uint8) (hex [2] * 0x11));
  870. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  871. (uint8) ((hex [2] << 4) + hex [3]),
  872. (uint8) ((hex [4] << 4) + hex [5]));
  873. }
  874. if (s [index] == 'r'
  875. && s [index + 1] == 'g'
  876. && s [index + 2] == 'b')
  877. {
  878. const int openBracket = s.indexOfChar (index, '(');
  879. const int closeBracket = s.indexOfChar (openBracket, ')');
  880. if (openBracket >= 3 && closeBracket > openBracket)
  881. {
  882. index = closeBracket;
  883. StringArray tokens;
  884. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  885. tokens.trim();
  886. tokens.removeEmptyStrings();
  887. if (tokens[0].containsChar ('%'))
  888. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  889. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  890. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  891. else
  892. return Colour ((uint8) tokens[0].getIntValue(),
  893. (uint8) tokens[1].getIntValue(),
  894. (uint8) tokens[2].getIntValue());
  895. }
  896. }
  897. return Colours::findColourForName (s, defaultColour);
  898. }
  899. static AffineTransform parseTransform (String t)
  900. {
  901. AffineTransform result;
  902. while (t.isNotEmpty())
  903. {
  904. StringArray tokens;
  905. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  906. .upToFirstOccurrenceOf (")", false, false),
  907. ", ", String::empty);
  908. tokens.removeEmptyStrings (true);
  909. float numbers [6];
  910. for (int i = 0; i < 6; ++i)
  911. numbers[i] = tokens[i].getFloatValue();
  912. AffineTransform trans;
  913. if (t.startsWithIgnoreCase ("matrix"))
  914. {
  915. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  916. numbers[1], numbers[3], numbers[5]);
  917. }
  918. else if (t.startsWithIgnoreCase ("translate"))
  919. {
  920. jassert (tokens.size() == 2);
  921. trans = AffineTransform::translation (numbers[0], numbers[1]);
  922. }
  923. else if (t.startsWithIgnoreCase ("scale"))
  924. {
  925. if (tokens.size() == 1)
  926. trans = AffineTransform::scale (numbers[0]);
  927. else
  928. trans = AffineTransform::scale (numbers[0], numbers[1]);
  929. }
  930. else if (t.startsWithIgnoreCase ("rotate"))
  931. {
  932. if (tokens.size() != 3)
  933. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  934. else
  935. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  936. numbers[1], numbers[2]);
  937. }
  938. else if (t.startsWithIgnoreCase ("skewX"))
  939. {
  940. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  941. 0.0f, 1.0f, 0.0f);
  942. }
  943. else if (t.startsWithIgnoreCase ("skewY"))
  944. {
  945. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  946. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  947. }
  948. result = trans.followedBy (result);
  949. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  950. }
  951. return result;
  952. }
  953. static void endpointToCentreParameters (const double x1, const double y1,
  954. const double x2, const double y2,
  955. const double angle,
  956. const bool largeArc, const bool sweep,
  957. double& rx, double& ry,
  958. double& centreX, double& centreY,
  959. double& startAngle, double& deltaAngle)
  960. {
  961. const double midX = (x1 - x2) * 0.5;
  962. const double midY = (y1 - y2) * 0.5;
  963. const double cosAngle = cos (angle);
  964. const double sinAngle = sin (angle);
  965. const double xp = cosAngle * midX + sinAngle * midY;
  966. const double yp = cosAngle * midY - sinAngle * midX;
  967. const double xp2 = xp * xp;
  968. const double yp2 = yp * yp;
  969. double rx2 = rx * rx;
  970. double ry2 = ry * ry;
  971. const double s = (xp2 / rx2) + (yp2 / ry2);
  972. double c;
  973. if (s <= 1.0)
  974. {
  975. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  976. / (( rx2 * yp2) + (ry2 * xp2))));
  977. if (largeArc == sweep)
  978. c = -c;
  979. }
  980. else
  981. {
  982. const double s2 = std::sqrt (s);
  983. rx *= s2;
  984. ry *= s2;
  985. c = 0;
  986. }
  987. const double cpx = ((rx * yp) / ry) * c;
  988. const double cpy = ((-ry * xp) / rx) * c;
  989. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  990. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  991. const double ux = (xp - cpx) / rx;
  992. const double uy = (yp - cpy) / ry;
  993. const double vx = (-xp - cpx) / rx;
  994. const double vy = (-yp - cpy) / ry;
  995. const double length = juce_hypot (ux, uy);
  996. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  997. if (uy < 0)
  998. startAngle = -startAngle;
  999. startAngle += double_Pi * 0.5;
  1000. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  1001. / (length * juce_hypot (vx, vy))));
  1002. if ((ux * vy) - (uy * vx) < 0)
  1003. deltaAngle = -deltaAngle;
  1004. if (sweep)
  1005. {
  1006. if (deltaAngle < 0)
  1007. deltaAngle += double_Pi * 2.0;
  1008. }
  1009. else
  1010. {
  1011. if (deltaAngle > 0)
  1012. deltaAngle -= double_Pi * 2.0;
  1013. }
  1014. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  1015. }
  1016. template <typename OperationType>
  1017. static bool findElementForId (const XmlPath& parent, const String& id, OperationType& op)
  1018. {
  1019. forEachXmlChildElement (*parent, e)
  1020. {
  1021. if (e->compareAttribute ("id", id))
  1022. {
  1023. op (parent.getChild (e));
  1024. return true;
  1025. }
  1026. if (findElementForId (parent.getChild (e), id, op))
  1027. return true;
  1028. }
  1029. return false;
  1030. }
  1031. SVGState& operator= (const SVGState&) JUCE_DELETED_FUNCTION;
  1032. };
  1033. //==============================================================================
  1034. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  1035. {
  1036. SVGState state (&svgDocument);
  1037. return state.parseSVGElement (SVGState::XmlPath (&svgDocument, nullptr));
  1038. }
  1039. Path Drawable::parseSVGPath (const String& svgPath)
  1040. {
  1041. SVGState state (nullptr);
  1042. Path p;
  1043. state.parsePathString (p, svgPath);
  1044. return p;
  1045. }