SVGSVGElement.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <matthewcolsson@gmail.com>
  3. * Copyright (c) 2022, Andreas Kling <andreas@ladybird.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibWeb/Bindings/SVGSVGElementPrototype.h>
  8. #include <LibWeb/CSS/Parser/Parser.h>
  9. #include <LibWeb/CSS/StyleComputer.h>
  10. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  11. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  12. #include <LibWeb/DOM/Document.h>
  13. #include <LibWeb/DOM/Event.h>
  14. #include <LibWeb/DOM/StaticNodeList.h>
  15. #include <LibWeb/HTML/Parser/HTMLParser.h>
  16. #include <LibWeb/Layout/SVGSVGBox.h>
  17. #include <LibWeb/SVG/AttributeNames.h>
  18. #include <LibWeb/SVG/SVGAnimatedRect.h>
  19. #include <LibWeb/SVG/SVGSVGElement.h>
  20. #include <LibWeb/Selection/Selection.h>
  21. namespace Web::SVG {
  22. GC_DEFINE_ALLOCATOR(SVGSVGElement);
  23. SVGSVGElement::SVGSVGElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  24. : SVGGraphicsElement(document, qualified_name)
  25. {
  26. }
  27. void SVGSVGElement::initialize(JS::Realm& realm)
  28. {
  29. Base::initialize(realm);
  30. WEB_SET_PROTOTYPE_FOR_INTERFACE(SVGSVGElement);
  31. m_view_box_for_bindings = realm.create<SVGAnimatedRect>(realm);
  32. }
  33. void SVGSVGElement::visit_edges(Visitor& visitor)
  34. {
  35. Base::visit_edges(visitor);
  36. visitor.visit(m_view_box_for_bindings);
  37. }
  38. GC::Ptr<Layout::Node> SVGSVGElement::create_layout_node(CSS::StyleProperties style)
  39. {
  40. return heap().allocate<Layout::SVGSVGBox>(document(), *this, move(style));
  41. }
  42. RefPtr<CSS::CSSStyleValue> SVGSVGElement::width_style_value_from_attribute() const
  43. {
  44. auto parsing_context = CSS::Parser::ParsingContext { document(), CSS::Parser::ParsingContext::Mode::SVGPresentationAttribute };
  45. auto width_attribute = attribute(SVG::AttributeNames::width);
  46. if (auto width_value = parse_css_value(parsing_context, width_attribute.value_or(String {}), CSS::PropertyID::Width)) {
  47. return width_value.release_nonnull();
  48. }
  49. if (width_attribute == "") {
  50. // If the `width` attribute is an empty string, it defaults to 100%.
  51. // This matches WebKit and Blink, but not Firefox. The spec is unclear.
  52. // FIXME: Figure out what to do here.
  53. return CSS::PercentageStyleValue::create(CSS::Percentage { 100 });
  54. }
  55. return nullptr;
  56. }
  57. RefPtr<CSS::CSSStyleValue> SVGSVGElement::height_style_value_from_attribute() const
  58. {
  59. auto parsing_context = CSS::Parser::ParsingContext { document(), CSS::Parser::ParsingContext::Mode::SVGPresentationAttribute };
  60. auto height_attribute = attribute(SVG::AttributeNames::height);
  61. if (auto height_value = parse_css_value(parsing_context, height_attribute.value_or(String {}), CSS::PropertyID::Height)) {
  62. return height_value.release_nonnull();
  63. }
  64. if (height_attribute == "") {
  65. // If the `height` attribute is an empty string, it defaults to 100%.
  66. // This matches WebKit and Blink, but not Firefox. The spec is unclear.
  67. // FIXME: Figure out what to do here.
  68. return CSS::PercentageStyleValue::create(CSS::Percentage { 100 });
  69. }
  70. return nullptr;
  71. }
  72. void SVGSVGElement::apply_presentational_hints(CSS::StyleProperties& style) const
  73. {
  74. Base::apply_presentational_hints(style);
  75. auto parsing_context = CSS::Parser::ParsingContext { document(), CSS::Parser::ParsingContext::Mode::SVGPresentationAttribute };
  76. auto x_attribute = attribute(SVG::AttributeNames::x);
  77. if (auto x_value = parse_css_value(parsing_context, x_attribute.value_or(String {}), CSS::PropertyID::X)) {
  78. style.set_property(CSS::PropertyID::X, x_value.release_nonnull());
  79. }
  80. auto y_attribute = attribute(SVG::AttributeNames::y);
  81. if (auto y_value = parse_css_value(parsing_context, y_attribute.value_or(String {}), CSS::PropertyID::Y)) {
  82. style.set_property(CSS::PropertyID::Y, y_value.release_nonnull());
  83. }
  84. if (auto width = width_style_value_from_attribute())
  85. style.set_property(CSS::PropertyID::Width, width.release_nonnull());
  86. if (auto height = height_style_value_from_attribute())
  87. style.set_property(CSS::PropertyID::Height, height.release_nonnull());
  88. }
  89. void SVGSVGElement::attribute_changed(FlyString const& name, Optional<String> const& old_value, Optional<String> const& value, Optional<FlyString> const& namespace_)
  90. {
  91. Base::attribute_changed(name, old_value, value, namespace_);
  92. if (name.equals_ignoring_ascii_case(SVG::AttributeNames::viewBox)) {
  93. if (!value.has_value()) {
  94. m_view_box_for_bindings->set_nulled(true);
  95. } else {
  96. m_view_box = try_parse_view_box(value.value_or(String {}));
  97. m_view_box_for_bindings->set_nulled(!m_view_box.has_value());
  98. if (m_view_box.has_value()) {
  99. m_view_box_for_bindings->set_base_val(Gfx::DoubleRect { m_view_box->min_x, m_view_box->min_y, m_view_box->width, m_view_box->height });
  100. m_view_box_for_bindings->set_anim_val(Gfx::DoubleRect { m_view_box->min_x, m_view_box->min_y, m_view_box->width, m_view_box->height });
  101. }
  102. }
  103. }
  104. if (name.equals_ignoring_ascii_case(SVG::AttributeNames::preserveAspectRatio))
  105. m_preserve_aspect_ratio = AttributeParser::parse_preserve_aspect_ratio(value.value_or(String {}));
  106. if (name.equals_ignoring_ascii_case(SVG::AttributeNames::width) || name.equals_ignoring_ascii_case(SVG::AttributeNames::height))
  107. update_fallback_view_box_for_svg_as_image();
  108. }
  109. void SVGSVGElement::update_fallback_view_box_for_svg_as_image()
  110. {
  111. // AD-HOC: This creates a fallback viewBox for SVGs used as images.
  112. // If the <svg> element has width and height, but no viewBox,
  113. // we fall back to a synthetic viewBox="0 0 width height".
  114. Optional<double> width;
  115. Optional<double> height;
  116. auto width_attribute = get_attribute_value(SVG::AttributeNames::width);
  117. auto parsing_context = CSS::Parser::ParsingContext { document() };
  118. if (auto width_value = parse_css_value(parsing_context, width_attribute, CSS::PropertyID::Width)) {
  119. if (width_value->is_length() && width_value->as_length().length().is_absolute())
  120. width = width_value->as_length().length().absolute_length_to_px().to_double();
  121. }
  122. auto height_attribute = get_attribute_value(SVG::AttributeNames::height);
  123. if (auto height_value = parse_css_value(parsing_context, height_attribute, CSS::PropertyID::Height)) {
  124. if (height_value->is_length() && height_value->as_length().length().is_absolute())
  125. height = height_value->as_length().length().absolute_length_to_px().to_double();
  126. }
  127. if (width.has_value() && width.value() > 0 && height.has_value() && height.value() > 0) {
  128. m_fallback_view_box_for_svg_as_image = ViewBox { 0, 0, width.value(), height.value() };
  129. } else {
  130. m_fallback_view_box_for_svg_as_image = {};
  131. }
  132. }
  133. void SVGSVGElement::set_fallback_view_box_for_svg_as_image(Optional<ViewBox> view_box)
  134. {
  135. m_fallback_view_box_for_svg_as_image = view_box;
  136. }
  137. Optional<ViewBox> SVGSVGElement::view_box() const
  138. {
  139. if (m_view_box.has_value())
  140. return m_view_box;
  141. // NOTE: If the parent is a document, we're an <svg> element used as an image.
  142. if (parent() && parent()->is_document() && m_fallback_view_box_for_svg_as_image.has_value())
  143. return m_fallback_view_box_for_svg_as_image;
  144. return {};
  145. }
  146. GC::Ref<SVGAnimatedLength> SVGSVGElement::x() const
  147. {
  148. return svg_animated_length_for_property(CSS::PropertyID::X);
  149. }
  150. GC::Ref<SVGAnimatedLength> SVGSVGElement::y() const
  151. {
  152. return svg_animated_length_for_property(CSS::PropertyID::Y);
  153. }
  154. GC::Ref<SVGAnimatedLength> SVGSVGElement::width() const
  155. {
  156. return svg_animated_length_for_property(CSS::PropertyID::Width);
  157. }
  158. GC::Ref<SVGAnimatedLength> SVGSVGElement::height() const
  159. {
  160. return svg_animated_length_for_property(CSS::PropertyID::Height);
  161. }
  162. float SVGSVGElement::current_scale() const
  163. {
  164. dbgln("(STUBBED) SVGSVGElement::current_scale(). Called on: {}", debug_description());
  165. return 1.0f;
  166. }
  167. void SVGSVGElement::set_current_scale(float)
  168. {
  169. dbgln("(STUBBED) SVGSVGElement::set_current_scale(). Called on: {}", debug_description());
  170. }
  171. GC::Ref<Geometry::DOMPointReadOnly> SVGSVGElement::current_translate() const
  172. {
  173. dbgln("(STUBBED) SVGSVGElement::current_translate(). Called on: {}", debug_description());
  174. return Geometry::DOMPointReadOnly::create(realm());
  175. }
  176. GC::Ref<DOM::NodeList> SVGSVGElement::get_intersection_list(GC::Ref<Geometry::DOMRectReadOnly>, GC::Ptr<SVGElement>) const
  177. {
  178. dbgln("(STUBBED) SVGSVGElement::get_intersection_list(). Called on: {}", debug_description());
  179. return DOM::StaticNodeList::create(realm(), {});
  180. }
  181. GC::Ref<DOM::NodeList> SVGSVGElement::get_enclosure_list(GC::Ref<Geometry::DOMRectReadOnly>, GC::Ptr<SVGElement>) const
  182. {
  183. dbgln("(STUBBED) SVGSVGElement::get_enclosure_list(). Called on: {}", debug_description());
  184. return DOM::StaticNodeList::create(realm(), {});
  185. }
  186. bool SVGSVGElement::check_intersection(GC::Ref<SVGElement>, GC::Ref<Geometry::DOMRectReadOnly>) const
  187. {
  188. dbgln("(STUBBED) SVGSVGElement::check_intersection(). Called on: {}", debug_description());
  189. return false;
  190. }
  191. bool SVGSVGElement::check_enclosure(GC::Ref<SVGElement>, GC::Ref<Geometry::DOMRectReadOnly>) const
  192. {
  193. dbgln("(STUBBED) SVGSVGElement::check_enclosure(). Called on: {}", debug_description());
  194. return false;
  195. }
  196. void SVGSVGElement::deselect_all() const
  197. {
  198. // This is equivalent to calling document.getSelection().removeAllRanges() on the document that this ‘svg’ element is in.
  199. if (auto selection = document().get_selection())
  200. selection->remove_all_ranges();
  201. }
  202. GC::Ref<SVGLength> SVGSVGElement::create_svg_length() const
  203. {
  204. // A new, detached SVGLength object whose value is the unitless <number> 0.
  205. return SVGLength::create(realm(), SVGLength::SVG_LENGTHTYPE_NUMBER, 0);
  206. }
  207. GC::Ref<Geometry::DOMPoint> SVGSVGElement::create_svg_point() const
  208. {
  209. // A new, detached DOMPoint object whose coordinates are all 0.
  210. return Geometry::DOMPoint::from_point(vm(), Geometry::DOMPointInit {});
  211. }
  212. GC::Ref<Geometry::DOMMatrix> SVGSVGElement::create_svg_matrix() const
  213. {
  214. // A new, detached DOMMatrix object representing the identity matrix.
  215. return Geometry::DOMMatrix::create(realm());
  216. }
  217. GC::Ref<Geometry::DOMRect> SVGSVGElement::create_svg_rect() const
  218. {
  219. // A new, DOMRect object whose x, y, width and height are all 0.
  220. return Geometry::DOMRect::construct_impl(realm(), 0, 0, 0, 0).release_value_but_fixme_should_propagate_errors();
  221. }
  222. GC::Ref<SVGTransform> SVGSVGElement::create_svg_transform() const
  223. {
  224. return SVGTransform::create(realm());
  225. }
  226. SVGSVGElement::NaturalMetrics SVGSVGElement::negotiate_natural_metrics(SVG::SVGSVGElement const& svg_root)
  227. {
  228. // https://www.w3.org/TR/SVG2/coords.html#SizingSVGInCSS
  229. NaturalMetrics natural_metrics;
  230. // The intrinsic dimensions must also be determined from the width and height sizing properties.
  231. // If either width or height are not specified, the used value is the initial value 'auto'.
  232. // 'auto' and percentage lengths must not be used to determine an intrinsic width or intrinsic height.
  233. if (auto width = svg_root.width_style_value_from_attribute(); width && width->is_length() && width->as_length().length().is_absolute()) {
  234. natural_metrics.width = width->as_length().length().absolute_length_to_px();
  235. }
  236. if (auto height = svg_root.height_style_value_from_attribute(); height && height->is_length() && height->as_length().length().is_absolute()) {
  237. natural_metrics.height = height->as_length().length().absolute_length_to_px();
  238. }
  239. // The intrinsic aspect ratio must be calculated using the following algorithm. If the algorithm returns null, then there is no intrinsic aspect ratio.
  240. natural_metrics.aspect_ratio = [&]() -> Optional<CSSPixelFraction> {
  241. // 1. If the width and height sizing properties on the ‘svg’ element are both absolute values:
  242. if (natural_metrics.width.has_value() && natural_metrics.height.has_value()) {
  243. if (natural_metrics.width != 0 && natural_metrics.height != 0) {
  244. // 1. return width / height
  245. return *natural_metrics.width / *natural_metrics.height;
  246. }
  247. return {};
  248. }
  249. // FIXME: 2. If an SVG View is active:
  250. // FIXME: 1. let viewbox be the viewbox defined by the active SVG View
  251. // FIXME: 2. return viewbox.width / viewbox.height
  252. // 3. If the ‘viewBox’ on the ‘svg’ element is correctly specified:
  253. if (svg_root.view_box().has_value()) {
  254. // 1. let viewbox be the viewbox defined by the ‘viewBox’ attribute on the ‘svg’ element
  255. auto const& viewbox = svg_root.view_box().value();
  256. // 2. return viewbox.width / viewbox.height
  257. auto viewbox_width = CSSPixels::nearest_value_for(viewbox.width);
  258. auto viewbox_height = CSSPixels::nearest_value_for(viewbox.height);
  259. if (viewbox_width != 0 && viewbox_height != 0)
  260. return viewbox_width / viewbox_height;
  261. return {};
  262. }
  263. // 4. return null
  264. return {};
  265. }();
  266. return natural_metrics;
  267. }
  268. }