HTMLImageElement.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, weak_element = make_weak_ptr()](auto data) {
  23. if (!weak_element) {
  24. dbg() << "HTMLImageElement: Load completed after element destroyed.";
  25. return;
  26. }
  27. if (data.is_null()) {
  28. dbg() << "HTMLImageElement: Failed to load " << this->src();
  29. return;
  30. }
  31. m_image_data = data;
  32. m_image_loader = ImageDecoder::create(m_image_data.data(), m_image_data.size());
  33. document().update_layout();
  34. });
  35. }
  36. int HTMLImageElement::preferred_width() const
  37. {
  38. bool ok = false;
  39. int width = attribute("width").to_int(ok);
  40. if (ok)
  41. return width;
  42. if (m_image_loader)
  43. return m_image_loader->width();
  44. return 0;
  45. }
  46. int HTMLImageElement::preferred_height() const
  47. {
  48. bool ok = false;
  49. int height = attribute("height").to_int(ok);
  50. if (ok)
  51. return height;
  52. if (m_image_loader)
  53. return m_image_loader->height();
  54. return 0;
  55. }
  56. RefPtr<LayoutNode> HTMLImageElement::create_layout_node(const StyleProperties* parent_style) const
  57. {
  58. auto style = document().style_resolver().resolve_style(*this, parent_style);
  59. auto display = style->string_or_fallback(CSS::PropertyID::Display, "inline");
  60. if (display == "none")
  61. return nullptr;
  62. return adopt(*new LayoutImage(*this, move(style)));
  63. }
  64. const GraphicsBitmap* HTMLImageElement::bitmap() const
  65. {
  66. if (!m_image_loader)
  67. return nullptr;
  68. return m_image_loader->bitmap();
  69. }