LayoutNode.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <LibGUI/GPainter.h>
  2. #include <LibHTML/DOM/Document.h>
  3. #include <LibHTML/DOM/Element.h>
  4. #include <LibHTML/Layout/LayoutBlock.h>
  5. #include <LibHTML/Layout/LayoutNode.h>
  6. //#define DRAW_BOXES_AROUND_LAYOUT_NODES
  7. //#define DRAW_BOXES_AROUND_HOVERED_NODES
  8. LayoutNode::LayoutNode(const Node* node, StyleProperties&& style_properties)
  9. : m_node(node)
  10. , m_style_properties(style_properties)
  11. {
  12. }
  13. LayoutNode::~LayoutNode()
  14. {
  15. }
  16. void LayoutNode::layout()
  17. {
  18. for_each_child([](auto& child) {
  19. child.layout();
  20. });
  21. }
  22. const LayoutBlock* LayoutNode::containing_block() const
  23. {
  24. for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  25. if (ancestor->is_block())
  26. return static_cast<const LayoutBlock*>(ancestor);
  27. }
  28. return nullptr;
  29. }
  30. void LayoutNode::render(RenderingContext& context)
  31. {
  32. #ifdef DRAW_BOXES_AROUND_LAYOUT_NODES
  33. context.painter().draw_rect(m_rect, Color::Blue);
  34. #endif
  35. #ifdef DRAW_BOXES_AROUND_HOVERED_NODES
  36. if (!is_anonymous() && node() == document().hovered_node())
  37. context.painter().draw_rect(m_rect, Color::Red);
  38. #endif
  39. auto bgcolor = style_properties().property("background-color");
  40. if (bgcolor.has_value() && bgcolor.value()->is_color()) {
  41. Rect background_rect;
  42. background_rect.set_x(rect().x() - style().padding().left.to_px());
  43. background_rect.set_width(rect().width() + style().padding().left.to_px() + style().padding().right.to_px());
  44. background_rect.set_y(rect().y() - style().padding().top.to_px());
  45. background_rect.set_height(rect().height() + style().padding().top.to_px() + style().padding().bottom.to_px());
  46. context.painter().fill_rect(background_rect, bgcolor.value()->to_color());
  47. }
  48. // TODO: render our border
  49. for_each_child([&](auto& child) {
  50. child.render(context);
  51. });
  52. }
  53. HitTestResult LayoutNode::hit_test(const Point& position) const
  54. {
  55. // FIXME: It would be nice if we could confidently skip over hit testing
  56. // parts of the layout tree, but currently we can't just check
  57. // m_rect.contains() since inline text rects can't be trusted..
  58. HitTestResult result { m_rect.contains(position) ? this : nullptr };
  59. for_each_child([&](auto& child) {
  60. auto child_result = child.hit_test(position);
  61. if (child_result.layout_node)
  62. result = child_result;
  63. });
  64. return result;
  65. }
  66. const Document& LayoutNode::document() const
  67. {
  68. if (is_anonymous())
  69. return parent()->document();
  70. return node()->document();
  71. }