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.

1492 lines
52KB

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