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.

1238 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")) 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. const XmlElement* const group = xml.getChildByName ("g");
  119. if (group != nullptr)
  120. return parseGroupElement (*group);
  121. return nullptr;
  122. }
  123. DrawableComposite* parseGroupElement (const XmlElement& xml)
  124. {
  125. DrawableComposite* const drawable = new DrawableComposite();
  126. drawable->setName (xml.getStringAttribute ("id"));
  127. if (xml.hasAttribute ("transform"))
  128. {
  129. SVGState newState (*this);
  130. newState.addTransform (xml);
  131. newState.parseSubElements (xml, drawable);
  132. }
  133. else
  134. {
  135. parseSubElements (xml, drawable);
  136. }
  137. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  138. return drawable;
  139. }
  140. //==============================================================================
  141. Drawable* parsePath (const XmlElement& xml) const
  142. {
  143. const String dAttribute (xml.getStringAttribute ("d").trimStart());
  144. String::CharPointerType d (dAttribute.getCharPointer());
  145. Path path;
  146. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  147. path.setUsingNonZeroWinding (false);
  148. Point<float> subpathStart, last, last2, p1, p2, p3;
  149. juce_wchar lastCommandChar = 0;
  150. bool isRelative = true;
  151. bool carryOn = true;
  152. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  153. while (! d.isEmpty())
  154. {
  155. if (validCommandChars.indexOf (*d) >= 0)
  156. {
  157. lastCommandChar = d.getAndAdvance();
  158. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  159. }
  160. switch (lastCommandChar)
  161. {
  162. case 'M':
  163. case 'm':
  164. case 'L':
  165. case 'l':
  166. if (parseCoordsOrSkip (d, p1, false))
  167. {
  168. if (isRelative)
  169. p1 += last;
  170. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  171. {
  172. subpathStart = p1;
  173. path.startNewSubPath (p1);
  174. lastCommandChar = 'l';
  175. }
  176. else
  177. path.lineTo (p1);
  178. last2 = last;
  179. last = p1;
  180. }
  181. break;
  182. case 'H':
  183. case 'h':
  184. if (parseCoord (d, p1.x, false, true))
  185. {
  186. if (isRelative)
  187. p1.x += last.x;
  188. path.lineTo (p1.x, last.y);
  189. last2.x = last.x;
  190. last.x = p1.x;
  191. }
  192. else
  193. {
  194. ++d;
  195. }
  196. break;
  197. case 'V':
  198. case 'v':
  199. if (parseCoord (d, p1.y, false, false))
  200. {
  201. if (isRelative)
  202. p1.y += last.y;
  203. path.lineTo (last.x, p1.y);
  204. last2.y = last.y;
  205. last.y = p1.y;
  206. }
  207. else
  208. {
  209. ++d;
  210. }
  211. break;
  212. case 'C':
  213. case 'c':
  214. if (parseCoordsOrSkip (d, p1, false)
  215. && parseCoordsOrSkip (d, p2, false)
  216. && parseCoordsOrSkip (d, p3, false))
  217. {
  218. if (isRelative)
  219. {
  220. p1 += last;
  221. p2 += last;
  222. p3 += last;
  223. }
  224. path.cubicTo (p1, p2, p3);
  225. last2 = p2;
  226. last = p3;
  227. }
  228. break;
  229. case 'S':
  230. case 's':
  231. if (parseCoordsOrSkip (d, p1, false)
  232. && parseCoordsOrSkip (d, p3, false))
  233. {
  234. if (isRelative)
  235. {
  236. p1 += last;
  237. p3 += last;
  238. }
  239. p2 = last + (last - last2);
  240. path.cubicTo (p2, p1, p3);
  241. last2 = p1;
  242. last = p3;
  243. }
  244. break;
  245. case 'Q':
  246. case 'q':
  247. if (parseCoordsOrSkip (d, p1, false)
  248. && parseCoordsOrSkip (d, p2, false))
  249. {
  250. if (isRelative)
  251. {
  252. p1 += last;
  253. p2 += last;
  254. }
  255. path.quadraticTo (p1, p2);
  256. last2 = p1;
  257. last = p2;
  258. }
  259. break;
  260. case 'T':
  261. case 't':
  262. if (parseCoordsOrSkip (d, p1, false))
  263. {
  264. if (isRelative)
  265. p1 += last;
  266. p2 = last + (last - last2);
  267. path.quadraticTo (p2, p1);
  268. last2 = p2;
  269. last = p1;
  270. }
  271. break;
  272. case 'A':
  273. case 'a':
  274. if (parseCoordsOrSkip (d, p1, false))
  275. {
  276. String num;
  277. if (parseNextNumber (d, num, false))
  278. {
  279. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  280. if (parseNextNumber (d, num, false))
  281. {
  282. const bool largeArc = num.getIntValue() != 0;
  283. if (parseNextNumber (d, num, false))
  284. {
  285. const bool sweep = num.getIntValue() != 0;
  286. if (parseCoordsOrSkip (d, p2, false))
  287. {
  288. if (isRelative)
  289. p2 += last;
  290. if (last != p2)
  291. {
  292. double centreX, centreY, startAngle, deltaAngle;
  293. double rx = p1.x, ry = p1.y;
  294. endpointToCentreParameters (last.x, last.y, p2.x, p2.y,
  295. angle, largeArc, sweep,
  296. rx, ry, centreX, centreY,
  297. startAngle, deltaAngle);
  298. path.addCentredArc ((float) centreX, (float) centreY,
  299. (float) rx, (float) ry,
  300. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  301. false);
  302. path.lineTo (p2);
  303. }
  304. last2 = last;
  305. last = p2;
  306. }
  307. }
  308. }
  309. }
  310. }
  311. break;
  312. case 'Z':
  313. case 'z':
  314. path.closeSubPath();
  315. last = last2 = subpathStart;
  316. d = d.findEndOfWhitespace();
  317. lastCommandChar = 'M';
  318. break;
  319. default:
  320. carryOn = false;
  321. break;
  322. }
  323. if (! carryOn)
  324. break;
  325. }
  326. return parseShape (xml, path);
  327. }
  328. Drawable* parseRect (const XmlElement& xml) const
  329. {
  330. Path rect;
  331. const bool hasRX = xml.hasAttribute ("rx");
  332. const bool hasRY = xml.hasAttribute ("ry");
  333. if (hasRX || hasRY)
  334. {
  335. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  336. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  337. if (! hasRX)
  338. rx = ry;
  339. else if (! hasRY)
  340. ry = rx;
  341. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  342. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  343. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  344. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  345. rx, ry);
  346. }
  347. else
  348. {
  349. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  350. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  351. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  352. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  353. }
  354. return parseShape (xml, rect);
  355. }
  356. Drawable* parseCircle (const XmlElement& xml) const
  357. {
  358. Path circle;
  359. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  360. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  361. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  362. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  363. return parseShape (xml, circle);
  364. }
  365. Drawable* parseEllipse (const XmlElement& xml) const
  366. {
  367. Path ellipse;
  368. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  369. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  370. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  371. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  372. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  373. return parseShape (xml, ellipse);
  374. }
  375. Drawable* parseLine (const XmlElement& xml) const
  376. {
  377. Path line;
  378. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  379. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  380. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  381. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  382. line.startNewSubPath (x1, y1);
  383. line.lineTo (x2, y2);
  384. return parseShape (xml, line);
  385. }
  386. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  387. {
  388. const String pointsAtt (xml.getStringAttribute ("points"));
  389. String::CharPointerType points (pointsAtt.getCharPointer());
  390. Path path;
  391. Point<float> p;
  392. if (parseCoords (points, p, true))
  393. {
  394. Point<float> first (p), last;
  395. path.startNewSubPath (first);
  396. while (parseCoords (points, p, true))
  397. {
  398. last = p;
  399. path.lineTo (p);
  400. }
  401. if ((! isPolyline) || first == last)
  402. path.closeSubPath();
  403. }
  404. return parseShape (xml, path);
  405. }
  406. //==============================================================================
  407. Drawable* parseShape (const XmlElement& xml, Path& path,
  408. const bool shouldParseTransform = true) const
  409. {
  410. if (shouldParseTransform && xml.hasAttribute ("transform"))
  411. {
  412. SVGState newState (*this);
  413. newState.addTransform (xml);
  414. return newState.parseShape (xml, path, false);
  415. }
  416. DrawablePath* dp = new DrawablePath();
  417. dp->setName (xml.getStringAttribute ("id"));
  418. dp->setFill (Colours::transparentBlack);
  419. path.applyTransform (transform);
  420. dp->setPath (path);
  421. Path::Iterator iter (path);
  422. bool containsClosedSubPath = false;
  423. while (iter.next())
  424. {
  425. if (iter.elementType == Path::Iterator::closePath)
  426. {
  427. containsClosedSubPath = true;
  428. break;
  429. }
  430. }
  431. dp->setFill (getPathFillType (path,
  432. getStyleAttribute (&xml, "fill"),
  433. getStyleAttribute (&xml, "fill-opacity"),
  434. getStyleAttribute (&xml, "opacity"),
  435. containsClosedSubPath ? Colours::black
  436. : Colours::transparentBlack));
  437. const String strokeType (getStyleAttribute (&xml, "stroke"));
  438. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  439. {
  440. dp->setStrokeFill (getPathFillType (path, strokeType,
  441. getStyleAttribute (&xml, "stroke-opacity"),
  442. getStyleAttribute (&xml, "opacity"),
  443. Colours::transparentBlack));
  444. dp->setStrokeType (getStrokeFor (&xml));
  445. }
  446. return dp;
  447. }
  448. const XmlElement* findLinkedElement (const XmlElement* e) const
  449. {
  450. const String id (e->getStringAttribute ("xlink:href"));
  451. if (! id.startsWithChar ('#'))
  452. return nullptr;
  453. return findElementForId (topLevelXml, id.substring (1));
  454. }
  455. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  456. {
  457. if (fillXml == 0)
  458. return;
  459. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  460. {
  461. int index = 0;
  462. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  463. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  464. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  465. double offset = e->getDoubleAttribute ("offset");
  466. if (e->getStringAttribute ("offset").containsChar ('%'))
  467. offset *= 0.01;
  468. cg.addColour (jlimit (0.0, 1.0, offset), col);
  469. }
  470. }
  471. FillType getPathFillType (const Path& path,
  472. const String& fill,
  473. const String& fillOpacity,
  474. const String& overallOpacity,
  475. const Colour& defaultColour) const
  476. {
  477. float opacity = 1.0f;
  478. if (overallOpacity.isNotEmpty())
  479. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  480. if (fillOpacity.isNotEmpty())
  481. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  482. if (fill.startsWithIgnoreCase ("url"))
  483. {
  484. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  485. .upToLastOccurrenceOf (")", false, false).trim());
  486. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  487. if (fillXml != nullptr
  488. && (fillXml->hasTagName ("linearGradient")
  489. || fillXml->hasTagName ("radialGradient")))
  490. {
  491. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  492. ColourGradient gradient;
  493. addGradientStopsIn (gradient, inheritedFrom);
  494. addGradientStopsIn (gradient, fillXml);
  495. if (gradient.getNumColours() > 0)
  496. {
  497. gradient.addColour (0.0, gradient.getColour (0));
  498. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  499. }
  500. else
  501. {
  502. gradient.addColour (0.0, Colours::black);
  503. gradient.addColour (1.0, Colours::black);
  504. }
  505. if (overallOpacity.isNotEmpty())
  506. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  507. jassert (gradient.getNumColours() > 0);
  508. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  509. float gradientWidth = viewBoxW;
  510. float gradientHeight = viewBoxH;
  511. float dx = 0.0f;
  512. float dy = 0.0f;
  513. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  514. if (! userSpace)
  515. {
  516. const Rectangle<float> bounds (path.getBounds());
  517. dx = bounds.getX();
  518. dy = bounds.getY();
  519. gradientWidth = bounds.getWidth();
  520. gradientHeight = bounds.getHeight();
  521. }
  522. if (gradient.isRadial)
  523. {
  524. if (userSpace)
  525. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  526. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  527. else
  528. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  529. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  530. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  531. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  532. //xxx (the fx, fy focal point isn't handled properly here..)
  533. }
  534. else
  535. {
  536. if (userSpace)
  537. {
  538. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  539. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  540. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  541. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  542. }
  543. else
  544. {
  545. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  546. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  547. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  548. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  549. }
  550. if (gradient.point1 == gradient.point2)
  551. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  552. }
  553. FillType type (gradient);
  554. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  555. .followedBy (transform);
  556. return type;
  557. }
  558. }
  559. if (fill.equalsIgnoreCase ("none"))
  560. return Colours::transparentBlack;
  561. int i = 0;
  562. const Colour colour (parseColour (fill, i, defaultColour));
  563. return colour.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], 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. const XmlElement* const found = findElementForId (e, id);
  968. if (found != nullptr)
  969. return found;
  970. }
  971. return nullptr;
  972. }
  973. SVGState& operator= (const SVGState&);
  974. };
  975. //==============================================================================
  976. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  977. {
  978. SVGState state (&svgDocument);
  979. return state.parseSVGElement (svgDocument);
  980. }