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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - 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 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-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. forEachXmlChildElement (*xml, e)
  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 (num.getFloatValue());
  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 = d.findEndOfWhitespace();
  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, const bool shouldParseClip = true)
  373. {
  374. forEachXmlChildElement (*xml, e)
  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, const 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. const 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 = t.findEndOfWhitespace();
  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. forEachXmlChildElementWithTagName (*fillXml, e, "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, opacity.getFloatValue()));
  666. double offset = e->getDoubleAttribute ("offset");
  667. if (e->getStringAttribute ("offset").containsChar ('%'))
  668. offset *= 0.01;
  669. cg.addColour (jlimit (0.0, 1.0, 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, overallOpacity.getFloatValue());
  783. if (fillOpacity.isNotEmpty())
  784. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  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 ((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 = 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[8] = { 0 };
  1188. hex[6] = hex[7] = 15;
  1189. int numChars = 0;
  1190. auto s = text.getCharPointer();
  1191. while (numChars < 8)
  1192. {
  1193. auto hexValue = CharacterFunctions::getHexDigitValue (*++s);
  1194. if (hexValue >= 0)
  1195. hex[numChars++] = (uint32) hexValue;
  1196. else
  1197. break;
  1198. }
  1199. if (numChars <= 3)
  1200. return Colour ((uint8) (hex[0] * 0x11),
  1201. (uint8) (hex[1] * 0x11),
  1202. (uint8) (hex[2] * 0x11));
  1203. return Colour ((uint8) ((hex[0] << 4) + hex[1]),
  1204. (uint8) ((hex[2] << 4) + hex[3]),
  1205. (uint8) ((hex[4] << 4) + hex[5]),
  1206. (uint8) ((hex[6] << 4) + hex[7]));
  1207. }
  1208. if (text.startsWith ("rgb") || text.startsWith ("hsl"))
  1209. {
  1210. auto tokens = [&text]
  1211. {
  1212. auto openBracket = text.indexOfChar ('(');
  1213. auto closeBracket = text.indexOfChar (openBracket, ')');
  1214. StringArray arr;
  1215. if (openBracket >= 3 && closeBracket > openBracket)
  1216. {
  1217. arr.addTokens (text.substring (openBracket + 1, closeBracket), ",", "");
  1218. arr.trim();
  1219. arr.removeEmptyStrings();
  1220. }
  1221. return arr;
  1222. }();
  1223. auto alpha = [&tokens, &text]
  1224. {
  1225. if ((text.startsWith ("rgba") || text.startsWith ("hsla")) && tokens.size() == 4)
  1226. return tokens[3].getFloatValue();
  1227. return 1.0f;
  1228. }();
  1229. if (text.startsWith ("hsl"))
  1230. return Colour::fromHSL ((float) (tokens[0].getDoubleValue() / 360.0),
  1231. (float) (tokens[1].getDoubleValue() / 100.0),
  1232. (float) (tokens[2].getDoubleValue() / 100.0),
  1233. alpha);
  1234. if (tokens[0].containsChar ('%'))
  1235. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  1236. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  1237. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()),
  1238. alpha);
  1239. return Colour ((uint8) tokens[0].getIntValue(),
  1240. (uint8) tokens[1].getIntValue(),
  1241. (uint8) tokens[2].getIntValue(),
  1242. alpha);
  1243. }
  1244. if (text == "inherit")
  1245. {
  1246. for (const XmlPath* p = xml.parent; p != nullptr; p = p->parent)
  1247. if (getStyleAttribute (*p, attributeName).isNotEmpty())
  1248. return parseColour (*p, attributeName, defaultColour);
  1249. }
  1250. return Colours::findColourForName (text, defaultColour);
  1251. }
  1252. static AffineTransform parseTransform (String t)
  1253. {
  1254. AffineTransform result;
  1255. while (t.isNotEmpty())
  1256. {
  1257. StringArray tokens;
  1258. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  1259. .upToFirstOccurrenceOf (")", false, false),
  1260. ", ", "");
  1261. tokens.removeEmptyStrings (true);
  1262. float numbers[6];
  1263. for (int i = 0; i < numElementsInArray (numbers); ++i)
  1264. numbers[i] = tokens[i].getFloatValue();
  1265. AffineTransform trans;
  1266. if (t.startsWithIgnoreCase ("matrix"))
  1267. {
  1268. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  1269. numbers[1], numbers[3], numbers[5]);
  1270. }
  1271. else if (t.startsWithIgnoreCase ("translate"))
  1272. {
  1273. trans = AffineTransform::translation (numbers[0], numbers[1]);
  1274. }
  1275. else if (t.startsWithIgnoreCase ("scale"))
  1276. {
  1277. trans = AffineTransform::scale (numbers[0], numbers[tokens.size() > 1 ? 1 : 0]);
  1278. }
  1279. else if (t.startsWithIgnoreCase ("rotate"))
  1280. {
  1281. trans = AffineTransform::rotation (degreesToRadians (numbers[0]), numbers[1], numbers[2]);
  1282. }
  1283. else if (t.startsWithIgnoreCase ("skewX"))
  1284. {
  1285. trans = AffineTransform::shear (std::tan (degreesToRadians (numbers[0])), 0.0f);
  1286. }
  1287. else if (t.startsWithIgnoreCase ("skewY"))
  1288. {
  1289. trans = AffineTransform::shear (0.0f, std::tan (degreesToRadians (numbers[0])));
  1290. }
  1291. result = trans.followedBy (result);
  1292. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  1293. }
  1294. return result;
  1295. }
  1296. static void endpointToCentreParameters (double x1, double y1,
  1297. double x2, double y2,
  1298. double angle,
  1299. bool largeArc, bool sweep,
  1300. double& rx, double& ry,
  1301. double& centreX, double& centreY,
  1302. double& startAngle, double& deltaAngle) noexcept
  1303. {
  1304. const double midX = (x1 - x2) * 0.5;
  1305. const double midY = (y1 - y2) * 0.5;
  1306. const double cosAngle = std::cos (angle);
  1307. const double sinAngle = std::sin (angle);
  1308. const double xp = cosAngle * midX + sinAngle * midY;
  1309. const double yp = cosAngle * midY - sinAngle * midX;
  1310. const double xp2 = xp * xp;
  1311. const double yp2 = yp * yp;
  1312. double rx2 = rx * rx;
  1313. double ry2 = ry * ry;
  1314. const double s = (xp2 / rx2) + (yp2 / ry2);
  1315. double c;
  1316. if (s <= 1.0)
  1317. {
  1318. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  1319. / (( rx2 * yp2) + (ry2 * xp2))));
  1320. if (largeArc == sweep)
  1321. c = -c;
  1322. }
  1323. else
  1324. {
  1325. const double s2 = std::sqrt (s);
  1326. rx *= s2;
  1327. ry *= s2;
  1328. c = 0;
  1329. }
  1330. const double cpx = ((rx * yp) / ry) * c;
  1331. const double cpy = ((-ry * xp) / rx) * c;
  1332. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  1333. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  1334. const double ux = (xp - cpx) / rx;
  1335. const double uy = (yp - cpy) / ry;
  1336. const double vx = (-xp - cpx) / rx;
  1337. const double vy = (-yp - cpy) / ry;
  1338. const double length = juce_hypot (ux, uy);
  1339. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  1340. if (uy < 0)
  1341. startAngle = -startAngle;
  1342. startAngle += MathConstants<double>::halfPi;
  1343. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  1344. / (length * juce_hypot (vx, vy))));
  1345. if ((ux * vy) - (uy * vx) < 0)
  1346. deltaAngle = -deltaAngle;
  1347. if (sweep)
  1348. {
  1349. if (deltaAngle < 0)
  1350. deltaAngle += MathConstants<double>::twoPi;
  1351. }
  1352. else
  1353. {
  1354. if (deltaAngle > 0)
  1355. deltaAngle -= MathConstants<double>::twoPi;
  1356. }
  1357. deltaAngle = fmod (deltaAngle, MathConstants<double>::twoPi);
  1358. }
  1359. SVGState& operator= (const SVGState&) = delete;
  1360. };
  1361. //==============================================================================
  1362. std::unique_ptr<Drawable> Drawable::createFromSVG (const XmlElement& svgDocument)
  1363. {
  1364. if (! svgDocument.hasTagNameIgnoringNamespace ("svg"))
  1365. return {};
  1366. SVGState state (&svgDocument);
  1367. return std::unique_ptr<Drawable> (state.parseSVGElement (SVGState::XmlPath (&svgDocument, {})));
  1368. }
  1369. std::unique_ptr<Drawable> Drawable::createFromSVGFile (const File& svgFile)
  1370. {
  1371. if (auto xml = parseXMLIfTagMatches (svgFile, "svg"))
  1372. return createFromSVG (*xml);
  1373. return {};
  1374. }
  1375. Path Drawable::parseSVGPath (const String& svgPath)
  1376. {
  1377. SVGState state (nullptr);
  1378. Path p;
  1379. state.parsePathString (p, svgPath);
  1380. return p;
  1381. }
  1382. } // namespace juce