LayoutImage.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <LibDraw/Font.h>
  2. #include <LibDraw/StylePainter.h>
  3. #include <LibGUI/GPainter.h>
  4. #include <LibHTML/Layout/LayoutImage.h>
  5. LayoutImage::LayoutImage(const HTMLImageElement& element, NonnullRefPtr<StyleProperties> style)
  6. : LayoutReplaced(element, move(style))
  7. {
  8. }
  9. LayoutImage::~LayoutImage()
  10. {
  11. }
  12. void LayoutImage::layout()
  13. {
  14. if (node().preferred_width() && node().preferred_height()) {
  15. rect().set_width(node().preferred_width());
  16. rect().set_height(node().preferred_height());
  17. } else if (renders_as_alt_text()) {
  18. auto& font = Font::default_font();
  19. auto alt = node().alt();
  20. if (alt.is_empty())
  21. alt = node().src();
  22. rect().set_width(font.width(alt) + 16);
  23. rect().set_height(font.glyph_height() + 16);
  24. } else {
  25. rect().set_width(16);
  26. rect().set_height(16);
  27. }
  28. LayoutReplaced::layout();
  29. }
  30. void LayoutImage::render(RenderingContext& context)
  31. {
  32. if (!is_visible())
  33. return;
  34. // FIXME: This should be done at a different level. Also rect() does not include padding etc!
  35. if (!context.viewport_rect().intersects(rect()))
  36. return;
  37. if (renders_as_alt_text()) {
  38. context.painter().set_font(Font::default_font());
  39. StylePainter::paint_frame(context.painter(), rect(), FrameShape::Container, FrameShadow::Sunken, 2);
  40. auto alt = node().alt();
  41. if (alt.is_empty())
  42. alt = node().src();
  43. context.painter().draw_text(rect(), alt, TextAlignment::Center, style().color_or_fallback(CSS::PropertyID::Color, document(), Color::Black), TextElision::Right);
  44. } else {
  45. context.painter().draw_scaled_bitmap(rect(), *node().bitmap(), node().bitmap()->rect());
  46. }
  47. LayoutReplaced::render(context);
  48. }
  49. bool LayoutImage::renders_as_alt_text() const
  50. {
  51. return !node().image_loader();
  52. }