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.

1233 lines
43KB

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