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.

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