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.

1248 lines
44KB

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