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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  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 (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 = 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, 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, 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 = 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, 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. 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 (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& operator= (const SVGState&) = delete;
  1368. };
  1369. //==============================================================================
  1370. std::unique_ptr<Drawable> Drawable::createFromSVG (const XmlElement& svgDocument)
  1371. {
  1372. if (! svgDocument.hasTagNameIgnoringNamespace ("svg"))
  1373. return {};
  1374. SVGState state (&svgDocument);
  1375. return std::unique_ptr<Drawable> (state.parseSVGElement (SVGState::XmlPath (&svgDocument, {})));
  1376. }
  1377. std::unique_ptr<Drawable> Drawable::createFromSVGFile (const File& svgFile)
  1378. {
  1379. if (auto xml = parseXMLIfTagMatches (svgFile, "svg"))
  1380. return createFromSVG (*xml);
  1381. return {};
  1382. }
  1383. Path Drawable::parseSVGPath (const String& svgPath)
  1384. {
  1385. SVGState state (nullptr);
  1386. Path p;
  1387. state.parsePathString (p, svgPath);
  1388. return p;
  1389. }
  1390. } // namespace juce