ImageBox.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.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/HTML/ImageRequest.h>
  9. #include <LibWeb/Layout/ImageBox.h>
  10. #include <LibWeb/Layout/ImageProvider.h>
  11. #include <LibWeb/Painting/ImagePaintable.h>
  12. #include <LibWeb/Platform/FontPlugin.h>
  13. namespace Web::Layout {
  14. ImageBox::ImageBox(DOM::Document& document, DOM::Element& element, NonnullRefPtr<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& font = Platform::FontPlugin::the().default_font();
  33. auto alt = element.get_attribute_value(HTML::AttributeNames::alt);
  34. CSSPixels alt_text_width = 0;
  35. if (!m_cached_alt_text_width.has_value())
  36. m_cached_alt_text_width = CSSPixels::nearest_value_for(font.width(alt));
  37. alt_text_width = m_cached_alt_text_width.value();
  38. set_natural_width(alt_text_width + 16);
  39. set_natural_height(CSSPixels::nearest_value_for(font.pixel_size()) + 16);
  40. }
  41. if (!has_natural_width() && !has_natural_height()) {
  42. // FIXME: Do something.
  43. }
  44. }
  45. void ImageBox::dom_node_did_update_alt_text(Badge<ImageProvider>)
  46. {
  47. m_cached_alt_text_width = {};
  48. }
  49. bool ImageBox::renders_as_alt_text() const
  50. {
  51. if (auto const* image_provider = dynamic_cast<ImageProvider const*>(&dom_node()))
  52. return !image_provider->is_image_available();
  53. return false;
  54. }
  55. JS::GCPtr<Painting::Paintable> ImageBox::create_paintable() const
  56. {
  57. return Painting::ImagePaintable::create(*this);
  58. }
  59. }