ImageBox.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <andreas@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/HTML/BrowsingContext.h>
  7. #include <LibWeb/HTML/DecodedImageData.h>
  8. #include <LibWeb/Layout/ImageBox.h>
  9. #include <LibWeb/Layout/ImageProvider.h>
  10. #include <LibWeb/Painting/ImagePaintable.h>
  11. #include <LibWeb/Platform/FontPlugin.h>
  12. namespace Web::Layout {
  13. JS_DEFINE_ALLOCATOR(ImageBox);
  14. ImageBox::ImageBox(DOM::Document& document, DOM::Element& element, CSS::StyleProperties style, ImageProvider const& image_provider)
  15. : ReplacedBox(document, element, move(style))
  16. , m_image_provider(image_provider)
  17. {
  18. }
  19. ImageBox::~ImageBox() = default;
  20. void ImageBox::visit_edges(JS::Cell::Visitor& visitor)
  21. {
  22. Base::visit_edges(visitor);
  23. visitor.visit(m_image_provider.to_html_element());
  24. }
  25. void ImageBox::prepare_for_replaced_layout()
  26. {
  27. set_natural_width(m_image_provider.intrinsic_width());
  28. set_natural_height(m_image_provider.intrinsic_height());
  29. set_natural_aspect_ratio(m_image_provider.intrinsic_aspect_ratio());
  30. if (renders_as_alt_text()) {
  31. auto const& element = verify_cast<HTML::HTMLElement>(dom_node());
  32. auto alt = element.get_attribute_value(HTML::AttributeNames::alt);
  33. if (alt.is_empty()) {
  34. set_natural_width(0);
  35. set_natural_height(0);
  36. } else {
  37. auto const& font = Platform::FontPlugin::the().default_font();
  38. CSSPixels alt_text_width = 0;
  39. if (!m_cached_alt_text_width.has_value())
  40. m_cached_alt_text_width = CSSPixels::nearest_value_for(font.width(alt));
  41. alt_text_width = m_cached_alt_text_width.value();
  42. set_natural_width(alt_text_width + 16);
  43. set_natural_height(CSSPixels::nearest_value_for(font.pixel_size()) + 16);
  44. }
  45. }
  46. if (!has_natural_width() && !has_natural_height()) {
  47. // FIXME: Do something.
  48. }
  49. }
  50. void ImageBox::dom_node_did_update_alt_text(Badge<ImageProvider>)
  51. {
  52. m_cached_alt_text_width = {};
  53. }
  54. bool ImageBox::renders_as_alt_text() const
  55. {
  56. if (auto const* image_provider = dynamic_cast<ImageProvider const*>(&dom_node()))
  57. return !image_provider->is_image_available();
  58. return false;
  59. }
  60. JS::GCPtr<Painting::Paintable> ImageBox::create_paintable() const
  61. {
  62. return Painting::ImagePaintable::create(*this);
  63. }
  64. }