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.

1247 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. break;
  327. default:
  328. carryOn = false;
  329. break;
  330. }
  331. if (! carryOn)
  332. break;
  333. }
  334. return parseShape (xml, path);
  335. }
  336. Drawable* parseRect (const XmlElement& xml) const
  337. {
  338. Path rect;
  339. const bool hasRX = xml.hasAttribute ("rx");
  340. const bool hasRY = xml.hasAttribute ("ry");
  341. if (hasRX || hasRY)
  342. {
  343. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  344. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  345. if (! hasRX)
  346. rx = ry;
  347. else if (! hasRY)
  348. ry = rx;
  349. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  350. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  351. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  352. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  353. rx, ry);
  354. }
  355. else
  356. {
  357. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  358. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  359. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  360. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  361. }
  362. return parseShape (xml, rect);
  363. }
  364. Drawable* parseCircle (const XmlElement& xml) const
  365. {
  366. Path circle;
  367. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  368. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  369. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  370. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  371. return parseShape (xml, circle);
  372. }
  373. Drawable* parseEllipse (const XmlElement& xml) const
  374. {
  375. Path ellipse;
  376. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  377. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  378. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  379. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  380. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  381. return parseShape (xml, ellipse);
  382. }
  383. Drawable* parseLine (const XmlElement& xml) const
  384. {
  385. Path line;
  386. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  387. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  388. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  389. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  390. line.startNewSubPath (x1, y1);
  391. line.lineTo (x2, y2);
  392. return parseShape (xml, line);
  393. }
  394. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  395. {
  396. const String pointsAtt (xml.getStringAttribute ("points"));
  397. String::CharPointerType points (pointsAtt.getCharPointer());
  398. Path path;
  399. Point<float> p;
  400. if (parseCoords (points, p, true))
  401. {
  402. Point<float> first (p), last;
  403. path.startNewSubPath (first);
  404. while (parseCoords (points, p, true))
  405. {
  406. last = p;
  407. path.lineTo (p);
  408. }
  409. if ((! isPolyline) || first == last)
  410. path.closeSubPath();
  411. }
  412. return parseShape (xml, path);
  413. }
  414. //==============================================================================
  415. Drawable* parseShape (const XmlElement& xml, Path& path,
  416. const bool shouldParseTransform = true) const
  417. {
  418. if (shouldParseTransform && xml.hasAttribute ("transform"))
  419. {
  420. SVGState newState (*this);
  421. newState.addTransform (xml);
  422. return newState.parseShape (xml, path, false);
  423. }
  424. DrawablePath* dp = new DrawablePath();
  425. dp->setName (xml.getStringAttribute ("id"));
  426. dp->setFill (Colours::transparentBlack);
  427. path.applyTransform (transform);
  428. dp->setPath (path);
  429. Path::Iterator iter (path);
  430. bool containsClosedSubPath = false;
  431. while (iter.next())
  432. {
  433. if (iter.elementType == Path::Iterator::closePath)
  434. {
  435. containsClosedSubPath = true;
  436. break;
  437. }
  438. }
  439. dp->setFill (getPathFillType (path,
  440. getStyleAttribute (&xml, "fill"),
  441. getStyleAttribute (&xml, "fill-opacity"),
  442. getStyleAttribute (&xml, "opacity"),
  443. containsClosedSubPath ? Colours::black
  444. : Colours::transparentBlack));
  445. const String strokeType (getStyleAttribute (&xml, "stroke"));
  446. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  447. {
  448. dp->setStrokeFill (getPathFillType (path, strokeType,
  449. getStyleAttribute (&xml, "stroke-opacity"),
  450. getStyleAttribute (&xml, "opacity"),
  451. Colours::transparentBlack));
  452. dp->setStrokeType (getStrokeFor (&xml));
  453. }
  454. return dp;
  455. }
  456. const XmlElement* findLinkedElement (const XmlElement* e) const
  457. {
  458. const String id (e->getStringAttribute ("xlink:href"));
  459. if (! id.startsWithChar ('#'))
  460. return nullptr;
  461. return findElementForId (topLevelXml, id.substring (1));
  462. }
  463. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  464. {
  465. if (fillXml == 0)
  466. return;
  467. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  468. {
  469. int index = 0;
  470. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  471. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  472. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  473. double offset = e->getDoubleAttribute ("offset");
  474. if (e->getStringAttribute ("offset").containsChar ('%'))
  475. offset *= 0.01;
  476. cg.addColour (jlimit (0.0, 1.0, offset), col);
  477. }
  478. }
  479. FillType getPathFillType (const Path& path,
  480. const String& fill,
  481. const String& fillOpacity,
  482. const String& overallOpacity,
  483. const Colour& defaultColour) const
  484. {
  485. float opacity = 1.0f;
  486. if (overallOpacity.isNotEmpty())
  487. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  488. if (fillOpacity.isNotEmpty())
  489. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  490. if (fill.startsWithIgnoreCase ("url"))
  491. {
  492. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  493. .upToLastOccurrenceOf (")", false, false).trim());
  494. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  495. if (fillXml != nullptr
  496. && (fillXml->hasTagName ("linearGradient")
  497. || fillXml->hasTagName ("radialGradient")))
  498. {
  499. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  500. ColourGradient gradient;
  501. addGradientStopsIn (gradient, inheritedFrom);
  502. addGradientStopsIn (gradient, fillXml);
  503. if (gradient.getNumColours() > 0)
  504. {
  505. gradient.addColour (0.0, gradient.getColour (0));
  506. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  507. }
  508. else
  509. {
  510. gradient.addColour (0.0, Colours::black);
  511. gradient.addColour (1.0, Colours::black);
  512. }
  513. if (overallOpacity.isNotEmpty())
  514. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  515. jassert (gradient.getNumColours() > 0);
  516. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  517. float gradientWidth = viewBoxW;
  518. float gradientHeight = viewBoxH;
  519. float dx = 0.0f;
  520. float dy = 0.0f;
  521. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  522. if (! userSpace)
  523. {
  524. const Rectangle<float> bounds (path.getBounds());
  525. dx = bounds.getX();
  526. dy = bounds.getY();
  527. gradientWidth = bounds.getWidth();
  528. gradientHeight = bounds.getHeight();
  529. }
  530. if (gradient.isRadial)
  531. {
  532. if (userSpace)
  533. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  534. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  535. else
  536. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  537. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  538. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  539. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  540. //xxx (the fx, fy focal point isn't handled properly here..)
  541. }
  542. else
  543. {
  544. if (userSpace)
  545. {
  546. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  547. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  548. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  549. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  550. }
  551. else
  552. {
  553. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  554. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  555. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  556. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  557. }
  558. if (gradient.point1 == gradient.point2)
  559. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  560. }
  561. FillType type (gradient);
  562. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  563. .followedBy (transform);
  564. return type;
  565. }
  566. }
  567. if (fill.equalsIgnoreCase ("none"))
  568. return Colours::transparentBlack;
  569. int i = 0;
  570. const Colour colour (parseColour (fill, i, defaultColour));
  571. return colour.withMultipliedAlpha (opacity);
  572. }
  573. PathStrokeType getStrokeFor (const XmlElement* const xml) const
  574. {
  575. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  576. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  577. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  578. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  579. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  580. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  581. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  582. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  583. if (join.equalsIgnoreCase ("round"))
  584. joinStyle = PathStrokeType::curved;
  585. else if (join.equalsIgnoreCase ("bevel"))
  586. joinStyle = PathStrokeType::beveled;
  587. if (cap.equalsIgnoreCase ("round"))
  588. capStyle = PathStrokeType::rounded;
  589. else if (cap.equalsIgnoreCase ("square"))
  590. capStyle = PathStrokeType::square;
  591. float ox = 0.0f, oy = 0.0f;
  592. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  593. transform.transformPoints (ox, oy, x, y);
  594. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  595. joinStyle, capStyle);
  596. }
  597. //==============================================================================
  598. Drawable* parseText (const XmlElement& xml)
  599. {
  600. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  601. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  602. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  603. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  604. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  605. //xxx not done text yet!
  606. forEachXmlChildElement (xml, e)
  607. {
  608. if (e->isTextElement())
  609. {
  610. const String text (e->getText());
  611. Path path;
  612. Drawable* s = parseShape (*e, path);
  613. delete s; // xxx not finished!
  614. }
  615. else if (e->hasTagName ("tspan"))
  616. {
  617. Drawable* s = parseText (*e);
  618. delete s; // xxx not finished!
  619. }
  620. }
  621. return nullptr;
  622. }
  623. //==============================================================================
  624. void addTransform (const XmlElement& xml)
  625. {
  626. transform = parseTransform (xml.getStringAttribute ("transform"))
  627. .followedBy (transform);
  628. }
  629. //==============================================================================
  630. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  631. {
  632. String number;
  633. if (! parseNextNumber (s, number, allowUnits))
  634. {
  635. value = 0;
  636. return false;
  637. }
  638. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  639. return true;
  640. }
  641. bool parseCoords (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  642. {
  643. return parseCoord (s, p.x, allowUnits, true)
  644. && parseCoord (s, p.y, allowUnits, false);
  645. }
  646. bool parseCoordsOrSkip (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  647. {
  648. const bool b = parseCoords (s, p, allowUnits);
  649. if (! b)
  650. ++s;
  651. return b;
  652. }
  653. float getCoordLength (const String& s, const float sizeForProportions) const
  654. {
  655. float n = s.getFloatValue();
  656. const int len = s.length();
  657. if (len > 2)
  658. {
  659. const float dpi = 96.0f;
  660. const juce_wchar n1 = s [len - 2];
  661. const juce_wchar n2 = s [len - 1];
  662. if (n1 == 'i' && n2 == 'n') n *= dpi;
  663. else if (n1 == 'm' && n2 == 'm') n *= dpi / 25.4f;
  664. else if (n1 == 'c' && n2 == 'm') n *= dpi / 2.54f;
  665. else if (n1 == 'p' && n2 == 'c') n *= 15.0f;
  666. else if (n2 == '%') n *= 0.01f * sizeForProportions;
  667. }
  668. return n;
  669. }
  670. void getCoordList (Array <float>& coords, const String& list,
  671. const bool allowUnits, const bool isX) const
  672. {
  673. String::CharPointerType text (list.getCharPointer());
  674. float value;
  675. while (parseCoord (text, value, allowUnits, isX))
  676. coords.add (value);
  677. }
  678. //==============================================================================
  679. void parseCSSStyle (const XmlElement& xml)
  680. {
  681. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  682. }
  683. String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  684. const String& defaultValue = String::empty) const
  685. {
  686. if (xml->hasAttribute (attributeName))
  687. return xml->getStringAttribute (attributeName, defaultValue);
  688. const String styleAtt (xml->getStringAttribute ("style"));
  689. if (styleAtt.isNotEmpty())
  690. {
  691. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  692. if (value.isNotEmpty())
  693. return value;
  694. }
  695. else if (xml->hasAttribute ("class"))
  696. {
  697. const String className ("." + xml->getStringAttribute ("class"));
  698. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  699. if (index < 0)
  700. index = cssStyleText.indexOfIgnoreCase (className + "{");
  701. if (index >= 0)
  702. {
  703. const int openBracket = cssStyleText.indexOfChar (index, '{');
  704. if (openBracket > index)
  705. {
  706. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  707. if (closeBracket > openBracket)
  708. {
  709. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  710. if (value.isNotEmpty())
  711. return value;
  712. }
  713. }
  714. }
  715. }
  716. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  717. if (xml != nullptr)
  718. return getStyleAttribute (xml, attributeName, defaultValue);
  719. return defaultValue;
  720. }
  721. String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  722. {
  723. if (xml->hasAttribute (attributeName))
  724. return xml->getStringAttribute (attributeName);
  725. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  726. if (xml != nullptr)
  727. return getInheritedAttribute (xml, attributeName);
  728. return String::empty;
  729. }
  730. //==============================================================================
  731. static bool isIdentifierChar (const juce_wchar c)
  732. {
  733. return CharacterFunctions::isLetter (c) || c == '-';
  734. }
  735. static String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  736. {
  737. int i = 0;
  738. for (;;)
  739. {
  740. i = list.indexOf (i, attributeName);
  741. if (i < 0)
  742. break;
  743. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  744. && ! isIdentifierChar (list [i + attributeName.length()]))
  745. {
  746. i = list.indexOfChar (i, ':');
  747. if (i < 0)
  748. break;
  749. int end = list.indexOfChar (i, ';');
  750. if (end < 0)
  751. end = 0x7ffff;
  752. return list.substring (i + 1, end).trim();
  753. }
  754. ++i;
  755. }
  756. return defaultValue;
  757. }
  758. //==============================================================================
  759. static bool parseNextNumber (String::CharPointerType& s, String& value, const bool allowUnits)
  760. {
  761. while (s.isWhitespace() || *s == ',')
  762. ++s;
  763. String::CharPointerType start (s);
  764. int numChars = 0;
  765. if (s.isDigit() || *s == '.' || *s == '-')
  766. {
  767. ++numChars;
  768. ++s;
  769. }
  770. while (s.isDigit() || *s == '.')
  771. {
  772. ++numChars;
  773. ++s;
  774. }
  775. if ((*s == 'e' || *s == 'E')
  776. && ((s + 1).isDigit() || s[1] == '-' || s[1] == '+'))
  777. {
  778. s += 2;
  779. numChars += 2;
  780. while (s.isDigit())
  781. {
  782. ++numChars;
  783. ++s;
  784. }
  785. }
  786. if (allowUnits)
  787. {
  788. while (s.isLetter())
  789. {
  790. ++numChars;
  791. ++s;
  792. }
  793. }
  794. if (numChars == 0)
  795. return false;
  796. value = String (start, (size_t) numChars);
  797. while (s.isWhitespace() || *s == ',')
  798. ++s;
  799. return true;
  800. }
  801. //==============================================================================
  802. static Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  803. {
  804. if (s [index] == '#')
  805. {
  806. uint32 hex[6] = { 0 };
  807. int numChars = 0;
  808. for (int i = 6; --i >= 0;)
  809. {
  810. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  811. if (hexValue >= 0)
  812. hex [numChars++] = (uint32) hexValue;
  813. else
  814. break;
  815. }
  816. if (numChars <= 3)
  817. return Colour ((uint8) (hex [0] * 0x11),
  818. (uint8) (hex [1] * 0x11),
  819. (uint8) (hex [2] * 0x11));
  820. else
  821. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  822. (uint8) ((hex [2] << 4) + hex [3]),
  823. (uint8) ((hex [4] << 4) + hex [5]));
  824. }
  825. else if (s [index] == 'r'
  826. && s [index + 1] == 'g'
  827. && s [index + 2] == 'b')
  828. {
  829. const int openBracket = s.indexOfChar (index, '(');
  830. const int closeBracket = s.indexOfChar (openBracket, ')');
  831. if (openBracket >= 3 && closeBracket > openBracket)
  832. {
  833. index = closeBracket;
  834. StringArray tokens;
  835. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  836. tokens.trim();
  837. tokens.removeEmptyStrings();
  838. if (tokens[0].containsChar ('%'))
  839. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  840. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  841. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  842. else
  843. return Colour ((uint8) tokens[0].getIntValue(),
  844. (uint8) tokens[1].getIntValue(),
  845. (uint8) tokens[2].getIntValue());
  846. }
  847. }
  848. return Colours::findColourForName (s, defaultColour);
  849. }
  850. static const AffineTransform parseTransform (String t)
  851. {
  852. AffineTransform result;
  853. while (t.isNotEmpty())
  854. {
  855. StringArray tokens;
  856. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  857. .upToFirstOccurrenceOf (")", false, false),
  858. ", ", String::empty);
  859. tokens.removeEmptyStrings (true);
  860. float numbers [6];
  861. for (int i = 0; i < 6; ++i)
  862. numbers[i] = tokens[i].getFloatValue();
  863. AffineTransform trans;
  864. if (t.startsWithIgnoreCase ("matrix"))
  865. {
  866. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  867. numbers[1], numbers[3], numbers[5]);
  868. }
  869. else if (t.startsWithIgnoreCase ("translate"))
  870. {
  871. jassert (tokens.size() == 2);
  872. trans = AffineTransform::translation (numbers[0], numbers[1]);
  873. }
  874. else if (t.startsWithIgnoreCase ("scale"))
  875. {
  876. if (tokens.size() == 1)
  877. trans = AffineTransform::scale (numbers[0], numbers[0]);
  878. else
  879. trans = AffineTransform::scale (numbers[0], numbers[1]);
  880. }
  881. else if (t.startsWithIgnoreCase ("rotate"))
  882. {
  883. if (tokens.size() != 3)
  884. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  885. else
  886. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  887. numbers[1], numbers[2]);
  888. }
  889. else if (t.startsWithIgnoreCase ("skewX"))
  890. {
  891. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  892. 0.0f, 1.0f, 0.0f);
  893. }
  894. else if (t.startsWithIgnoreCase ("skewY"))
  895. {
  896. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  897. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  898. }
  899. result = trans.followedBy (result);
  900. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  901. }
  902. return result;
  903. }
  904. static void endpointToCentreParameters (const double x1, const double y1,
  905. const double x2, const double y2,
  906. const double angle,
  907. const bool largeArc, const bool sweep,
  908. double& rx, double& ry,
  909. double& centreX, double& centreY,
  910. double& startAngle, double& deltaAngle)
  911. {
  912. const double midX = (x1 - x2) * 0.5;
  913. const double midY = (y1 - y2) * 0.5;
  914. const double cosAngle = cos (angle);
  915. const double sinAngle = sin (angle);
  916. const double xp = cosAngle * midX + sinAngle * midY;
  917. const double yp = cosAngle * midY - sinAngle * midX;
  918. const double xp2 = xp * xp;
  919. const double yp2 = yp * yp;
  920. double rx2 = rx * rx;
  921. double ry2 = ry * ry;
  922. const double s = (xp2 / rx2) + (yp2 / ry2);
  923. double c;
  924. if (s <= 1.0)
  925. {
  926. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  927. / (( rx2 * yp2) + (ry2 * xp2))));
  928. if (largeArc == sweep)
  929. c = -c;
  930. }
  931. else
  932. {
  933. const double s2 = std::sqrt (s);
  934. rx *= s2;
  935. ry *= s2;
  936. rx2 = rx * rx;
  937. ry2 = ry * ry;
  938. c = 0;
  939. }
  940. const double cpx = ((rx * yp) / ry) * c;
  941. const double cpy = ((-ry * xp) / rx) * c;
  942. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  943. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  944. const double ux = (xp - cpx) / rx;
  945. const double uy = (yp - cpy) / ry;
  946. const double vx = (-xp - cpx) / rx;
  947. const double vy = (-yp - cpy) / ry;
  948. const double length = juce_hypot (ux, uy);
  949. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  950. if (uy < 0)
  951. startAngle = -startAngle;
  952. startAngle += double_Pi * 0.5;
  953. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  954. / (length * juce_hypot (vx, vy))));
  955. if ((ux * vy) - (uy * vx) < 0)
  956. deltaAngle = -deltaAngle;
  957. if (sweep)
  958. {
  959. if (deltaAngle < 0)
  960. deltaAngle += double_Pi * 2.0;
  961. }
  962. else
  963. {
  964. if (deltaAngle > 0)
  965. deltaAngle -= double_Pi * 2.0;
  966. }
  967. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  968. }
  969. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  970. {
  971. forEachXmlChildElement (*parent, e)
  972. {
  973. if (e->compareAttribute ("id", id))
  974. return e;
  975. const XmlElement* const found = findElementForId (e, id);
  976. if (found != nullptr)
  977. return found;
  978. }
  979. return nullptr;
  980. }
  981. SVGState& operator= (const SVGState&);
  982. };
  983. //==============================================================================
  984. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  985. {
  986. SVGState state (&svgDocument);
  987. return state.parseSVGElement (svgDocument);
  988. }