HTMLImageElement.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGfx/Bitmap.h>
  7. #include <LibWeb/CSS/Parser/Parser.h>
  8. #include <LibWeb/CSS/StyleResolver.h>
  9. #include <LibWeb/DOM/Document.h>
  10. #include <LibWeb/DOM/Event.h>
  11. #include <LibWeb/HTML/EventNames.h>
  12. #include <LibWeb/HTML/HTMLImageElement.h>
  13. #include <LibWeb/Layout/ImageBox.h>
  14. #include <LibWeb/Loader/ResourceLoader.h>
  15. namespace Web::HTML {
  16. HTMLImageElement::HTMLImageElement(DOM::Document& document, QualifiedName qualified_name)
  17. : HTMLElement(document, move(qualified_name))
  18. , m_image_loader(*this)
  19. {
  20. m_image_loader.on_load = [this] {
  21. this->document().update_layout();
  22. dispatch_event(DOM::Event::create(EventNames::load));
  23. };
  24. m_image_loader.on_fail = [this] {
  25. dbgln("HTMLImageElement: Resource did fail: {}", src());
  26. this->document().update_layout();
  27. dispatch_event(DOM::Event::create(EventNames::error));
  28. };
  29. m_image_loader.on_animate = [this] {
  30. if (layout_node())
  31. layout_node()->set_needs_display();
  32. };
  33. }
  34. HTMLImageElement::~HTMLImageElement()
  35. {
  36. }
  37. void HTMLImageElement::apply_presentational_hints(CSS::StyleProperties& style) const
  38. {
  39. for_each_attribute([&](auto& name, auto& value) {
  40. if (name == HTML::AttributeNames::width) {
  41. if (auto parsed_value = parse_html_length(document(), value)) {
  42. style.set_property(CSS::PropertyID::Width, parsed_value.release_nonnull());
  43. }
  44. } else if (name == HTML::AttributeNames::height) {
  45. if (auto parsed_value = parse_html_length(document(), value)) {
  46. style.set_property(CSS::PropertyID::Height, parsed_value.release_nonnull());
  47. }
  48. }
  49. });
  50. }
  51. void HTMLImageElement::parse_attribute(const FlyString& name, const String& value)
  52. {
  53. HTMLElement::parse_attribute(name, value);
  54. if (name == HTML::AttributeNames::src && !value.is_empty())
  55. m_image_loader.load(document().complete_url(value));
  56. }
  57. RefPtr<Layout::Node> HTMLImageElement::create_layout_node()
  58. {
  59. auto style = document().style_resolver().resolve_style(*this);
  60. if (style->display() == CSS::Display::None)
  61. return nullptr;
  62. return adopt_ref(*new Layout::ImageBox(document(), *this, move(style), m_image_loader));
  63. }
  64. const Gfx::Bitmap* HTMLImageElement::bitmap() const
  65. {
  66. return m_image_loader.bitmap(m_image_loader.current_frame_index());
  67. }
  68. }