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 60KB

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