ImageBox.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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/Painting/ImagePaintable.h>
  11. #include <LibWeb/Platform/FontPlugin.h>
  12. namespace Web::Layout {
  13. ImageBox::ImageBox(DOM::Document& document, DOM::Element& element, NonnullRefPtr<CSS::StyleProperties> style, ImageProvider const& image_provider)
  14. : ReplacedBox(document, element, move(style))
  15. , m_image_provider(image_provider)
  16. {
  17. }
  18. ImageBox::~ImageBox() = default;
  19. void ImageBox::prepare_for_replaced_layout()
  20. {
  21. set_natural_width(m_image_provider.intrinsic_width());
  22. set_natural_height(m_image_provider.intrinsic_height());
  23. set_natural_aspect_ratio(m_image_provider.intrinsic_aspect_ratio());
  24. if (renders_as_alt_text()) {
  25. auto& image_element = verify_cast<HTML::HTMLImageElement>(dom_node());
  26. auto& font = Platform::FontPlugin::the().default_font();
  27. auto alt = image_element.alt();
  28. CSSPixels alt_text_width = 0;
  29. if (!m_cached_alt_text_width.has_value())
  30. m_cached_alt_text_width = font.width(alt);
  31. alt_text_width = m_cached_alt_text_width.value();
  32. set_natural_width(alt_text_width + 16);
  33. set_natural_height(font.pixel_size() + 16);
  34. }
  35. if (!has_natural_width() && !has_natural_height()) {
  36. // FIXME: Do something.
  37. }
  38. }
  39. void ImageBox::dom_node_did_update_alt_text(Badge<HTML::HTMLImageElement>)
  40. {
  41. m_cached_alt_text_width = {};
  42. }
  43. bool ImageBox::renders_as_alt_text() const
  44. {
  45. if (is<HTML::HTMLImageElement>(dom_node()))
  46. return !static_cast<HTML::HTMLImageElement const&>(dom_node()).current_request().is_available();
  47. return false;
  48. }
  49. JS::GCPtr<Painting::Paintable> ImageBox::create_paintable() const
  50. {
  51. return Painting::ImagePaintable::create(*this);
  52. }
  53. }