SVGPathElement.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <matthewcolsson@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Debug.h>
  27. #include <AK/StringBuilder.h>
  28. #include <LibGfx/Painter.h>
  29. #include <LibGfx/Path.h>
  30. #include <LibWeb/DOM/Document.h>
  31. #include <LibWeb/DOM/Event.h>
  32. #include <LibWeb/Layout/SVGPathBox.h>
  33. #include <LibWeb/SVG/SVGPathElement.h>
  34. #include <ctype.h>
  35. namespace Web::SVG {
  36. static void print_instruction(const PathInstruction& instruction)
  37. {
  38. VERIFY(PATH_DEBUG);
  39. auto& data = instruction.data;
  40. switch (instruction.type) {
  41. case PathInstructionType::Move:
  42. dbgln("Move (absolute={})", instruction.absolute);
  43. for (size_t i = 0; i < data.size(); i += 2)
  44. dbgln(" x={}, y={}", data[i], data[i + 1]);
  45. break;
  46. case PathInstructionType::ClosePath:
  47. dbgln("ClosePath (absolute={})", instruction.absolute);
  48. break;
  49. case PathInstructionType::Line:
  50. dbgln("Line (absolute={})", instruction.absolute);
  51. for (size_t i = 0; i < data.size(); i += 2)
  52. dbgln(" x={}, y={}", data[i], data[i + 1]);
  53. break;
  54. case PathInstructionType::HorizontalLine:
  55. dbgln("HorizontalLine (absolute={})", instruction.absolute);
  56. for (size_t i = 0; i < data.size(); ++i)
  57. dbgln(" x={}", data[i]);
  58. break;
  59. case PathInstructionType::VerticalLine:
  60. dbgln("VerticalLine (absolute={})", instruction.absolute);
  61. for (size_t i = 0; i < data.size(); ++i)
  62. dbgln(" y={}", data[i]);
  63. break;
  64. case PathInstructionType::Curve:
  65. dbgln("Curve (absolute={})", instruction.absolute);
  66. for (size_t i = 0; i < data.size(); i += 6)
  67. dbgln(" (x1={}, y1={}, x2={}, y2={}), (x={}, y={})", data[i], data[i + 1], data[i + 2], data[i + 3], data[i + 4], data[i + 5]);
  68. break;
  69. case PathInstructionType::SmoothCurve:
  70. dbgln("SmoothCurve (absolute={})", instruction.absolute);
  71. for (size_t i = 0; i < data.size(); i += 4)
  72. dbgln(" (x2={}, y2={}), (x={}, y={})", data[i], data[i + 1], data[i + 2], data[i + 3]);
  73. break;
  74. case PathInstructionType::QuadraticBezierCurve:
  75. dbgln("QuadraticBezierCurve (absolute={})", instruction.absolute);
  76. for (size_t i = 0; i < data.size(); i += 4)
  77. dbgln(" (x1={}, y1={}), (x={}, y={})", data[i], data[i + 1], data[i + 2], data[i + 3]);
  78. break;
  79. case PathInstructionType::SmoothQuadraticBezierCurve:
  80. dbgln("SmoothQuadraticBezierCurve (absolute={})", instruction.absolute);
  81. for (size_t i = 0; i < data.size(); i += 2)
  82. dbgln(" x={}, y={}", data[i], data[i + 1]);
  83. break;
  84. case PathInstructionType::EllipticalArc:
  85. dbgln("EllipticalArc (absolute={})", instruction.absolute);
  86. for (size_t i = 0; i < data.size(); i += 7)
  87. dbgln(" (rx={}, ry={}) x-axis-rotation={}, large-arc-flag={}, sweep-flag={}, (x={}, y={})",
  88. data[i],
  89. data[i + 1],
  90. data[i + 2],
  91. data[i + 3],
  92. data[i + 4],
  93. data[i + 5],
  94. data[i + 6]);
  95. break;
  96. case PathInstructionType::Invalid:
  97. dbgln("Invalid");
  98. break;
  99. }
  100. }
  101. PathDataParser::PathDataParser(const String& source)
  102. : m_source(source)
  103. {
  104. }
  105. Vector<PathInstruction> PathDataParser::parse()
  106. {
  107. parse_whitespace();
  108. while (!done())
  109. parse_drawto();
  110. if (!m_instructions.is_empty() && m_instructions[0].type != PathInstructionType::Move)
  111. VERIFY_NOT_REACHED();
  112. return m_instructions;
  113. }
  114. void PathDataParser::parse_drawto()
  115. {
  116. if (match('M') || match('m')) {
  117. parse_moveto();
  118. } else if (match('Z') || match('z')) {
  119. parse_closepath();
  120. } else if (match('L') || match('l')) {
  121. parse_lineto();
  122. } else if (match('H') || match('h')) {
  123. parse_horizontal_lineto();
  124. } else if (match('V') || match('v')) {
  125. parse_vertical_lineto();
  126. } else if (match('C') || match('c')) {
  127. parse_curveto();
  128. } else if (match('S') || match('s')) {
  129. parse_smooth_curveto();
  130. } else if (match('Q') || match('q')) {
  131. parse_quadratic_bezier_curveto();
  132. } else if (match('T') || match('t')) {
  133. parse_smooth_quadratic_bezier_curveto();
  134. } else if (match('A') || match('a')) {
  135. parse_elliptical_arc();
  136. } else {
  137. dbgln("PathDataParser::parse_drawto failed to match: '{}'", ch());
  138. TODO();
  139. }
  140. }
  141. void PathDataParser::parse_moveto()
  142. {
  143. bool absolute = consume() == 'M';
  144. parse_whitespace();
  145. for (auto& pair : parse_coordinate_pair_sequence())
  146. m_instructions.append({ PathInstructionType::Move, absolute, pair });
  147. }
  148. void PathDataParser::parse_closepath()
  149. {
  150. bool absolute = consume() == 'Z';
  151. parse_whitespace();
  152. m_instructions.append({ PathInstructionType::ClosePath, absolute, {} });
  153. }
  154. void PathDataParser::parse_lineto()
  155. {
  156. bool absolute = consume() == 'L';
  157. parse_whitespace();
  158. for (auto& pair : parse_coordinate_pair_sequence())
  159. m_instructions.append({ PathInstructionType::Line, absolute, pair });
  160. }
  161. void PathDataParser::parse_horizontal_lineto()
  162. {
  163. bool absolute = consume() == 'H';
  164. parse_whitespace();
  165. m_instructions.append({ PathInstructionType::HorizontalLine, absolute, parse_coordinate_sequence() });
  166. }
  167. void PathDataParser::parse_vertical_lineto()
  168. {
  169. bool absolute = consume() == 'V';
  170. parse_whitespace();
  171. m_instructions.append({ PathInstructionType::VerticalLine, absolute, parse_coordinate_sequence() });
  172. }
  173. void PathDataParser::parse_curveto()
  174. {
  175. bool absolute = consume() == 'C';
  176. parse_whitespace();
  177. while (true) {
  178. m_instructions.append({ PathInstructionType::Curve, absolute, parse_coordinate_pair_triplet() });
  179. if (match_comma_whitespace())
  180. parse_comma_whitespace();
  181. if (!match_coordinate())
  182. break;
  183. }
  184. }
  185. void PathDataParser::parse_smooth_curveto()
  186. {
  187. bool absolute = consume() == 'S';
  188. parse_whitespace();
  189. while (true) {
  190. m_instructions.append({ PathInstructionType::SmoothCurve, absolute, parse_coordinate_pair_double() });
  191. if (match_comma_whitespace())
  192. parse_comma_whitespace();
  193. if (!match_coordinate())
  194. break;
  195. }
  196. }
  197. void PathDataParser::parse_quadratic_bezier_curveto()
  198. {
  199. bool absolute = consume() == 'Q';
  200. parse_whitespace();
  201. while (true) {
  202. m_instructions.append({ PathInstructionType::QuadraticBezierCurve, absolute, parse_coordinate_pair_double() });
  203. if (match_comma_whitespace())
  204. parse_comma_whitespace();
  205. if (!match_coordinate())
  206. break;
  207. }
  208. }
  209. void PathDataParser::parse_smooth_quadratic_bezier_curveto()
  210. {
  211. bool absolute = consume() == 'T';
  212. parse_whitespace();
  213. while (true) {
  214. m_instructions.append({ PathInstructionType::SmoothQuadraticBezierCurve, absolute, parse_coordinate_pair() });
  215. if (match_comma_whitespace())
  216. parse_comma_whitespace();
  217. if (!match_coordinate())
  218. break;
  219. }
  220. }
  221. void PathDataParser::parse_elliptical_arc()
  222. {
  223. bool absolute = consume() == 'A';
  224. parse_whitespace();
  225. while (true) {
  226. m_instructions.append({ PathInstructionType::EllipticalArc, absolute, parse_elliptical_arg_argument() });
  227. if (match_comma_whitespace())
  228. parse_comma_whitespace();
  229. if (!match_coordinate())
  230. break;
  231. }
  232. }
  233. float PathDataParser::parse_coordinate()
  234. {
  235. return parse_sign() * parse_number();
  236. }
  237. Vector<float> PathDataParser::parse_coordinate_pair()
  238. {
  239. Vector<float> coordinates;
  240. coordinates.append(parse_coordinate());
  241. if (match_comma_whitespace())
  242. parse_comma_whitespace();
  243. coordinates.append(parse_coordinate());
  244. return coordinates;
  245. }
  246. Vector<float> PathDataParser::parse_coordinate_sequence()
  247. {
  248. Vector<float> sequence;
  249. while (true) {
  250. sequence.append(parse_coordinate());
  251. if (match_comma_whitespace())
  252. parse_comma_whitespace();
  253. if (!match_comma_whitespace() && !match_coordinate())
  254. break;
  255. }
  256. return sequence;
  257. }
  258. Vector<Vector<float>> PathDataParser::parse_coordinate_pair_sequence()
  259. {
  260. Vector<Vector<float>> sequence;
  261. while (true) {
  262. sequence.append(parse_coordinate_pair());
  263. if (match_comma_whitespace())
  264. parse_comma_whitespace();
  265. if (!match_comma_whitespace() && !match_coordinate())
  266. break;
  267. }
  268. return sequence;
  269. }
  270. Vector<float> PathDataParser::parse_coordinate_pair_double()
  271. {
  272. Vector<float> coordinates;
  273. coordinates.append(parse_coordinate_pair());
  274. if (match_comma_whitespace())
  275. parse_comma_whitespace();
  276. coordinates.append(parse_coordinate_pair());
  277. return coordinates;
  278. }
  279. Vector<float> PathDataParser::parse_coordinate_pair_triplet()
  280. {
  281. Vector<float> coordinates;
  282. coordinates.append(parse_coordinate_pair());
  283. if (match_comma_whitespace())
  284. parse_comma_whitespace();
  285. coordinates.append(parse_coordinate_pair());
  286. if (match_comma_whitespace())
  287. parse_comma_whitespace();
  288. coordinates.append(parse_coordinate_pair());
  289. return coordinates;
  290. }
  291. Vector<float> PathDataParser::parse_elliptical_arg_argument()
  292. {
  293. Vector<float> numbers;
  294. numbers.append(parse_number());
  295. if (match_comma_whitespace())
  296. parse_comma_whitespace();
  297. numbers.append(parse_number());
  298. if (match_comma_whitespace())
  299. parse_comma_whitespace();
  300. numbers.append(parse_number());
  301. parse_comma_whitespace();
  302. numbers.append(parse_flag());
  303. if (match_comma_whitespace())
  304. parse_comma_whitespace();
  305. numbers.append(parse_flag());
  306. if (match_comma_whitespace())
  307. parse_comma_whitespace();
  308. numbers.append(parse_coordinate_pair());
  309. return numbers;
  310. }
  311. void PathDataParser::parse_whitespace(bool must_match_once)
  312. {
  313. bool matched = false;
  314. while (!done() && match_whitespace()) {
  315. consume();
  316. matched = true;
  317. }
  318. VERIFY(!must_match_once || matched);
  319. }
  320. void PathDataParser::parse_comma_whitespace()
  321. {
  322. if (match(',')) {
  323. consume();
  324. parse_whitespace();
  325. } else {
  326. parse_whitespace(1);
  327. if (match(','))
  328. consume();
  329. parse_whitespace();
  330. }
  331. }
  332. float PathDataParser::parse_fractional_constant()
  333. {
  334. StringBuilder builder;
  335. bool floating_point = false;
  336. while (!done() && isdigit(ch()))
  337. builder.append(consume());
  338. if (match('.')) {
  339. floating_point = true;
  340. builder.append('.');
  341. consume();
  342. while (!done() && isdigit(ch()))
  343. builder.append(consume());
  344. } else {
  345. VERIFY(builder.length() > 0);
  346. }
  347. if (floating_point)
  348. return strtof(builder.to_string().characters(), nullptr);
  349. return builder.to_string().to_int().value();
  350. }
  351. float PathDataParser::parse_number()
  352. {
  353. auto number = parse_fractional_constant();
  354. if (match('e') || match('E'))
  355. TODO();
  356. return number;
  357. }
  358. float PathDataParser::parse_flag()
  359. {
  360. if (!match('0') && !match('1'))
  361. VERIFY_NOT_REACHED();
  362. return consume() - '0';
  363. }
  364. int PathDataParser::parse_sign()
  365. {
  366. if (match('-')) {
  367. consume();
  368. return -1;
  369. }
  370. if (match('+'))
  371. consume();
  372. return 1;
  373. }
  374. bool PathDataParser::match_whitespace() const
  375. {
  376. if (done())
  377. return false;
  378. char c = ch();
  379. return c == 0x9 || c == 0x20 || c == 0xa || c == 0xc || c == 0xd;
  380. }
  381. bool PathDataParser::match_comma_whitespace() const
  382. {
  383. return match_whitespace() || match(',');
  384. }
  385. bool PathDataParser::match_coordinate() const
  386. {
  387. return !done() && (isdigit(ch()) || ch() == '-' || ch() == '+' || ch() == '.');
  388. }
  389. SVGPathElement::SVGPathElement(DOM::Document& document, QualifiedName qualified_name)
  390. : SVGGeometryElement(document, move(qualified_name))
  391. {
  392. }
  393. RefPtr<Layout::Node> SVGPathElement::create_layout_node()
  394. {
  395. auto style = document().style_resolver().resolve_style(*this);
  396. if (style->display() == CSS::Display::None)
  397. return nullptr;
  398. return adopt(*new Layout::SVGPathBox(document(), *this, move(style)));
  399. }
  400. void SVGPathElement::parse_attribute(const FlyString& name, const String& value)
  401. {
  402. SVGGeometryElement::parse_attribute(name, value);
  403. if (name == "d")
  404. m_instructions = PathDataParser(value).parse();
  405. }
  406. Gfx::Path& SVGPathElement::get_path()
  407. {
  408. if (m_path.has_value())
  409. return m_path.value();
  410. Gfx::Path path;
  411. for (auto& instruction : m_instructions) {
  412. auto& absolute = instruction.absolute;
  413. auto& data = instruction.data;
  414. if constexpr (PATH_DEBUG) {
  415. print_instruction(instruction);
  416. }
  417. bool clear_last_control_point = true;
  418. switch (instruction.type) {
  419. case PathInstructionType::Move: {
  420. Gfx::FloatPoint point = { data[0], data[1] };
  421. if (absolute) {
  422. path.move_to(point);
  423. } else {
  424. VERIFY(!path.segments().is_empty());
  425. path.move_to(point + path.segments().last().point());
  426. }
  427. break;
  428. }
  429. case PathInstructionType::ClosePath:
  430. path.close();
  431. break;
  432. case PathInstructionType::Line: {
  433. Gfx::FloatPoint point = { data[0], data[1] };
  434. if (absolute) {
  435. path.line_to(point);
  436. } else {
  437. VERIFY(!path.segments().is_empty());
  438. path.line_to(point + path.segments().last().point());
  439. }
  440. break;
  441. }
  442. case PathInstructionType::HorizontalLine: {
  443. VERIFY(!path.segments().is_empty());
  444. auto last_point = path.segments().last().point();
  445. if (absolute) {
  446. path.line_to(Gfx::FloatPoint { data[0], last_point.y() });
  447. } else {
  448. path.line_to(Gfx::FloatPoint { data[0] + last_point.x(), last_point.y() });
  449. }
  450. break;
  451. }
  452. case PathInstructionType::VerticalLine: {
  453. VERIFY(!path.segments().is_empty());
  454. auto last_point = path.segments().last().point();
  455. if (absolute) {
  456. path.line_to(Gfx::FloatPoint { last_point.x(), data[0] });
  457. } else {
  458. path.line_to(Gfx::FloatPoint { last_point.x(), data[0] + last_point.y() });
  459. }
  460. break;
  461. }
  462. case PathInstructionType::EllipticalArc: {
  463. double rx = data[0];
  464. double ry = data[1];
  465. double x_axis_rotation = double { data[2] } * M_DEG2RAD;
  466. double large_arc_flag = data[3];
  467. double sweep_flag = data[4];
  468. auto& last_point = path.segments().last().point();
  469. Gfx::FloatPoint next_point;
  470. if (absolute) {
  471. next_point = { data[5], data[6] };
  472. } else {
  473. next_point = { data[5] + last_point.x(), data[6] + last_point.y() };
  474. }
  475. path.elliptical_arc_to(next_point, { rx, ry }, x_axis_rotation, large_arc_flag != 0, sweep_flag != 0);
  476. break;
  477. }
  478. case PathInstructionType::QuadraticBezierCurve: {
  479. clear_last_control_point = false;
  480. Gfx::FloatPoint through = { data[0], data[1] };
  481. Gfx::FloatPoint point = { data[2], data[3] };
  482. if (absolute) {
  483. path.quadratic_bezier_curve_to(through, point);
  484. m_previous_control_point = through;
  485. } else {
  486. VERIFY(!path.segments().is_empty());
  487. auto last_point = path.segments().last().point();
  488. auto control_point = through + last_point;
  489. path.quadratic_bezier_curve_to(control_point, point + last_point);
  490. m_previous_control_point = control_point;
  491. }
  492. break;
  493. }
  494. case PathInstructionType::SmoothQuadraticBezierCurve: {
  495. clear_last_control_point = false;
  496. VERIFY(!path.segments().is_empty());
  497. auto last_point = path.segments().last().point();
  498. if (m_previous_control_point.is_null()) {
  499. m_previous_control_point = last_point;
  500. }
  501. auto dx_end_control = last_point.dx_relative_to(m_previous_control_point);
  502. auto dy_end_control = last_point.dy_relative_to(m_previous_control_point);
  503. auto control_point = Gfx::FloatPoint { last_point.x() + dx_end_control, last_point.y() + dy_end_control };
  504. Gfx::FloatPoint end_point = { data[0], data[1] };
  505. if (absolute) {
  506. path.quadratic_bezier_curve_to(control_point, end_point);
  507. } else {
  508. path.quadratic_bezier_curve_to(control_point, end_point + last_point);
  509. }
  510. m_previous_control_point = control_point;
  511. break;
  512. }
  513. case PathInstructionType::Curve:
  514. case PathInstructionType::SmoothCurve:
  515. // Instead of crashing the browser every time we come across an SVG
  516. // with these path instructions, let's just skip them
  517. continue;
  518. case PathInstructionType::Invalid:
  519. VERIFY_NOT_REACHED();
  520. }
  521. if (clear_last_control_point) {
  522. m_previous_control_point = Gfx::FloatPoint {};
  523. }
  524. }
  525. m_path = path;
  526. return m_path.value();
  527. }
  528. }