Audio plugin host https://kx.studio/carla
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.

juce_SVGParser.cpp 46KB

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