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.

1279 lines
45KB

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