HTMLImageElement.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <LibDraw/PNGLoader.h>
  2. #include <LibHTML/CSS/StyleResolver.h>
  3. #include <LibHTML/DOM/Document.h>
  4. #include <LibHTML/DOM/HTMLImageElement.h>
  5. #include <LibHTML/Layout/LayoutImage.h>
  6. #include <LibHTML/ResourceLoader.h>
  7. HTMLImageElement::HTMLImageElement(Document& document, const String& tag_name)
  8. : HTMLElement(document, tag_name)
  9. {
  10. }
  11. HTMLImageElement::~HTMLImageElement()
  12. {
  13. }
  14. void HTMLImageElement::parse_attribute(const String& name, const String& value)
  15. {
  16. if (name == "src")
  17. load_image(value);
  18. }
  19. void HTMLImageElement::load_image(const String& src)
  20. {
  21. URL src_url = document().complete_url(src);
  22. ResourceLoader::the().load(src_url, [this](auto data) {
  23. if (data.is_null()) {
  24. dbg() << "HTMLImageElement: Failed to load " << this->src();
  25. return;
  26. }
  27. m_bitmap = load_png_from_memory(data.data(), data.size());
  28. document().invalidate_layout();
  29. });
  30. }
  31. int HTMLImageElement::preferred_width() const
  32. {
  33. bool ok = false;
  34. int width = attribute("width").to_int(ok);
  35. if (ok)
  36. return width;
  37. if (m_bitmap)
  38. return m_bitmap->width();
  39. return 0;
  40. }
  41. int HTMLImageElement::preferred_height() const
  42. {
  43. bool ok = false;
  44. int height = attribute("height").to_int(ok);
  45. if (ok)
  46. return height;
  47. if (m_bitmap)
  48. return m_bitmap->height();
  49. return 0;
  50. }
  51. RefPtr<LayoutNode> HTMLImageElement::create_layout_node(const StyleResolver& resolver, const StyleProperties* parent_style) const
  52. {
  53. auto style = resolver.resolve_style(*this, parent_style);
  54. auto display_property = style->property(CSS::PropertyID::Display);
  55. String display = display_property.has_value() ? display_property.release_value()->to_string() : "inline";
  56. if (display == "none")
  57. return nullptr;
  58. return adopt(*new LayoutImage(*this, move(style)));
  59. }
  60. const GraphicsBitmap* HTMLImageElement::bitmap() const
  61. {
  62. return m_bitmap;
  63. }