The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1279 lines
45KB

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