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

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