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.

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