juce_SVGParser.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. class SVGState
  18. {
  19. public:
  20. //==============================================================================
  21. explicit SVGState (const XmlElement* const topLevel)
  22. : topLevelXml (topLevel, nullptr),
  23. elementX (0), elementY (0),
  24. width (512), height (512),
  25. viewBoxW (0), viewBoxH (0)
  26. {
  27. }
  28. struct XmlPath
  29. {
  30. XmlPath (const XmlElement* e, const XmlPath* p) noexcept : xml (e), parent (p) {}
  31. const XmlElement& operator*() const noexcept { jassert (xml != nullptr); return *xml; }
  32. const XmlElement* operator->() const noexcept { return xml; }
  33. XmlPath getChild (const XmlElement* e) const noexcept { return XmlPath (e, this); }
  34. template <typename OperationType>
  35. bool applyOperationToChildWithID (const String& id, OperationType& op) const
  36. {
  37. forEachXmlChildElement (*xml, e)
  38. {
  39. XmlPath child (e, this);
  40. if (e->compareAttribute ("id", id))
  41. {
  42. op (child);
  43. return true;
  44. }
  45. if (child.applyOperationToChildWithID (id, op))
  46. return true;
  47. }
  48. return false;
  49. }
  50. const XmlElement* xml;
  51. const XmlPath* parent;
  52. };
  53. //==============================================================================
  54. Drawable* parseSVGElement (const XmlPath& xml)
  55. {
  56. if (! xml->hasTagNameIgnoringNamespace ("svg"))
  57. return nullptr;
  58. DrawableComposite* const drawable = new DrawableComposite();
  59. setCommonAttributes (*drawable, xml);
  60. SVGState newState (*this);
  61. if (xml->hasAttribute ("transform"))
  62. newState.addTransform (xml);
  63. newState.elementX = getCoordLength (xml->getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  64. newState.elementY = getCoordLength (xml->getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  65. newState.width = getCoordLength (xml->getStringAttribute ("width", String (newState.width)), viewBoxW);
  66. newState.height = getCoordLength (xml->getStringAttribute ("height", String (newState.height)), viewBoxH);
  67. if (newState.width <= 0) newState.width = 100;
  68. if (newState.height <= 0) newState.height = 100;
  69. Point<float> viewboxXY;
  70. if (xml->hasAttribute ("viewBox"))
  71. {
  72. const String viewBoxAtt (xml->getStringAttribute ("viewBox"));
  73. String::CharPointerType viewParams (viewBoxAtt.getCharPointer());
  74. Point<float> vwh;
  75. if (parseCoords (viewParams, viewboxXY, true)
  76. && parseCoords (viewParams, vwh, true)
  77. && vwh.x > 0
  78. && vwh.y > 0)
  79. {
  80. newState.viewBoxW = vwh.x;
  81. newState.viewBoxH = vwh.y;
  82. const int placementFlags = parsePlacementFlags (xml->getStringAttribute ("preserveAspectRatio").trim());
  83. if (placementFlags != 0)
  84. newState.transform = RectanglePlacement (placementFlags)
  85. .getTransformToFit (Rectangle<float> (viewboxXY.x, viewboxXY.y, vwh.x, vwh.y),
  86. Rectangle<float> (newState.width, newState.height))
  87. .followedBy (newState.transform);
  88. }
  89. }
  90. else
  91. {
  92. if (viewBoxW == 0) newState.viewBoxW = newState.width;
  93. if (viewBoxH == 0) newState.viewBoxH = newState.height;
  94. }
  95. newState.parseSubElements (xml, *drawable);
  96. drawable->setContentArea (RelativeRectangle (RelativeCoordinate (viewboxXY.x),
  97. RelativeCoordinate (viewboxXY.x + newState.viewBoxW),
  98. RelativeCoordinate (viewboxXY.y),
  99. RelativeCoordinate (viewboxXY.y + newState.viewBoxH)));
  100. drawable->resetBoundingBoxToContentArea();
  101. return drawable;
  102. }
  103. //==============================================================================
  104. void parsePathString (Path& path, const String& pathString) const
  105. {
  106. String::CharPointerType d (pathString.getCharPointer().findEndOfWhitespace());
  107. Point<float> subpathStart, last, last2, p1, p2, p3;
  108. juce_wchar lastCommandChar = 0;
  109. bool isRelative = true;
  110. bool carryOn = true;
  111. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  112. while (! d.isEmpty())
  113. {
  114. if (validCommandChars.indexOf (*d) >= 0)
  115. {
  116. lastCommandChar = d.getAndAdvance();
  117. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  118. }
  119. switch (lastCommandChar)
  120. {
  121. case 'M':
  122. case 'm':
  123. case 'L':
  124. case 'l':
  125. if (parseCoordsOrSkip (d, p1, false))
  126. {
  127. if (isRelative)
  128. p1 += last;
  129. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  130. {
  131. subpathStart = p1;
  132. path.startNewSubPath (p1);
  133. lastCommandChar = 'l';
  134. }
  135. else
  136. path.lineTo (p1);
  137. last2 = last;
  138. last = p1;
  139. }
  140. break;
  141. case 'H':
  142. case 'h':
  143. if (parseCoord (d, p1.x, false, true))
  144. {
  145. if (isRelative)
  146. p1.x += last.x;
  147. path.lineTo (p1.x, last.y);
  148. last2.x = last.x;
  149. last.x = p1.x;
  150. }
  151. else
  152. {
  153. ++d;
  154. }
  155. break;
  156. case 'V':
  157. case 'v':
  158. if (parseCoord (d, p1.y, false, false))
  159. {
  160. if (isRelative)
  161. p1.y += last.y;
  162. path.lineTo (last.x, p1.y);
  163. last2.y = last.y;
  164. last.y = p1.y;
  165. }
  166. else
  167. {
  168. ++d;
  169. }
  170. break;
  171. case 'C':
  172. case 'c':
  173. if (parseCoordsOrSkip (d, p1, false)
  174. && parseCoordsOrSkip (d, p2, false)
  175. && parseCoordsOrSkip (d, p3, false))
  176. {
  177. if (isRelative)
  178. {
  179. p1 += last;
  180. p2 += last;
  181. p3 += last;
  182. }
  183. path.cubicTo (p1, p2, p3);
  184. last2 = p2;
  185. last = p3;
  186. }
  187. break;
  188. case 'S':
  189. case 's':
  190. if (parseCoordsOrSkip (d, p1, false)
  191. && parseCoordsOrSkip (d, p3, false))
  192. {
  193. if (isRelative)
  194. {
  195. p1 += last;
  196. p3 += last;
  197. }
  198. p2 = last + (last - last2);
  199. path.cubicTo (p2, p1, p3);
  200. last2 = p1;
  201. last = p3;
  202. }
  203. break;
  204. case 'Q':
  205. case 'q':
  206. if (parseCoordsOrSkip (d, p1, false)
  207. && parseCoordsOrSkip (d, p2, false))
  208. {
  209. if (isRelative)
  210. {
  211. p1 += last;
  212. p2 += last;
  213. }
  214. path.quadraticTo (p1, p2);
  215. last2 = p1;
  216. last = p2;
  217. }
  218. break;
  219. case 'T':
  220. case 't':
  221. if (parseCoordsOrSkip (d, p1, false))
  222. {
  223. if (isRelative)
  224. p1 += last;
  225. p2 = last + (last - last2);
  226. path.quadraticTo (p2, p1);
  227. last2 = p2;
  228. last = p1;
  229. }
  230. break;
  231. case 'A':
  232. case 'a':
  233. if (parseCoordsOrSkip (d, p1, false))
  234. {
  235. String num;
  236. if (parseNextNumber (d, num, false))
  237. {
  238. const float angle = degreesToRadians (num.getFloatValue());
  239. if (parseNextNumber (d, num, false))
  240. {
  241. const bool largeArc = num.getIntValue() != 0;
  242. if (parseNextNumber (d, num, false))
  243. {
  244. const bool sweep = num.getIntValue() != 0;
  245. if (parseCoordsOrSkip (d, p2, false))
  246. {
  247. if (isRelative)
  248. p2 += last;
  249. if (last != p2)
  250. {
  251. double centreX, centreY, startAngle, deltaAngle;
  252. double rx = p1.x, ry = p1.y;
  253. endpointToCentreParameters (last.x, last.y, p2.x, p2.y,
  254. angle, largeArc, sweep,
  255. rx, ry, centreX, centreY,
  256. startAngle, deltaAngle);
  257. path.addCentredArc ((float) centreX, (float) centreY,
  258. (float) rx, (float) ry,
  259. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  260. false);
  261. path.lineTo (p2);
  262. }
  263. last2 = last;
  264. last = p2;
  265. }
  266. }
  267. }
  268. }
  269. }
  270. break;
  271. case 'Z':
  272. case 'z':
  273. path.closeSubPath();
  274. last = last2 = subpathStart;
  275. d = d.findEndOfWhitespace();
  276. lastCommandChar = 'M';
  277. break;
  278. default:
  279. carryOn = false;
  280. break;
  281. }
  282. if (! carryOn)
  283. break;
  284. }
  285. // paths that finish back at their start position often seem to be
  286. // left without a 'z', so need to be closed explicitly..
  287. if (path.getCurrentPosition() == subpathStart)
  288. path.closeSubPath();
  289. }
  290. private:
  291. //==============================================================================
  292. const XmlPath topLevelXml;
  293. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  294. AffineTransform transform;
  295. String cssStyleText;
  296. static void setCommonAttributes (Drawable& d, const XmlPath& xml)
  297. {
  298. String compID (xml->getStringAttribute ("id"));
  299. d.setName (compID);
  300. d.setComponentID (compID);
  301. if (xml->getStringAttribute ("display") == "none")
  302. d.setVisible (false);
  303. }
  304. //==============================================================================
  305. void parseSubElements (const XmlPath& xml, DrawableComposite& parentDrawable)
  306. {
  307. forEachXmlChildElement (*xml, e)
  308. parentDrawable.addAndMakeVisible (parseSubElement (xml.getChild (e)));
  309. }
  310. Drawable* parseSubElement (const XmlPath& xml)
  311. {
  312. {
  313. Path path;
  314. if (parsePathElement (xml, path))
  315. return parseShape (xml, path);
  316. }
  317. const String tag (xml->getTagNameWithoutNamespace());
  318. if (tag == "g") return parseGroupElement (xml);
  319. if (tag == "svg") return parseSVGElement (xml);
  320. if (tag == "text") return parseText (xml, true);
  321. if (tag == "switch") return parseSwitch (xml);
  322. if (tag == "a") return parseLinkElement (xml);
  323. if (tag == "style") parseCSSStyle (xml);
  324. return nullptr;
  325. }
  326. bool parsePathElement (const XmlPath& xml, Path& path) const
  327. {
  328. const String tag (xml->getTagNameWithoutNamespace());
  329. if (tag == "path") { parsePath (xml, path); return true; }
  330. if (tag == "rect") { parseRect (xml, path); return true; }
  331. if (tag == "circle") { parseCircle (xml, path); return true; }
  332. if (tag == "ellipse") { parseEllipse (xml, path); return true; }
  333. if (tag == "line") { parseLine (xml, path); return true; }
  334. if (tag == "polyline") { parsePolygon (xml, true, path); return true; }
  335. if (tag == "polygon") { parsePolygon (xml, false, path); return true; }
  336. if (tag == "use") { parseUse (xml, path); return true; }
  337. return false;
  338. }
  339. DrawableComposite* parseSwitch (const XmlPath& xml)
  340. {
  341. if (const XmlElement* const group = xml->getChildByName ("g"))
  342. return parseGroupElement (xml.getChild (group));
  343. return nullptr;
  344. }
  345. DrawableComposite* parseGroupElement (const XmlPath& xml)
  346. {
  347. DrawableComposite* const drawable = new DrawableComposite();
  348. setCommonAttributes (*drawable, xml);
  349. if (xml->hasAttribute ("transform"))
  350. {
  351. SVGState newState (*this);
  352. newState.addTransform (xml);
  353. newState.parseSubElements (xml, *drawable);
  354. }
  355. else
  356. {
  357. parseSubElements (xml, *drawable);
  358. }
  359. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  360. return drawable;
  361. }
  362. DrawableComposite* parseLinkElement (const XmlPath& xml)
  363. {
  364. return parseGroupElement (xml); // TODO: support for making this clickable
  365. }
  366. //==============================================================================
  367. void parsePath (const XmlPath& xml, Path& path) const
  368. {
  369. parsePathString (path, xml->getStringAttribute ("d"));
  370. if (getStyleAttribute (xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  371. path.setUsingNonZeroWinding (false);
  372. }
  373. void parseRect (const XmlPath& xml, Path& rect) const
  374. {
  375. const bool hasRX = xml->hasAttribute ("rx");
  376. const bool hasRY = xml->hasAttribute ("ry");
  377. if (hasRX || hasRY)
  378. {
  379. float rx = getCoordLength (xml, "rx", viewBoxW);
  380. float ry = getCoordLength (xml, "ry", viewBoxH);
  381. if (! hasRX)
  382. rx = ry;
  383. else if (! hasRY)
  384. ry = rx;
  385. rect.addRoundedRectangle (getCoordLength (xml, "x", viewBoxW),
  386. getCoordLength (xml, "y", viewBoxH),
  387. getCoordLength (xml, "width", viewBoxW),
  388. getCoordLength (xml, "height", viewBoxH),
  389. rx, ry);
  390. }
  391. else
  392. {
  393. rect.addRectangle (getCoordLength (xml, "x", viewBoxW),
  394. getCoordLength (xml, "y", viewBoxH),
  395. getCoordLength (xml, "width", viewBoxW),
  396. getCoordLength (xml, "height", viewBoxH));
  397. }
  398. }
  399. void parseCircle (const XmlPath& xml, Path& circle) const
  400. {
  401. const float cx = getCoordLength (xml, "cx", viewBoxW);
  402. const float cy = getCoordLength (xml, "cy", viewBoxH);
  403. const float radius = getCoordLength (xml, "r", viewBoxW);
  404. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  405. }
  406. void parseEllipse (const XmlPath& xml, Path& ellipse) const
  407. {
  408. const float cx = getCoordLength (xml, "cx", viewBoxW);
  409. const float cy = getCoordLength (xml, "cy", viewBoxH);
  410. const float radiusX = getCoordLength (xml, "rx", viewBoxW);
  411. const float radiusY = getCoordLength (xml, "ry", viewBoxH);
  412. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  413. }
  414. void parseLine (const XmlPath& xml, Path& line) const
  415. {
  416. const float x1 = getCoordLength (xml, "x1", viewBoxW);
  417. const float y1 = getCoordLength (xml, "y1", viewBoxH);
  418. const float x2 = getCoordLength (xml, "x2", viewBoxW);
  419. const float y2 = getCoordLength (xml, "y2", viewBoxH);
  420. line.startNewSubPath (x1, y1);
  421. line.lineTo (x2, y2);
  422. }
  423. void parsePolygon (const XmlPath& xml, const bool isPolyline, Path& path) const
  424. {
  425. const String pointsAtt (xml->getStringAttribute ("points"));
  426. String::CharPointerType points (pointsAtt.getCharPointer());
  427. Point<float> p;
  428. if (parseCoords (points, p, true))
  429. {
  430. Point<float> first (p), last;
  431. path.startNewSubPath (first);
  432. while (parseCoords (points, p, true))
  433. {
  434. last = p;
  435. path.lineTo (p);
  436. }
  437. if ((! isPolyline) || first == last)
  438. path.closeSubPath();
  439. }
  440. }
  441. void parseUse (const XmlPath& xml, Path& path) const
  442. {
  443. const String link (xml->getStringAttribute ("xlink:href"));
  444. if (link.startsWithChar ('#'))
  445. {
  446. const String linkedID = link.substring (1);
  447. struct UsePathOp
  448. {
  449. const SVGState* state;
  450. Path* targetPath;
  451. void operator() (const XmlPath& xmlPath)
  452. {
  453. state->parsePathElement (xmlPath, *targetPath);
  454. }
  455. };
  456. UsePathOp op = { this, &path };
  457. topLevelXml.applyOperationToChildWithID (linkedID, op);
  458. }
  459. }
  460. static String parseURL (const String& str)
  461. {
  462. if (str.startsWithIgnoreCase ("url"))
  463. return str.fromFirstOccurrenceOf ("#", false, false)
  464. .upToLastOccurrenceOf (")", false, false).trim();
  465. return String();
  466. }
  467. //==============================================================================
  468. Drawable* parseShape (const XmlPath& xml, Path& path,
  469. const bool shouldParseTransform = true) const
  470. {
  471. if (shouldParseTransform && xml->hasAttribute ("transform"))
  472. {
  473. SVGState newState (*this);
  474. newState.addTransform (xml);
  475. return newState.parseShape (xml, path, false);
  476. }
  477. DrawablePath* dp = new DrawablePath();
  478. setCommonAttributes (*dp, xml);
  479. dp->setFill (Colours::transparentBlack);
  480. path.applyTransform (transform);
  481. dp->setPath (path);
  482. dp->setFill (getPathFillType (path,
  483. getStyleAttribute (xml, "fill"),
  484. getStyleAttribute (xml, "fill-opacity"),
  485. getStyleAttribute (xml, "opacity"),
  486. pathContainsClosedSubPath (path) ? Colours::black
  487. : Colours::transparentBlack));
  488. const String strokeType (getStyleAttribute (xml, "stroke"));
  489. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  490. {
  491. dp->setStrokeFill (getPathFillType (path, strokeType,
  492. getStyleAttribute (xml, "stroke-opacity"),
  493. getStyleAttribute (xml, "opacity"),
  494. Colours::transparentBlack));
  495. dp->setStrokeType (getStrokeFor (xml));
  496. }
  497. const String strokeDashArray (getStyleAttribute (xml, "stroke-dasharray"));
  498. if (strokeDashArray.isNotEmpty())
  499. parseDashArray (strokeDashArray, *dp);
  500. parseClipPath (xml, *dp);
  501. return dp;
  502. }
  503. static bool pathContainsClosedSubPath (const Path& path) noexcept
  504. {
  505. for (Path::Iterator iter (path); iter.next();)
  506. if (iter.elementType == Path::Iterator::closePath)
  507. return true;
  508. return false;
  509. }
  510. void parseDashArray (const String& dashList, DrawablePath& dp) const
  511. {
  512. if (dashList.equalsIgnoreCase ("null") || dashList.equalsIgnoreCase ("none"))
  513. return;
  514. Array<float> dashLengths;
  515. for (String::CharPointerType t = dashList.getCharPointer();;)
  516. {
  517. float value;
  518. if (! parseCoord (t, value, true, true))
  519. break;
  520. dashLengths.add (value);
  521. t = t.findEndOfWhitespace();
  522. if (*t == ',')
  523. ++t;
  524. }
  525. if (dashLengths.size() > 0)
  526. {
  527. float* const dashes = dashLengths.getRawDataPointer();
  528. for (int i = 0; i < dashLengths.size(); ++i)
  529. {
  530. if (dashes[i] <= 0) // SVG uses zero-length dashes to mean a dotted line
  531. {
  532. if (dashLengths.size() == 1)
  533. return;
  534. const float nonZeroLength = 0.001f;
  535. dashes[i] = nonZeroLength;
  536. const int pairedIndex = i ^ 1;
  537. if (isPositiveAndBelow (pairedIndex, dashLengths.size())
  538. && dashes[pairedIndex] > nonZeroLength)
  539. dashes[pairedIndex] -= nonZeroLength;
  540. }
  541. }
  542. dp.setDashLengths (dashLengths);
  543. }
  544. }
  545. void parseClipPath (const XmlPath& xml, Drawable& d) const
  546. {
  547. const String clipPath (getStyleAttribute (xml, "clip-path"));
  548. if (clipPath.isNotEmpty())
  549. {
  550. String urlID = parseURL (clipPath);
  551. if (urlID.isNotEmpty())
  552. {
  553. struct GetClipPathOp
  554. {
  555. const SVGState* state;
  556. Drawable* target;
  557. void operator() (const XmlPath& xmlPath)
  558. {
  559. state->applyClipPath (*target, xmlPath);
  560. }
  561. };
  562. GetClipPathOp op = { this, &d };
  563. topLevelXml.applyOperationToChildWithID (urlID, op);
  564. }
  565. }
  566. }
  567. void applyClipPath (Drawable& target, const XmlPath& xmlPath) const
  568. {
  569. if (xmlPath->hasTagNameIgnoringNamespace ("clipPath"))
  570. {
  571. // TODO: implement clipping..
  572. ignoreUnused (target);
  573. }
  574. }
  575. void addGradientStopsIn (ColourGradient& cg, const XmlPath& fillXml) const
  576. {
  577. if (fillXml.xml != nullptr)
  578. {
  579. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  580. {
  581. int index = 0;
  582. Colour col (parseColour (getStyleAttribute (fillXml.getChild (e), "stop-color"), index, Colours::black));
  583. const String opacity (getStyleAttribute (fillXml.getChild (e), "stop-opacity", "1"));
  584. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  585. double offset = e->getDoubleAttribute ("offset");
  586. if (e->getStringAttribute ("offset").containsChar ('%'))
  587. offset *= 0.01;
  588. cg.addColour (jlimit (0.0, 1.0, offset), col);
  589. }
  590. }
  591. }
  592. FillType getGradientFillType (const XmlPath& fillXml,
  593. const Path& path,
  594. const float opacity) const
  595. {
  596. ColourGradient gradient;
  597. {
  598. const String id (fillXml->getStringAttribute ("xlink:href"));
  599. if (id.startsWithChar ('#'))
  600. {
  601. struct SetGradientStopsOp
  602. {
  603. const SVGState* state;
  604. ColourGradient* gradient;
  605. void operator() (const XmlPath& xml)
  606. {
  607. state->addGradientStopsIn (*gradient, xml);
  608. }
  609. };
  610. SetGradientStopsOp op = { this, &gradient, };
  611. topLevelXml.applyOperationToChildWithID (id.substring (1), op);
  612. }
  613. }
  614. addGradientStopsIn (gradient, fillXml);
  615. if (int numColours = gradient.getNumColours())
  616. {
  617. if (gradient.getColourPosition (0) > 0)
  618. gradient.addColour (0.0, gradient.getColour (0));
  619. if (gradient.getColourPosition (numColours - 1) < 1.0)
  620. gradient.addColour (1.0, gradient.getColour (numColours - 1));
  621. }
  622. else
  623. {
  624. gradient.addColour (0.0, Colours::black);
  625. gradient.addColour (1.0, Colours::black);
  626. }
  627. if (opacity < 1.0f)
  628. gradient.multiplyOpacity (opacity);
  629. jassert (gradient.getNumColours() > 0);
  630. gradient.isRadial = fillXml->hasTagNameIgnoringNamespace ("radialGradient");
  631. float gradientWidth = viewBoxW;
  632. float gradientHeight = viewBoxH;
  633. float dx = 0.0f;
  634. float dy = 0.0f;
  635. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  636. if (! userSpace)
  637. {
  638. const Rectangle<float> bounds (path.getBounds());
  639. dx = bounds.getX();
  640. dy = bounds.getY();
  641. gradientWidth = bounds.getWidth();
  642. gradientHeight = bounds.getHeight();
  643. }
  644. if (gradient.isRadial)
  645. {
  646. if (userSpace)
  647. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  648. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  649. else
  650. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  651. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  652. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  653. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  654. //xxx (the fx, fy focal point isn't handled properly here..)
  655. }
  656. else
  657. {
  658. if (userSpace)
  659. {
  660. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  661. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  662. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  663. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  664. }
  665. else
  666. {
  667. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  668. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  669. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  670. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  671. }
  672. if (gradient.point1 == gradient.point2)
  673. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  674. }
  675. FillType type (gradient);
  676. const AffineTransform gradientTransform (parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  677. .followedBy (transform));
  678. if (gradient.isRadial)
  679. {
  680. type.transform = gradientTransform;
  681. }
  682. else
  683. {
  684. // Transform the perpendicular vector into the new coordinate space for the gradient.
  685. // This vector is now the slope of the linear gradient as it should appear in the new coord space
  686. const Point<float> perpendicular (Point<float> (gradient.point2.y - gradient.point1.y,
  687. gradient.point1.x - gradient.point2.x)
  688. .transformedBy (gradientTransform.withAbsoluteTranslation (0, 0)));
  689. const Point<float> newGradPoint1 (gradient.point1.transformedBy (gradientTransform));
  690. const Point<float> newGradPoint2 (gradient.point2.transformedBy (gradientTransform));
  691. // Project the transformed gradient vector onto the transformed slope of the linear
  692. // gradient as it should appear in the new coordinate space
  693. const float scale = perpendicular.getDotProduct (newGradPoint2 - newGradPoint1)
  694. / perpendicular.getDotProduct (perpendicular);
  695. type.gradient->point1 = newGradPoint1;
  696. type.gradient->point2 = newGradPoint2 - perpendicular * scale;
  697. }
  698. return type;
  699. }
  700. FillType getPathFillType (const Path& path,
  701. const String& fill,
  702. const String& fillOpacity,
  703. const String& overallOpacity,
  704. const Colour defaultColour) const
  705. {
  706. float opacity = 1.0f;
  707. if (overallOpacity.isNotEmpty())
  708. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  709. if (fillOpacity.isNotEmpty())
  710. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  711. String urlID = parseURL (fill);
  712. if (urlID.isNotEmpty())
  713. {
  714. struct GetFillTypeOp
  715. {
  716. const SVGState* state;
  717. const Path* path;
  718. float opacity;
  719. FillType fillType;
  720. void operator() (const XmlPath& xml)
  721. {
  722. if (xml->hasTagNameIgnoringNamespace ("linearGradient")
  723. || xml->hasTagNameIgnoringNamespace ("radialGradient"))
  724. fillType = state->getGradientFillType (xml, *path, opacity);
  725. }
  726. };
  727. GetFillTypeOp op = { this, &path, opacity, FillType() };
  728. if (topLevelXml.applyOperationToChildWithID (urlID, op))
  729. return op.fillType;
  730. }
  731. if (fill.equalsIgnoreCase ("none"))
  732. return Colours::transparentBlack;
  733. int i = 0;
  734. return parseColour (fill, i, defaultColour).withMultipliedAlpha (opacity);
  735. }
  736. static PathStrokeType::JointStyle getJointStyle (const String& join) noexcept
  737. {
  738. if (join.equalsIgnoreCase ("round")) return PathStrokeType::curved;
  739. if (join.equalsIgnoreCase ("bevel")) return PathStrokeType::beveled;
  740. return PathStrokeType::mitered;
  741. }
  742. static PathStrokeType::EndCapStyle getEndCapStyle (const String& cap) noexcept
  743. {
  744. if (cap.equalsIgnoreCase ("round")) return PathStrokeType::rounded;
  745. if (cap.equalsIgnoreCase ("square")) return PathStrokeType::square;
  746. return PathStrokeType::butt;
  747. }
  748. float getStrokeWidth (const String& strokeWidth) const noexcept
  749. {
  750. return transform.getScaleFactor() * getCoordLength (strokeWidth, viewBoxW);
  751. }
  752. PathStrokeType getStrokeFor (const XmlPath& xml) const
  753. {
  754. return PathStrokeType (getStrokeWidth (getStyleAttribute (xml, "stroke-width", "1")),
  755. getJointStyle (getStyleAttribute (xml, "stroke-linejoin")),
  756. getEndCapStyle (getStyleAttribute (xml, "stroke-linecap")));
  757. }
  758. //==============================================================================
  759. Drawable* parseText (const XmlPath& xml, bool shouldParseTransform)
  760. {
  761. if (shouldParseTransform && xml->hasAttribute ("transform"))
  762. {
  763. SVGState newState (*this);
  764. newState.addTransform (xml);
  765. return newState.parseText (xml, false);
  766. }
  767. Array<float> xCoords, yCoords, dxCoords, dyCoords;
  768. getCoordList (xCoords, getInheritedAttribute (xml, "x"), true, true);
  769. getCoordList (yCoords, getInheritedAttribute (xml, "y"), true, false);
  770. getCoordList (dxCoords, getInheritedAttribute (xml, "dx"), true, true);
  771. getCoordList (dyCoords, getInheritedAttribute (xml, "dy"), true, false);
  772. const Font font (getFont (xml));
  773. const String anchorStr = getStyleAttribute(xml, "text-anchor");
  774. DrawableComposite* dc = new DrawableComposite();
  775. setCommonAttributes (*dc, xml);
  776. forEachXmlChildElement (*xml, e)
  777. {
  778. if (e->isTextElement())
  779. {
  780. const String text (e->getText().trim());
  781. DrawableText* dt = new DrawableText();
  782. dc->addAndMakeVisible (dt);
  783. dt->setText (text);
  784. dt->setFont (font, true);
  785. dt->setTransform (transform);
  786. int i = 0;
  787. dt->setColour (parseColour (getStyleAttribute (xml, "fill"), i, Colours::black)
  788. .withMultipliedAlpha (getStyleAttribute (xml, "fill-opacity", "1").getFloatValue()));
  789. Rectangle<float> bounds (xCoords[0], yCoords[0] - font.getAscent(),
  790. font.getStringWidthFloat (text), font.getHeight());
  791. if (anchorStr == "middle") bounds.setX (bounds.getX() - bounds.getWidth() / 2.0f);
  792. else if (anchorStr == "end") bounds.setX (bounds.getX() - bounds.getWidth());
  793. dt->setBoundingBox (bounds);
  794. }
  795. else if (e->hasTagNameIgnoringNamespace ("tspan"))
  796. {
  797. dc->addAndMakeVisible (parseText (xml.getChild (e), true));
  798. }
  799. }
  800. return dc;
  801. }
  802. Font getFont (const XmlPath& xml) const
  803. {
  804. const float fontSize = getCoordLength (getStyleAttribute (xml, "font-size"), 1.0f);
  805. int style = getStyleAttribute (xml, "font-style").containsIgnoreCase ("italic") ? Font::italic : Font::plain;
  806. if (getStyleAttribute (xml, "font-weight").containsIgnoreCase ("bold"))
  807. style |= Font::bold;
  808. const String family (getStyleAttribute (xml, "font-family"));
  809. return family.isEmpty() ? Font (fontSize, style)
  810. : Font (family, fontSize, style);
  811. }
  812. //==============================================================================
  813. void addTransform (const XmlPath& xml)
  814. {
  815. transform = parseTransform (xml->getStringAttribute ("transform"))
  816. .followedBy (transform);
  817. }
  818. //==============================================================================
  819. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  820. {
  821. String number;
  822. if (! parseNextNumber (s, number, allowUnits))
  823. {
  824. value = 0;
  825. return false;
  826. }
  827. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  828. return true;
  829. }
  830. bool parseCoords (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  831. {
  832. return parseCoord (s, p.x, allowUnits, true)
  833. && parseCoord (s, p.y, allowUnits, false);
  834. }
  835. bool parseCoordsOrSkip (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  836. {
  837. if (parseCoords (s, p, allowUnits))
  838. return true;
  839. if (! s.isEmpty()) ++s;
  840. return false;
  841. }
  842. float getCoordLength (const String& s, const float sizeForProportions) const noexcept
  843. {
  844. float n = s.getFloatValue();
  845. const int len = s.length();
  846. if (len > 2)
  847. {
  848. const float dpi = 96.0f;
  849. const juce_wchar n1 = s [len - 2];
  850. const juce_wchar n2 = s [len - 1];
  851. if (n1 == 'i' && n2 == 'n') n *= dpi;
  852. else if (n1 == 'm' && n2 == 'm') n *= dpi / 25.4f;
  853. else if (n1 == 'c' && n2 == 'm') n *= dpi / 2.54f;
  854. else if (n1 == 'p' && n2 == 'c') n *= 15.0f;
  855. else if (n2 == '%') n *= 0.01f * sizeForProportions;
  856. }
  857. return n;
  858. }
  859. float getCoordLength (const XmlPath& xml, const char* attName, const float sizeForProportions) const noexcept
  860. {
  861. return getCoordLength (xml->getStringAttribute (attName), sizeForProportions);
  862. }
  863. void getCoordList (Array<float>& coords, const String& list, bool allowUnits, const bool isX) const
  864. {
  865. String::CharPointerType text (list.getCharPointer());
  866. float value;
  867. while (parseCoord (text, value, allowUnits, isX))
  868. coords.add (value);
  869. }
  870. //==============================================================================
  871. void parseCSSStyle (const XmlPath& xml)
  872. {
  873. cssStyleText = xml->getAllSubText() + "\n" + cssStyleText;
  874. }
  875. static String::CharPointerType findStyleItem (String::CharPointerType source, String::CharPointerType name)
  876. {
  877. const int nameLength = (int) name.length();
  878. while (! source.isEmpty())
  879. {
  880. if (source.getAndAdvance() == '.'
  881. && CharacterFunctions::compareIgnoreCaseUpTo (source, name, nameLength) == 0)
  882. {
  883. String::CharPointerType endOfName ((source + nameLength).findEndOfWhitespace());
  884. if (*endOfName == '{')
  885. return endOfName;
  886. }
  887. }
  888. return source;
  889. }
  890. String getStyleAttribute (const XmlPath& xml, StringRef attributeName,
  891. const String& defaultValue = String()) const
  892. {
  893. if (xml->hasAttribute (attributeName))
  894. return xml->getStringAttribute (attributeName, defaultValue);
  895. const String styleAtt (xml->getStringAttribute ("style"));
  896. if (styleAtt.isNotEmpty())
  897. {
  898. const String value (getAttributeFromStyleList (styleAtt, attributeName, String()));
  899. if (value.isNotEmpty())
  900. return value;
  901. }
  902. else if (xml->hasAttribute ("class"))
  903. {
  904. String::CharPointerType openBrace = findStyleItem (cssStyleText.getCharPointer(),
  905. xml->getStringAttribute ("class").getCharPointer());
  906. if (! openBrace.isEmpty())
  907. {
  908. String::CharPointerType closeBrace = CharacterFunctions::find (openBrace, (juce_wchar) '}');
  909. if (closeBrace != openBrace)
  910. {
  911. const String value (getAttributeFromStyleList (String (openBrace + 1, closeBrace),
  912. attributeName, defaultValue));
  913. if (value.isNotEmpty())
  914. return value;
  915. }
  916. }
  917. }
  918. if (xml.parent != nullptr)
  919. return getStyleAttribute (*xml.parent, attributeName, defaultValue);
  920. return defaultValue;
  921. }
  922. String getInheritedAttribute (const XmlPath& xml, StringRef attributeName) const
  923. {
  924. if (xml->hasAttribute (attributeName))
  925. return xml->getStringAttribute (attributeName);
  926. if (xml.parent != nullptr)
  927. return getInheritedAttribute (*xml.parent, attributeName);
  928. return String();
  929. }
  930. static int parsePlacementFlags (const String& align) noexcept
  931. {
  932. if (align.isEmpty())
  933. return 0;
  934. if (align.containsIgnoreCase ("none"))
  935. return RectanglePlacement::stretchToFit;
  936. return (align.containsIgnoreCase ("slice") ? RectanglePlacement::fillDestination : 0)
  937. | (align.containsIgnoreCase ("xMin") ? RectanglePlacement::xLeft
  938. : (align.containsIgnoreCase ("xMax") ? RectanglePlacement::xRight
  939. : RectanglePlacement::xMid))
  940. | (align.containsIgnoreCase ("yMin") ? RectanglePlacement::yTop
  941. : (align.containsIgnoreCase ("yMax") ? RectanglePlacement::yBottom
  942. : RectanglePlacement::yMid));
  943. }
  944. //==============================================================================
  945. static bool isIdentifierChar (const juce_wchar c)
  946. {
  947. return CharacterFunctions::isLetter (c) || c == '-';
  948. }
  949. static String getAttributeFromStyleList (const String& list, StringRef attributeName, const String& defaultValue)
  950. {
  951. int i = 0;
  952. for (;;)
  953. {
  954. i = list.indexOf (i, attributeName);
  955. if (i < 0)
  956. break;
  957. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  958. && ! isIdentifierChar (list [i + attributeName.length()]))
  959. {
  960. i = list.indexOfChar (i, ':');
  961. if (i < 0)
  962. break;
  963. int end = list.indexOfChar (i, ';');
  964. if (end < 0)
  965. end = 0x7ffff;
  966. return list.substring (i + 1, end).trim();
  967. }
  968. ++i;
  969. }
  970. return defaultValue;
  971. }
  972. //==============================================================================
  973. static bool isStartOfNumber (juce_wchar c) noexcept
  974. {
  975. return CharacterFunctions::isDigit (c) || c == '-' || c == '+';
  976. }
  977. static bool parseNextNumber (String::CharPointerType& text, String& value, const bool allowUnits)
  978. {
  979. String::CharPointerType s (text);
  980. while (s.isWhitespace() || *s == ',')
  981. ++s;
  982. String::CharPointerType start (s);
  983. if (isStartOfNumber (*s))
  984. ++s;
  985. while (s.isDigit())
  986. ++s;
  987. if (*s == '.')
  988. {
  989. ++s;
  990. while (s.isDigit())
  991. ++s;
  992. }
  993. if ((*s == 'e' || *s == 'E') && isStartOfNumber (s[1]))
  994. {
  995. s += 2;
  996. while (s.isDigit())
  997. ++s;
  998. }
  999. if (allowUnits)
  1000. while (s.isLetter())
  1001. ++s;
  1002. if (s == start)
  1003. {
  1004. text = s;
  1005. return false;
  1006. }
  1007. value = String (start, s);
  1008. while (s.isWhitespace() || *s == ',')
  1009. ++s;
  1010. text = s;
  1011. return true;
  1012. }
  1013. //==============================================================================
  1014. static Colour parseColour (const String& s, int& index, const Colour defaultColour)
  1015. {
  1016. if (s [index] == '#')
  1017. {
  1018. uint32 hex[6] = { 0 };
  1019. int numChars = 0;
  1020. for (int i = 6; --i >= 0;)
  1021. {
  1022. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  1023. if (hexValue >= 0)
  1024. hex [numChars++] = (uint32) hexValue;
  1025. else
  1026. break;
  1027. }
  1028. if (numChars <= 3)
  1029. return Colour ((uint8) (hex [0] * 0x11),
  1030. (uint8) (hex [1] * 0x11),
  1031. (uint8) (hex [2] * 0x11));
  1032. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  1033. (uint8) ((hex [2] << 4) + hex [3]),
  1034. (uint8) ((hex [4] << 4) + hex [5]));
  1035. }
  1036. if (s [index] == 'r'
  1037. && s [index + 1] == 'g'
  1038. && s [index + 2] == 'b')
  1039. {
  1040. const int openBracket = s.indexOfChar (index, '(');
  1041. const int closeBracket = s.indexOfChar (openBracket, ')');
  1042. if (openBracket >= 3 && closeBracket > openBracket)
  1043. {
  1044. index = closeBracket;
  1045. StringArray tokens;
  1046. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  1047. tokens.trim();
  1048. tokens.removeEmptyStrings();
  1049. if (tokens[0].containsChar ('%'))
  1050. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  1051. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  1052. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  1053. else
  1054. return Colour ((uint8) tokens[0].getIntValue(),
  1055. (uint8) tokens[1].getIntValue(),
  1056. (uint8) tokens[2].getIntValue());
  1057. }
  1058. }
  1059. return Colours::findColourForName (s, defaultColour);
  1060. }
  1061. static AffineTransform parseTransform (String t)
  1062. {
  1063. AffineTransform result;
  1064. while (t.isNotEmpty())
  1065. {
  1066. StringArray tokens;
  1067. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  1068. .upToFirstOccurrenceOf (")", false, false),
  1069. ", ", "");
  1070. tokens.removeEmptyStrings (true);
  1071. float numbers[6];
  1072. for (int i = 0; i < numElementsInArray (numbers); ++i)
  1073. numbers[i] = tokens[i].getFloatValue();
  1074. AffineTransform trans;
  1075. if (t.startsWithIgnoreCase ("matrix"))
  1076. {
  1077. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  1078. numbers[1], numbers[3], numbers[5]);
  1079. }
  1080. else if (t.startsWithIgnoreCase ("translate"))
  1081. {
  1082. trans = AffineTransform::translation (numbers[0], numbers[1]);
  1083. }
  1084. else if (t.startsWithIgnoreCase ("scale"))
  1085. {
  1086. trans = AffineTransform::scale (numbers[0], numbers[tokens.size() > 1 ? 1 : 0]);
  1087. }
  1088. else if (t.startsWithIgnoreCase ("rotate"))
  1089. {
  1090. trans = AffineTransform::rotation (degreesToRadians (numbers[0]), numbers[1], numbers[2]);
  1091. }
  1092. else if (t.startsWithIgnoreCase ("skewX"))
  1093. {
  1094. trans = AffineTransform::shear (std::tan (degreesToRadians (numbers[0])), 0.0f);
  1095. }
  1096. else if (t.startsWithIgnoreCase ("skewY"))
  1097. {
  1098. trans = AffineTransform::shear (0.0f, std::tan (degreesToRadians (numbers[0])));
  1099. }
  1100. result = trans.followedBy (result);
  1101. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  1102. }
  1103. return result;
  1104. }
  1105. static void endpointToCentreParameters (const double x1, const double y1,
  1106. const double x2, const double y2,
  1107. const double angle,
  1108. const bool largeArc, const bool sweep,
  1109. double& rx, double& ry,
  1110. double& centreX, double& centreY,
  1111. double& startAngle, double& deltaAngle) noexcept
  1112. {
  1113. const double midX = (x1 - x2) * 0.5;
  1114. const double midY = (y1 - y2) * 0.5;
  1115. const double cosAngle = std::cos (angle);
  1116. const double sinAngle = std::sin (angle);
  1117. const double xp = cosAngle * midX + sinAngle * midY;
  1118. const double yp = cosAngle * midY - sinAngle * midX;
  1119. const double xp2 = xp * xp;
  1120. const double yp2 = yp * yp;
  1121. double rx2 = rx * rx;
  1122. double ry2 = ry * ry;
  1123. const double s = (xp2 / rx2) + (yp2 / ry2);
  1124. double c;
  1125. if (s <= 1.0)
  1126. {
  1127. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  1128. / (( rx2 * yp2) + (ry2 * xp2))));
  1129. if (largeArc == sweep)
  1130. c = -c;
  1131. }
  1132. else
  1133. {
  1134. const double s2 = std::sqrt (s);
  1135. rx *= s2;
  1136. ry *= s2;
  1137. c = 0;
  1138. }
  1139. const double cpx = ((rx * yp) / ry) * c;
  1140. const double cpy = ((-ry * xp) / rx) * c;
  1141. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  1142. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  1143. const double ux = (xp - cpx) / rx;
  1144. const double uy = (yp - cpy) / ry;
  1145. const double vx = (-xp - cpx) / rx;
  1146. const double vy = (-yp - cpy) / ry;
  1147. const double length = juce_hypot (ux, uy);
  1148. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  1149. if (uy < 0)
  1150. startAngle = -startAngle;
  1151. startAngle += double_Pi * 0.5;
  1152. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  1153. / (length * juce_hypot (vx, vy))));
  1154. if ((ux * vy) - (uy * vx) < 0)
  1155. deltaAngle = -deltaAngle;
  1156. if (sweep)
  1157. {
  1158. if (deltaAngle < 0)
  1159. deltaAngle += double_Pi * 2.0;
  1160. }
  1161. else
  1162. {
  1163. if (deltaAngle > 0)
  1164. deltaAngle -= double_Pi * 2.0;
  1165. }
  1166. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  1167. }
  1168. SVGState& operator= (const SVGState&) JUCE_DELETED_FUNCTION;
  1169. };
  1170. //==============================================================================
  1171. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  1172. {
  1173. SVGState state (&svgDocument);
  1174. return state.parseSVGElement (SVGState::XmlPath (&svgDocument, nullptr));
  1175. }
  1176. Path Drawable::parseSVGPath (const String& svgPath)
  1177. {
  1178. SVGState state (nullptr);
  1179. Path p;
  1180. state.parsePathString (p, svgPath);
  1181. return p;
  1182. }