juce_SVGParser.cpp 59 KB

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