ImageBox.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. auto bitmap = m_image_provider.current_image_bitmap();
  22. if (!bitmap) {
  23. set_intrinsic_width(0);
  24. set_intrinsic_height(0);
  25. } else {
  26. auto width = bitmap->width();
  27. auto height = bitmap->height();
  28. set_intrinsic_width(width);
  29. set_intrinsic_height(height);
  30. set_intrinsic_aspect_ratio(static_cast<float>(width) / static_cast<float>(height));
  31. }
  32. if (renders_as_alt_text()) {
  33. auto& image_element = verify_cast<HTML::HTMLImageElement>(dom_node());
  34. auto& font = Platform::FontPlugin::the().default_font();
  35. auto alt = image_element.alt();
  36. CSSPixels alt_text_width = 0;
  37. if (!m_cached_alt_text_width.has_value())
  38. m_cached_alt_text_width = font.width(alt);
  39. alt_text_width = m_cached_alt_text_width.value();
  40. set_intrinsic_width(alt_text_width + 16);
  41. set_intrinsic_height(font.pixel_size() + 16);
  42. }
  43. if (!has_intrinsic_width() && !has_intrinsic_height()) {
  44. // FIXME: Do something.
  45. }
  46. }
  47. void ImageBox::dom_node_did_update_alt_text(Badge<HTML::HTMLImageElement>)
  48. {
  49. m_cached_alt_text_width = {};
  50. }
  51. bool ImageBox::renders_as_alt_text() const
  52. {
  53. if (is<HTML::HTMLImageElement>(dom_node()))
  54. return !static_cast<HTML::HTMLImageElement const&>(dom_node()).current_request().is_available();
  55. return false;
  56. }
  57. JS::GCPtr<Painting::Paintable> ImageBox::create_paintable() const
  58. {
  59. return Painting::ImagePaintable::create(*this);
  60. }
  61. }