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

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. class SVGState
  18. {
  19. public:
  20. //==============================================================================
  21. explicit SVGState (const XmlElement* const topLevel)
  22. : topLevelXml (topLevel, nullptr),
  23. elementX (0), elementY (0),
  24. width (512), height (512),
  25. viewBoxW (0), viewBoxH (0)
  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. const XmlElement* xml;
  35. const XmlPath* parent;
  36. };
  37. //==============================================================================
  38. Drawable* parseSVGElement (const XmlPath& xml)
  39. {
  40. if (! xml->hasTagNameIgnoringNamespace ("svg"))
  41. return nullptr;
  42. DrawableComposite* const drawable = new DrawableComposite();
  43. setCommonAttributes (*drawable, xml);
  44. SVGState newState (*this);
  45. if (xml->hasAttribute ("transform"))
  46. newState.addTransform (xml);
  47. newState.elementX = getCoordLength (xml->getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  48. newState.elementY = getCoordLength (xml->getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  49. newState.width = getCoordLength (xml->getStringAttribute ("width", String (newState.width)), viewBoxW);
  50. newState.height = getCoordLength (xml->getStringAttribute ("height", String (newState.height)), viewBoxH);
  51. if (newState.width <= 0) newState.width = 100;
  52. if (newState.height <= 0) newState.height = 100;
  53. Point<float> viewboxXY;
  54. if (xml->hasAttribute ("viewBox"))
  55. {
  56. const String viewBoxAtt (xml->getStringAttribute ("viewBox"));
  57. String::CharPointerType viewParams (viewBoxAtt.getCharPointer());
  58. Point<float> vwh;
  59. if (parseCoords (viewParams, viewboxXY, true)
  60. && parseCoords (viewParams, vwh, true)
  61. && vwh.x > 0
  62. && vwh.y > 0)
  63. {
  64. newState.viewBoxW = vwh.x;
  65. newState.viewBoxH = vwh.y;
  66. const int placementFlags = parsePlacementFlags (xml->getStringAttribute ("preserveAspectRatio").trim());
  67. if (placementFlags != 0)
  68. newState.transform = RectanglePlacement (placementFlags)
  69. .getTransformToFit (Rectangle<float> (viewboxXY.x, viewboxXY.y, vwh.x, vwh.y),
  70. Rectangle<float> (newState.width, newState.height))
  71. .followedBy (newState.transform);
  72. }
  73. }
  74. else
  75. {
  76. if (viewBoxW == 0) newState.viewBoxW = newState.width;
  77. if (viewBoxH == 0) newState.viewBoxH = newState.height;
  78. }
  79. newState.parseSubElements (xml, *drawable);
  80. drawable->setContentArea (RelativeRectangle (RelativeCoordinate (viewboxXY.x),
  81. RelativeCoordinate (viewboxXY.x + newState.viewBoxW),
  82. RelativeCoordinate (viewboxXY.y),
  83. RelativeCoordinate (viewboxXY.y + newState.viewBoxH)));
  84. drawable->resetBoundingBoxToContentArea();
  85. return drawable;
  86. }
  87. //==============================================================================
  88. void parsePathString (Path& path, const String& pathString) const
  89. {
  90. String::CharPointerType d (pathString.getCharPointer().findEndOfWhitespace());
  91. Point<float> subpathStart, last, last2, p1, p2, p3;
  92. juce_wchar lastCommandChar = 0;
  93. bool isRelative = true;
  94. bool carryOn = true;
  95. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  96. while (! d.isEmpty())
  97. {
  98. if (validCommandChars.indexOf (*d) >= 0)
  99. {
  100. lastCommandChar = d.getAndAdvance();
  101. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  102. }
  103. switch (lastCommandChar)
  104. {
  105. case 'M':
  106. case 'm':
  107. case 'L':
  108. case 'l':
  109. if (parseCoordsOrSkip (d, p1, false))
  110. {
  111. if (isRelative)
  112. p1 += last;
  113. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  114. {
  115. subpathStart = p1;
  116. path.startNewSubPath (p1);
  117. lastCommandChar = 'l';
  118. }
  119. else
  120. path.lineTo (p1);
  121. last2 = last;
  122. last = p1;
  123. }
  124. break;
  125. case 'H':
  126. case 'h':
  127. if (parseCoord (d, p1.x, false, true))
  128. {
  129. if (isRelative)
  130. p1.x += last.x;
  131. path.lineTo (p1.x, last.y);
  132. last2.x = last.x;
  133. last.x = p1.x;
  134. }
  135. else
  136. {
  137. ++d;
  138. }
  139. break;
  140. case 'V':
  141. case 'v':
  142. if (parseCoord (d, p1.y, false, false))
  143. {
  144. if (isRelative)
  145. p1.y += last.y;
  146. path.lineTo (last.x, p1.y);
  147. last2.y = last.y;
  148. last.y = p1.y;
  149. }
  150. else
  151. {
  152. ++d;
  153. }
  154. break;
  155. case 'C':
  156. case 'c':
  157. if (parseCoordsOrSkip (d, p1, false)
  158. && parseCoordsOrSkip (d, p2, false)
  159. && parseCoordsOrSkip (d, p3, false))
  160. {
  161. if (isRelative)
  162. {
  163. p1 += last;
  164. p2 += last;
  165. p3 += last;
  166. }
  167. path.cubicTo (p1, p2, p3);
  168. last2 = p2;
  169. last = p3;
  170. }
  171. break;
  172. case 'S':
  173. case 's':
  174. if (parseCoordsOrSkip (d, p1, false)
  175. && parseCoordsOrSkip (d, p3, false))
  176. {
  177. if (isRelative)
  178. {
  179. p1 += last;
  180. p3 += last;
  181. }
  182. p2 = last + (last - last2);
  183. path.cubicTo (p2, p1, p3);
  184. last2 = p1;
  185. last = p3;
  186. }
  187. break;
  188. case 'Q':
  189. case 'q':
  190. if (parseCoordsOrSkip (d, p1, false)
  191. && parseCoordsOrSkip (d, p2, false))
  192. {
  193. if (isRelative)
  194. {
  195. p1 += last;
  196. p2 += last;
  197. }
  198. path.quadraticTo (p1, p2);
  199. last2 = p1;
  200. last = p2;
  201. }
  202. break;
  203. case 'T':
  204. case 't':
  205. if (parseCoordsOrSkip (d, p1, false))
  206. {
  207. if (isRelative)
  208. p1 += last;
  209. p2 = last + (last - last2);
  210. path.quadraticTo (p2, p1);
  211. last2 = p2;
  212. last = p1;
  213. }
  214. break;
  215. case 'A':
  216. case 'a':
  217. if (parseCoordsOrSkip (d, p1, false))
  218. {
  219. String num;
  220. if (parseNextNumber (d, num, false))
  221. {
  222. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  223. if (parseNextNumber (d, num, false))
  224. {
  225. const bool largeArc = num.getIntValue() != 0;
  226. if (parseNextNumber (d, num, false))
  227. {
  228. const bool sweep = num.getIntValue() != 0;
  229. if (parseCoordsOrSkip (d, p2, false))
  230. {
  231. if (isRelative)
  232. p2 += last;
  233. if (last != p2)
  234. {
  235. double centreX, centreY, startAngle, deltaAngle;
  236. double rx = p1.x, ry = p1.y;
  237. endpointToCentreParameters (last.x, last.y, p2.x, p2.y,
  238. angle, largeArc, sweep,
  239. rx, ry, centreX, centreY,
  240. startAngle, deltaAngle);
  241. path.addCentredArc ((float) centreX, (float) centreY,
  242. (float) rx, (float) ry,
  243. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  244. false);
  245. path.lineTo (p2);
  246. }
  247. last2 = last;
  248. last = p2;
  249. }
  250. }
  251. }
  252. }
  253. }
  254. break;
  255. case 'Z':
  256. case 'z':
  257. path.closeSubPath();
  258. last = last2 = subpathStart;
  259. d = d.findEndOfWhitespace();
  260. lastCommandChar = 'M';
  261. break;
  262. default:
  263. carryOn = false;
  264. break;
  265. }
  266. if (! carryOn)
  267. break;
  268. }
  269. // paths that finish back at their start position often seem to be
  270. // left without a 'z', so need to be closed explicitly..
  271. if (path.getCurrentPosition() == subpathStart)
  272. path.closeSubPath();
  273. }
  274. private:
  275. //==============================================================================
  276. const XmlPath topLevelXml;
  277. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  278. AffineTransform transform;
  279. String cssStyleText;
  280. static void setCommonAttributes (Drawable& d, const XmlPath& xml)
  281. {
  282. String compID (xml->getStringAttribute ("id"));
  283. d.setName (compID);
  284. d.setComponentID (compID);
  285. if (xml->getStringAttribute ("display") == "none")
  286. d.setVisible (false);
  287. }
  288. //==============================================================================
  289. void parseSubElements (const XmlPath& xml, DrawableComposite& parentDrawable)
  290. {
  291. forEachXmlChildElement (*xml, e)
  292. parentDrawable.addAndMakeVisible (parseSubElement (xml.getChild (e)));
  293. }
  294. Drawable* parseSubElement (const XmlPath& xml)
  295. {
  296. const String tag (xml->getTagNameWithoutNamespace());
  297. if (tag == "g") return parseGroupElement (xml);
  298. if (tag == "svg") return parseSVGElement (xml);
  299. if (tag == "path") return parsePath (xml);
  300. if (tag == "rect") return parseRect (xml);
  301. if (tag == "circle") return parseCircle (xml);
  302. if (tag == "ellipse") return parseEllipse (xml);
  303. if (tag == "line") return parseLine (xml);
  304. if (tag == "polyline") return parsePolygon (xml, true);
  305. if (tag == "polygon") return parsePolygon (xml, false);
  306. if (tag == "text") return parseText (xml, true);
  307. if (tag == "switch") return parseSwitch (xml);
  308. if (tag == "style") parseCSSStyle (xml);
  309. return nullptr;
  310. }
  311. DrawableComposite* parseSwitch (const XmlPath& xml)
  312. {
  313. if (const XmlElement* const group = xml->getChildByName ("g"))
  314. return parseGroupElement (xml.getChild (group));
  315. return nullptr;
  316. }
  317. DrawableComposite* parseGroupElement (const XmlPath& xml)
  318. {
  319. DrawableComposite* const drawable = new DrawableComposite();
  320. setCommonAttributes (*drawable, xml);
  321. if (xml->hasAttribute ("transform"))
  322. {
  323. SVGState newState (*this);
  324. newState.addTransform (xml);
  325. newState.parseSubElements (xml, *drawable);
  326. }
  327. else
  328. {
  329. parseSubElements (xml, *drawable);
  330. }
  331. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  332. return drawable;
  333. }
  334. //==============================================================================
  335. Drawable* parsePath (const XmlPath& xml) const
  336. {
  337. Path path;
  338. parsePathString (path, xml->getStringAttribute ("d"));
  339. if (getStyleAttribute (xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  340. path.setUsingNonZeroWinding (false);
  341. return parseShape (xml, path);
  342. }
  343. Drawable* parseRect (const XmlPath& xml) const
  344. {
  345. Path rect;
  346. const bool hasRX = xml->hasAttribute ("rx");
  347. const bool hasRY = xml->hasAttribute ("ry");
  348. if (hasRX || hasRY)
  349. {
  350. float rx = getCoordLength (xml, "rx", viewBoxW);
  351. float ry = getCoordLength (xml, "ry", viewBoxH);
  352. if (! hasRX)
  353. rx = ry;
  354. else if (! hasRY)
  355. ry = rx;
  356. rect.addRoundedRectangle (getCoordLength (xml, "x", viewBoxW),
  357. getCoordLength (xml, "y", viewBoxH),
  358. getCoordLength (xml, "width", viewBoxW),
  359. getCoordLength (xml, "height", viewBoxH),
  360. rx, ry);
  361. }
  362. else
  363. {
  364. rect.addRectangle (getCoordLength (xml, "x", viewBoxW),
  365. getCoordLength (xml, "y", viewBoxH),
  366. getCoordLength (xml, "width", viewBoxW),
  367. getCoordLength (xml, "height", viewBoxH));
  368. }
  369. return parseShape (xml, rect);
  370. }
  371. Drawable* parseCircle (const XmlPath& xml) const
  372. {
  373. Path circle;
  374. const float cx = getCoordLength (xml, "cx", viewBoxW);
  375. const float cy = getCoordLength (xml, "cy", viewBoxH);
  376. const float radius = getCoordLength (xml, "r", viewBoxW);
  377. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  378. return parseShape (xml, circle);
  379. }
  380. Drawable* parseEllipse (const XmlPath& xml) const
  381. {
  382. Path ellipse;
  383. const float cx = getCoordLength (xml, "cx", viewBoxW);
  384. const float cy = getCoordLength (xml, "cy", viewBoxH);
  385. const float radiusX = getCoordLength (xml, "rx", viewBoxW);
  386. const float radiusY = getCoordLength (xml, "ry", viewBoxH);
  387. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  388. return parseShape (xml, ellipse);
  389. }
  390. Drawable* parseLine (const XmlPath& xml) const
  391. {
  392. Path line;
  393. const float x1 = getCoordLength (xml, "x1", viewBoxW);
  394. const float y1 = getCoordLength (xml, "y1", viewBoxH);
  395. const float x2 = getCoordLength (xml, "x2", viewBoxW);
  396. const float y2 = getCoordLength (xml, "y2", viewBoxH);
  397. line.startNewSubPath (x1, y1);
  398. line.lineTo (x2, y2);
  399. return parseShape (xml, line);
  400. }
  401. Drawable* parsePolygon (const XmlPath& xml, const bool isPolyline) const
  402. {
  403. const String pointsAtt (xml->getStringAttribute ("points"));
  404. String::CharPointerType points (pointsAtt.getCharPointer());
  405. Path path;
  406. Point<float> p;
  407. if (parseCoords (points, p, true))
  408. {
  409. Point<float> first (p), last;
  410. path.startNewSubPath (first);
  411. while (parseCoords (points, p, true))
  412. {
  413. last = p;
  414. path.lineTo (p);
  415. }
  416. if ((! isPolyline) || first == last)
  417. path.closeSubPath();
  418. }
  419. return parseShape (xml, path);
  420. }
  421. //==============================================================================
  422. Drawable* parseShape (const XmlPath& xml, Path& path,
  423. const bool shouldParseTransform = true) const
  424. {
  425. if (shouldParseTransform && xml->hasAttribute ("transform"))
  426. {
  427. SVGState newState (*this);
  428. newState.addTransform (xml);
  429. return newState.parseShape (xml, path, false);
  430. }
  431. DrawablePath* dp = new DrawablePath();
  432. setCommonAttributes (*dp, xml);
  433. dp->setFill (Colours::transparentBlack);
  434. path.applyTransform (transform);
  435. dp->setPath (path);
  436. dp->setFill (getPathFillType (path,
  437. getStyleAttribute (xml, "fill"),
  438. getStyleAttribute (xml, "fill-opacity"),
  439. getStyleAttribute (xml, "opacity"),
  440. pathContainsClosedSubPath (path) ? Colours::black
  441. : Colours::transparentBlack));
  442. const String strokeType (getStyleAttribute (xml, "stroke"));
  443. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  444. {
  445. dp->setStrokeFill (getPathFillType (path, strokeType,
  446. getStyleAttribute (xml, "stroke-opacity"),
  447. getStyleAttribute (xml, "opacity"),
  448. Colours::transparentBlack));
  449. dp->setStrokeType (getStrokeFor (xml));
  450. }
  451. return dp;
  452. }
  453. static bool pathContainsClosedSubPath (const Path& path) noexcept
  454. {
  455. for (Path::Iterator iter (path); iter.next();)
  456. if (iter.elementType == Path::Iterator::closePath)
  457. return true;
  458. return false;
  459. }
  460. struct SetGradientStopsOp
  461. {
  462. const SVGState* state;
  463. ColourGradient* gradient;
  464. void operator() (const XmlPath& xml)
  465. {
  466. state->addGradientStopsIn (*gradient, xml);
  467. }
  468. };
  469. void addGradientStopsIn (ColourGradient& cg, const XmlPath& fillXml) const
  470. {
  471. if (fillXml.xml != nullptr)
  472. {
  473. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  474. {
  475. int index = 0;
  476. Colour col (parseColour (getStyleAttribute (fillXml.getChild (e), "stop-color"), index, Colours::black));
  477. const String opacity (getStyleAttribute (fillXml.getChild (e), "stop-opacity", "1"));
  478. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  479. double offset = e->getDoubleAttribute ("offset");
  480. if (e->getStringAttribute ("offset").containsChar ('%'))
  481. offset *= 0.01;
  482. cg.addColour (jlimit (0.0, 1.0, offset), col);
  483. }
  484. }
  485. }
  486. FillType getGradientFillType (const XmlPath& fillXml,
  487. const Path& path,
  488. const float opacity) const
  489. {
  490. ColourGradient gradient;
  491. {
  492. const String id (fillXml->getStringAttribute ("xlink:href"));
  493. if (id.startsWithChar ('#'))
  494. {
  495. SetGradientStopsOp op = { this, &gradient, };
  496. findElementForId (topLevelXml, id.substring (1), op);
  497. }
  498. }
  499. addGradientStopsIn (gradient, fillXml);
  500. if (gradient.getNumColours() > 0)
  501. {
  502. gradient.addColour (0.0, gradient.getColour (0));
  503. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  504. }
  505. else
  506. {
  507. gradient.addColour (0.0, Colours::black);
  508. gradient.addColour (1.0, Colours::black);
  509. }
  510. if (opacity < 1.0f)
  511. gradient.multiplyOpacity (opacity);
  512. jassert (gradient.getNumColours() > 0);
  513. gradient.isRadial = fillXml->hasTagNameIgnoringNamespace ("radialGradient");
  514. float gradientWidth = viewBoxW;
  515. float gradientHeight = viewBoxH;
  516. float dx = 0.0f;
  517. float dy = 0.0f;
  518. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  519. if (! userSpace)
  520. {
  521. const Rectangle<float> bounds (path.getBounds());
  522. dx = bounds.getX();
  523. dy = bounds.getY();
  524. gradientWidth = bounds.getWidth();
  525. gradientHeight = bounds.getHeight();
  526. }
  527. if (gradient.isRadial)
  528. {
  529. if (userSpace)
  530. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  531. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  532. else
  533. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  534. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  535. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  536. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  537. //xxx (the fx, fy focal point isn't handled properly here..)
  538. }
  539. else
  540. {
  541. if (userSpace)
  542. {
  543. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  544. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  545. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  546. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  547. }
  548. else
  549. {
  550. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  551. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  552. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  553. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  554. }
  555. if (gradient.point1 == gradient.point2)
  556. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  557. }
  558. FillType type (gradient);
  559. const AffineTransform gradientTransform (parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  560. .followedBy (transform));
  561. if (gradient.isRadial)
  562. {
  563. type.transform = gradientTransform;
  564. }
  565. else
  566. {
  567. // Transform the perpendicular vector into the new coordinate space for the gradient.
  568. // This vector is now the slope of the linear gradient as it should appear in the new coord space
  569. const Point<float> perpendicular (Point<float> (gradient.point2.y - gradient.point1.y,
  570. gradient.point1.x - gradient.point2.x)
  571. .transformedBy (gradientTransform.withAbsoluteTranslation (0, 0)));
  572. const Point<float> newGradPoint1 (gradient.point1.transformedBy (gradientTransform));
  573. const Point<float> newGradPoint2 (gradient.point2.transformedBy (gradientTransform));
  574. // Project the transformed gradient vector onto the transformed slope of the linear
  575. // gradient as it should appear in the new coordinate space
  576. const float scale = perpendicular.getDotProduct (newGradPoint2 - newGradPoint1)
  577. / perpendicular.getDotProduct (perpendicular);
  578. type.gradient->point1 = newGradPoint1;
  579. type.gradient->point2 = newGradPoint2 - perpendicular * scale;
  580. }
  581. return type;
  582. }
  583. struct GetFillTypeOp
  584. {
  585. const SVGState* state;
  586. FillType* dest;
  587. const Path* path;
  588. float opacity;
  589. void operator() (const XmlPath& xml)
  590. {
  591. if (xml->hasTagNameIgnoringNamespace ("linearGradient")
  592. || xml->hasTagNameIgnoringNamespace ("radialGradient"))
  593. *dest = state->getGradientFillType (xml, *path, opacity);
  594. }
  595. };
  596. FillType getPathFillType (const Path& path,
  597. const String& fill,
  598. const String& fillOpacity,
  599. const String& overallOpacity,
  600. const Colour defaultColour) const
  601. {
  602. float opacity = 1.0f;
  603. if (overallOpacity.isNotEmpty())
  604. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  605. if (fillOpacity.isNotEmpty())
  606. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  607. if (fill.startsWithIgnoreCase ("url"))
  608. {
  609. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  610. .upToLastOccurrenceOf (")", false, false).trim());
  611. FillType result;
  612. GetFillTypeOp op = { this, &result, &path, opacity };
  613. if (findElementForId (topLevelXml, id, op))
  614. return result;
  615. }
  616. if (fill.equalsIgnoreCase ("none"))
  617. return Colours::transparentBlack;
  618. int i = 0;
  619. return parseColour (fill, i, defaultColour).withMultipliedAlpha (opacity);
  620. }
  621. static PathStrokeType::JointStyle getJointStyle (const String& join) noexcept
  622. {
  623. if (join.equalsIgnoreCase ("round")) return PathStrokeType::curved;
  624. if (join.equalsIgnoreCase ("bevel")) return PathStrokeType::beveled;
  625. return PathStrokeType::mitered;
  626. }
  627. static PathStrokeType::EndCapStyle getEndCapStyle (const String& cap) noexcept
  628. {
  629. if (cap.equalsIgnoreCase ("round")) return PathStrokeType::rounded;
  630. if (cap.equalsIgnoreCase ("square")) return PathStrokeType::square;
  631. return PathStrokeType::butt;
  632. }
  633. float getStrokeWidth (const String& strokeWidth) const noexcept
  634. {
  635. return transform.getScaleFactor() * getCoordLength (strokeWidth, viewBoxW);
  636. }
  637. PathStrokeType getStrokeFor (const XmlPath& xml) const
  638. {
  639. return PathStrokeType (getStrokeWidth (getStyleAttribute (xml, "stroke-width", "1")),
  640. getJointStyle (getStyleAttribute (xml, "stroke-linejoin")),
  641. getEndCapStyle (getStyleAttribute (xml, "stroke-linecap")));
  642. }
  643. //==============================================================================
  644. Drawable* parseText (const XmlPath& xml, bool shouldParseTransform)
  645. {
  646. if (shouldParseTransform && xml->hasAttribute ("transform"))
  647. {
  648. SVGState newState (*this);
  649. newState.addTransform (xml);
  650. return newState.parseText (xml, false);
  651. }
  652. Array<float> xCoords, yCoords, dxCoords, dyCoords;
  653. getCoordList (xCoords, getInheritedAttribute (xml, "x"), true, true);
  654. getCoordList (yCoords, getInheritedAttribute (xml, "y"), true, false);
  655. getCoordList (dxCoords, getInheritedAttribute (xml, "dx"), true, true);
  656. getCoordList (dyCoords, getInheritedAttribute (xml, "dy"), true, false);
  657. const Font font (getFont (xml));
  658. const String anchorStr = getStyleAttribute(xml, "text-anchor");
  659. DrawableComposite* dc = new DrawableComposite();
  660. setCommonAttributes (*dc, xml);
  661. forEachXmlChildElement (*xml, e)
  662. {
  663. if (e->isTextElement())
  664. {
  665. const String text (e->getText().trim());
  666. DrawableText* dt = new DrawableText();
  667. dc->addAndMakeVisible (dt);
  668. dt->setText (text);
  669. dt->setFont (font, true);
  670. dt->setTransform (transform);
  671. int i = 0;
  672. dt->setColour (parseColour (getStyleAttribute (xml, "fill"), i, Colours::black)
  673. .withMultipliedAlpha (getStyleAttribute (xml, "fill-opacity", "1").getFloatValue()));
  674. Rectangle<float> bounds (xCoords[0], yCoords[0] - font.getAscent(),
  675. font.getStringWidthFloat (text), font.getHeight());
  676. if (anchorStr == "middle") bounds.setX (bounds.getX() - bounds.getWidth() / 2.0f);
  677. else if (anchorStr == "end") bounds.setX (bounds.getX() - bounds.getWidth());
  678. dt->setBoundingBox (bounds);
  679. }
  680. else if (e->hasTagNameIgnoringNamespace ("tspan"))
  681. {
  682. dc->addAndMakeVisible (parseText (xml.getChild (e), true));
  683. }
  684. }
  685. return dc;
  686. }
  687. Font getFont (const XmlPath& xml) const
  688. {
  689. const float fontSize = getCoordLength (getStyleAttribute (xml, "font-size"), 1.0f);
  690. int style = getStyleAttribute (xml, "font-style").containsIgnoreCase ("italic") ? Font::italic : Font::plain;
  691. if (getStyleAttribute (xml, "font-weight").containsIgnoreCase ("bold"))
  692. style |= Font::bold;
  693. const String family (getStyleAttribute (xml, "font-family"));
  694. return family.isEmpty() ? Font (fontSize, style)
  695. : Font (family, fontSize, style);
  696. }
  697. //==============================================================================
  698. void addTransform (const XmlPath& xml)
  699. {
  700. transform = parseTransform (xml->getStringAttribute ("transform"))
  701. .followedBy (transform);
  702. }
  703. //==============================================================================
  704. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  705. {
  706. String number;
  707. if (! parseNextNumber (s, number, allowUnits))
  708. {
  709. value = 0;
  710. return false;
  711. }
  712. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  713. return true;
  714. }
  715. bool parseCoords (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  716. {
  717. return parseCoord (s, p.x, allowUnits, true)
  718. && parseCoord (s, p.y, allowUnits, false);
  719. }
  720. bool parseCoordsOrSkip (String::CharPointerType& s, Point<float>& p, const bool allowUnits) const
  721. {
  722. if (parseCoords (s, p, allowUnits))
  723. return true;
  724. if (! s.isEmpty()) ++s;
  725. return false;
  726. }
  727. float getCoordLength (const String& s, const float sizeForProportions) const noexcept
  728. {
  729. float n = s.getFloatValue();
  730. const int len = s.length();
  731. if (len > 2)
  732. {
  733. const float dpi = 96.0f;
  734. const juce_wchar n1 = s [len - 2];
  735. const juce_wchar n2 = s [len - 1];
  736. if (n1 == 'i' && n2 == 'n') n *= dpi;
  737. else if (n1 == 'm' && n2 == 'm') n *= dpi / 25.4f;
  738. else if (n1 == 'c' && n2 == 'm') n *= dpi / 2.54f;
  739. else if (n1 == 'p' && n2 == 'c') n *= 15.0f;
  740. else if (n2 == '%') n *= 0.01f * sizeForProportions;
  741. }
  742. return n;
  743. }
  744. float getCoordLength (const XmlPath& xml, const char* attName, const float sizeForProportions) const noexcept
  745. {
  746. return getCoordLength (xml->getStringAttribute (attName), sizeForProportions);
  747. }
  748. void getCoordList (Array<float>& coords, const String& list, bool allowUnits, const bool isX) const
  749. {
  750. String::CharPointerType text (list.getCharPointer());
  751. float value;
  752. while (parseCoord (text, value, allowUnits, isX))
  753. coords.add (value);
  754. }
  755. //==============================================================================
  756. void parseCSSStyle (const XmlPath& xml)
  757. {
  758. cssStyleText = xml->getAllSubText() + "\n" + cssStyleText;
  759. }
  760. static String::CharPointerType findStyleItem (String::CharPointerType source, String::CharPointerType name)
  761. {
  762. const int nameLength = (int) name.length();
  763. while (! source.isEmpty())
  764. {
  765. if (source.getAndAdvance() == '.'
  766. && CharacterFunctions::compareIgnoreCaseUpTo (source, name, nameLength) == 0)
  767. {
  768. String::CharPointerType endOfName ((source + nameLength).findEndOfWhitespace());
  769. if (*endOfName == '{')
  770. return endOfName;
  771. }
  772. }
  773. return source;
  774. }
  775. String getStyleAttribute (const XmlPath& xml, StringRef attributeName,
  776. const String& defaultValue = String()) const
  777. {
  778. if (xml->hasAttribute (attributeName))
  779. return xml->getStringAttribute (attributeName, defaultValue);
  780. const String styleAtt (xml->getStringAttribute ("style"));
  781. if (styleAtt.isNotEmpty())
  782. {
  783. const String value (getAttributeFromStyleList (styleAtt, attributeName, String()));
  784. if (value.isNotEmpty())
  785. return value;
  786. }
  787. else if (xml->hasAttribute ("class"))
  788. {
  789. String::CharPointerType openBrace = findStyleItem (cssStyleText.getCharPointer(),
  790. xml->getStringAttribute ("class").getCharPointer());
  791. if (! openBrace.isEmpty())
  792. {
  793. String::CharPointerType closeBrace = CharacterFunctions::find (openBrace, (juce_wchar) '}');
  794. if (closeBrace != openBrace)
  795. {
  796. const String value (getAttributeFromStyleList (String (openBrace + 1, closeBrace),
  797. attributeName, defaultValue));
  798. if (value.isNotEmpty())
  799. return value;
  800. }
  801. }
  802. }
  803. if (xml.parent != nullptr)
  804. return getStyleAttribute (*xml.parent, attributeName, defaultValue);
  805. return defaultValue;
  806. }
  807. String getInheritedAttribute (const XmlPath& xml, StringRef attributeName) const
  808. {
  809. if (xml->hasAttribute (attributeName))
  810. return xml->getStringAttribute (attributeName);
  811. if (xml.parent != nullptr)
  812. return getInheritedAttribute (*xml.parent, attributeName);
  813. return String();
  814. }
  815. static int parsePlacementFlags (const String& align) noexcept
  816. {
  817. if (align.isEmpty())
  818. return 0;
  819. if (align.containsIgnoreCase ("none"))
  820. return RectanglePlacement::stretchToFit;
  821. return (align.containsIgnoreCase ("slice") ? RectanglePlacement::fillDestination : 0)
  822. | (align.containsIgnoreCase ("xMin") ? RectanglePlacement::xLeft
  823. : (align.containsIgnoreCase ("xMax") ? RectanglePlacement::xRight
  824. : RectanglePlacement::xMid))
  825. | (align.containsIgnoreCase ("yMin") ? RectanglePlacement::yTop
  826. : (align.containsIgnoreCase ("yMax") ? RectanglePlacement::yBottom
  827. : RectanglePlacement::yMid));
  828. }
  829. //==============================================================================
  830. static bool isIdentifierChar (const juce_wchar c)
  831. {
  832. return CharacterFunctions::isLetter (c) || c == '-';
  833. }
  834. static String getAttributeFromStyleList (const String& list, StringRef attributeName, const String& defaultValue)
  835. {
  836. int i = 0;
  837. for (;;)
  838. {
  839. i = list.indexOf (i, attributeName);
  840. if (i < 0)
  841. break;
  842. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  843. && ! isIdentifierChar (list [i + attributeName.length()]))
  844. {
  845. i = list.indexOfChar (i, ':');
  846. if (i < 0)
  847. break;
  848. int end = list.indexOfChar (i, ';');
  849. if (end < 0)
  850. end = 0x7ffff;
  851. return list.substring (i + 1, end).trim();
  852. }
  853. ++i;
  854. }
  855. return defaultValue;
  856. }
  857. //==============================================================================
  858. static bool parseNextNumber (String::CharPointerType& text, String& value, const bool allowUnits)
  859. {
  860. String::CharPointerType s (text);
  861. while (s.isWhitespace() || *s == ',')
  862. ++s;
  863. String::CharPointerType start (s);
  864. if (s.isDigit() || *s == '.' || *s == '-')
  865. ++s;
  866. while (s.isDigit() || *s == '.')
  867. ++s;
  868. if ((*s == 'e' || *s == 'E')
  869. && ((s + 1).isDigit() || s[1] == '-' || s[1] == '+'))
  870. {
  871. s += 2;
  872. while (s.isDigit())
  873. ++s;
  874. }
  875. if (allowUnits)
  876. while (s.isLetter())
  877. ++s;
  878. if (s == start)
  879. {
  880. text = s;
  881. return false;
  882. }
  883. value = String (start, s);
  884. while (s.isWhitespace() || *s == ',')
  885. ++s;
  886. text = s;
  887. return true;
  888. }
  889. //==============================================================================
  890. static Colour parseColour (const String& s, int& index, const Colour defaultColour)
  891. {
  892. if (s [index] == '#')
  893. {
  894. uint32 hex[6] = { 0 };
  895. int numChars = 0;
  896. for (int i = 6; --i >= 0;)
  897. {
  898. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  899. if (hexValue >= 0)
  900. hex [numChars++] = (uint32) hexValue;
  901. else
  902. break;
  903. }
  904. if (numChars <= 3)
  905. return Colour ((uint8) (hex [0] * 0x11),
  906. (uint8) (hex [1] * 0x11),
  907. (uint8) (hex [2] * 0x11));
  908. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  909. (uint8) ((hex [2] << 4) + hex [3]),
  910. (uint8) ((hex [4] << 4) + hex [5]));
  911. }
  912. if (s [index] == 'r'
  913. && s [index + 1] == 'g'
  914. && s [index + 2] == 'b')
  915. {
  916. const int openBracket = s.indexOfChar (index, '(');
  917. const int closeBracket = s.indexOfChar (openBracket, ')');
  918. if (openBracket >= 3 && closeBracket > openBracket)
  919. {
  920. index = closeBracket;
  921. StringArray tokens;
  922. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  923. tokens.trim();
  924. tokens.removeEmptyStrings();
  925. if (tokens[0].containsChar ('%'))
  926. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  927. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  928. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  929. else
  930. return Colour ((uint8) tokens[0].getIntValue(),
  931. (uint8) tokens[1].getIntValue(),
  932. (uint8) tokens[2].getIntValue());
  933. }
  934. }
  935. return Colours::findColourForName (s, defaultColour);
  936. }
  937. static AffineTransform parseTransform (String t)
  938. {
  939. AffineTransform result;
  940. while (t.isNotEmpty())
  941. {
  942. StringArray tokens;
  943. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  944. .upToFirstOccurrenceOf (")", false, false),
  945. ", ", "");
  946. tokens.removeEmptyStrings (true);
  947. float numbers[6];
  948. for (int i = 0; i < numElementsInArray (numbers); ++i)
  949. numbers[i] = tokens[i].getFloatValue();
  950. AffineTransform trans;
  951. if (t.startsWithIgnoreCase ("matrix"))
  952. {
  953. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  954. numbers[1], numbers[3], numbers[5]);
  955. }
  956. else if (t.startsWithIgnoreCase ("translate"))
  957. {
  958. trans = AffineTransform::translation (numbers[0], numbers[1]);
  959. }
  960. else if (t.startsWithIgnoreCase ("scale"))
  961. {
  962. trans = AffineTransform::scale (numbers[0], numbers[tokens.size() > 1 ? 1 : 0]);
  963. }
  964. else if (t.startsWithIgnoreCase ("rotate"))
  965. {
  966. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi), numbers[1], numbers[2]);
  967. }
  968. else if (t.startsWithIgnoreCase ("skewX"))
  969. {
  970. trans = AffineTransform::shear (std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f);
  971. }
  972. else if (t.startsWithIgnoreCase ("skewY"))
  973. {
  974. trans = AffineTransform::shear (0.0f, std::tan (numbers[0] * (float_Pi / 180.0f)));
  975. }
  976. result = trans.followedBy (result);
  977. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  978. }
  979. return result;
  980. }
  981. static void endpointToCentreParameters (const double x1, const double y1,
  982. const double x2, const double y2,
  983. const double angle,
  984. const bool largeArc, const bool sweep,
  985. double& rx, double& ry,
  986. double& centreX, double& centreY,
  987. double& startAngle, double& deltaAngle) noexcept
  988. {
  989. const double midX = (x1 - x2) * 0.5;
  990. const double midY = (y1 - y2) * 0.5;
  991. const double cosAngle = std::cos (angle);
  992. const double sinAngle = std::sin (angle);
  993. const double xp = cosAngle * midX + sinAngle * midY;
  994. const double yp = cosAngle * midY - sinAngle * midX;
  995. const double xp2 = xp * xp;
  996. const double yp2 = yp * yp;
  997. double rx2 = rx * rx;
  998. double ry2 = ry * ry;
  999. const double s = (xp2 / rx2) + (yp2 / ry2);
  1000. double c;
  1001. if (s <= 1.0)
  1002. {
  1003. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  1004. / (( rx2 * yp2) + (ry2 * xp2))));
  1005. if (largeArc == sweep)
  1006. c = -c;
  1007. }
  1008. else
  1009. {
  1010. const double s2 = std::sqrt (s);
  1011. rx *= s2;
  1012. ry *= s2;
  1013. c = 0;
  1014. }
  1015. const double cpx = ((rx * yp) / ry) * c;
  1016. const double cpy = ((-ry * xp) / rx) * c;
  1017. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  1018. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  1019. const double ux = (xp - cpx) / rx;
  1020. const double uy = (yp - cpy) / ry;
  1021. const double vx = (-xp - cpx) / rx;
  1022. const double vy = (-yp - cpy) / ry;
  1023. const double length = juce_hypot (ux, uy);
  1024. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  1025. if (uy < 0)
  1026. startAngle = -startAngle;
  1027. startAngle += double_Pi * 0.5;
  1028. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  1029. / (length * juce_hypot (vx, vy))));
  1030. if ((ux * vy) - (uy * vx) < 0)
  1031. deltaAngle = -deltaAngle;
  1032. if (sweep)
  1033. {
  1034. if (deltaAngle < 0)
  1035. deltaAngle += double_Pi * 2.0;
  1036. }
  1037. else
  1038. {
  1039. if (deltaAngle > 0)
  1040. deltaAngle -= double_Pi * 2.0;
  1041. }
  1042. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  1043. }
  1044. template <typename OperationType>
  1045. static bool findElementForId (const XmlPath& parent, const String& id, OperationType& op)
  1046. {
  1047. forEachXmlChildElement (*parent, e)
  1048. {
  1049. if (e->compareAttribute ("id", id))
  1050. {
  1051. op (parent.getChild (e));
  1052. return true;
  1053. }
  1054. if (findElementForId (parent.getChild (e), id, op))
  1055. return true;
  1056. }
  1057. return false;
  1058. }
  1059. SVGState& operator= (const SVGState&) JUCE_DELETED_FUNCTION;
  1060. };
  1061. //==============================================================================
  1062. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  1063. {
  1064. SVGState state (&svgDocument);
  1065. return state.parseSVGElement (SVGState::XmlPath (&svgDocument, nullptr));
  1066. }
  1067. Path Drawable::parseSVGPath (const String& svgPath)
  1068. {
  1069. SVGState state (nullptr);
  1070. Path p;
  1071. state.parsePathString (p, svgPath);
  1072. return p;
  1073. }