StackingContext.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/QuickSort.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibGfx/AffineTransform.h>
  11. #include <LibGfx/Matrix4x4.h>
  12. #include <LibGfx/Rect.h>
  13. #include <LibWeb/CSS/ComputedValues.h>
  14. #include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
  15. #include <LibWeb/Layout/Box.h>
  16. #include <LibWeb/Layout/ReplacedBox.h>
  17. #include <LibWeb/Layout/Viewport.h>
  18. #include <LibWeb/Painting/PaintableBox.h>
  19. #include <LibWeb/Painting/SVGPaintable.h>
  20. #include <LibWeb/Painting/StackingContext.h>
  21. #include <LibWeb/Painting/TableBordersPainting.h>
  22. #include <LibWeb/SVG/SVGMaskElement.h>
  23. namespace Web::Painting {
  24. static void paint_node(Paintable const& paintable, PaintContext& context, PaintPhase phase)
  25. {
  26. paintable.before_paint(context, phase);
  27. paintable.paint(context, phase);
  28. paintable.after_paint(context, phase);
  29. }
  30. StackingContext::StackingContext(Paintable& paintable, StackingContext* parent, size_t index_in_tree_order)
  31. : m_paintable(paintable)
  32. , m_parent(parent)
  33. , m_index_in_tree_order(index_in_tree_order)
  34. {
  35. VERIFY(m_parent != this);
  36. if (m_parent)
  37. m_parent->m_children.append(this);
  38. }
  39. void StackingContext::sort()
  40. {
  41. quick_sort(m_children, [](auto& a, auto& b) {
  42. auto a_z_index = a->paintable().computed_values().z_index().value_or(0);
  43. auto b_z_index = b->paintable().computed_values().z_index().value_or(0);
  44. if (a_z_index == b_z_index)
  45. return a->m_index_in_tree_order < b->m_index_in_tree_order;
  46. return a_z_index < b_z_index;
  47. });
  48. for (auto* child : m_children)
  49. child->sort();
  50. }
  51. void StackingContext::set_last_paint_generation_id(u64 generation_id)
  52. {
  53. if (m_last_paint_generation_id.has_value() && m_last_paint_generation_id.value() >= generation_id) {
  54. dbgln("FIXME: Painting commands are recorded twice for stacking context: {}", m_paintable->layout_node().debug_description());
  55. }
  56. m_last_paint_generation_id = generation_id;
  57. }
  58. static PaintPhase to_paint_phase(StackingContext::StackingContextPaintPhase phase)
  59. {
  60. // There are not a fully correct mapping since some stacking context phases are combined.
  61. switch (phase) {
  62. case StackingContext::StackingContextPaintPhase::Floats:
  63. case StackingContext::StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced:
  64. case StackingContext::StackingContextPaintPhase::BackgroundAndBorders:
  65. return PaintPhase::Background;
  66. case StackingContext::StackingContextPaintPhase::Foreground:
  67. return PaintPhase::Foreground;
  68. case StackingContext::StackingContextPaintPhase::FocusAndOverlay:
  69. return PaintPhase::Overlay;
  70. default:
  71. VERIFY_NOT_REACHED();
  72. }
  73. }
  74. void StackingContext::paint_node_as_stacking_context(Paintable const& paintable, PaintContext& context)
  75. {
  76. paint_node(paintable, context, PaintPhase::Background);
  77. paint_node(paintable, context, PaintPhase::Border);
  78. paint_descendants(context, paintable, StackingContextPaintPhase::BackgroundAndBorders);
  79. paint_descendants(context, paintable, StackingContextPaintPhase::Floats);
  80. paint_descendants(context, paintable, StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced);
  81. paint_node(paintable, context, PaintPhase::Foreground);
  82. paint_descendants(context, paintable, StackingContextPaintPhase::Foreground);
  83. paint_node(paintable, context, PaintPhase::Outline);
  84. paint_node(paintable, context, PaintPhase::Overlay);
  85. paint_descendants(context, paintable, StackingContextPaintPhase::FocusAndOverlay);
  86. }
  87. void StackingContext::paint_descendants(PaintContext& context, Paintable const& paintable, StackingContextPaintPhase phase)
  88. {
  89. paintable.before_children_paint(context, to_paint_phase(phase));
  90. paintable.for_each_child([&context, phase](auto& child) {
  91. auto* stacking_context = child.stacking_context();
  92. auto const& z_index = child.computed_values().z_index();
  93. // NOTE: Grid specification https://www.w3.org/TR/css-grid-2/#z-order says that grid items should be treated
  94. // the same way as CSS2 defines for inline-blocks:
  95. // "For each one of these, treat the element as if it created a new stacking context, but any positioned
  96. // descendants and descendants which actually create a new stacking context should be considered part of
  97. // the parent stacking context, not this new one."
  98. auto should_be_treated_as_stacking_context = child.layout_node().is_grid_item() && !z_index.has_value();
  99. if (should_be_treated_as_stacking_context) {
  100. // FIXME: This may not be fully correct with respect to the paint phases.
  101. if (phase == StackingContextPaintPhase::Foreground)
  102. paint_node_as_stacking_context(child, context);
  103. return;
  104. }
  105. if (stacking_context && z_index.value_or(0) != 0)
  106. return;
  107. if (child.is_positioned() && z_index.value_or(0) == 0)
  108. return;
  109. if (stacking_context) {
  110. // FIXME: This may not be fully correct with respect to the paint phases.
  111. if (phase == StackingContextPaintPhase::Foreground) {
  112. paint_child(context, *stacking_context);
  113. }
  114. // Note: Don't further recurse into descendants as paint_child() will do that.
  115. return;
  116. }
  117. bool child_is_inline_or_replaced = child.is_inline() || is<Layout::ReplacedBox>(child.layout_node());
  118. switch (phase) {
  119. case StackingContextPaintPhase::BackgroundAndBorders:
  120. if (!child_is_inline_or_replaced && !child.is_floating()) {
  121. paint_node(child, context, PaintPhase::Background);
  122. bool is_table_with_collapsed_borders = child.display().is_table_inside() && child.computed_values().border_collapse() == CSS::BorderCollapse::Collapse;
  123. if (!child.display().is_table_cell() && !is_table_with_collapsed_borders)
  124. paint_node(child, context, PaintPhase::Border);
  125. paint_descendants(context, child, phase);
  126. if (child.display().is_table_inside() || child.computed_values().border_collapse() == CSS::BorderCollapse::Collapse) {
  127. paint_table_borders(context, verify_cast<PaintableBox>(child));
  128. }
  129. }
  130. break;
  131. case StackingContextPaintPhase::Floats:
  132. if (child.is_floating()) {
  133. paint_node(child, context, PaintPhase::Background);
  134. paint_node(child, context, PaintPhase::Border);
  135. paint_descendants(context, child, StackingContextPaintPhase::BackgroundAndBorders);
  136. }
  137. paint_descendants(context, child, phase);
  138. break;
  139. case StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced:
  140. if (child_is_inline_or_replaced) {
  141. paint_node(child, context, PaintPhase::Background);
  142. paint_node(child, context, PaintPhase::Border);
  143. if (child.display().is_table_inside() && child.computed_values().border_collapse() == CSS::BorderCollapse::Separate)
  144. paint_table_borders(context, verify_cast<PaintableBox>(child));
  145. paint_descendants(context, child, StackingContextPaintPhase::BackgroundAndBorders);
  146. }
  147. paint_descendants(context, child, phase);
  148. break;
  149. case StackingContextPaintPhase::Foreground:
  150. paint_node(child, context, PaintPhase::Foreground);
  151. paint_descendants(context, child, phase);
  152. break;
  153. case StackingContextPaintPhase::FocusAndOverlay:
  154. paint_node(child, context, PaintPhase::Outline);
  155. paint_node(child, context, PaintPhase::Overlay);
  156. paint_descendants(context, child, phase);
  157. break;
  158. }
  159. });
  160. paintable.after_children_paint(context, to_paint_phase(phase));
  161. }
  162. void StackingContext::paint_child(PaintContext& context, StackingContext const& child)
  163. {
  164. const_cast<StackingContext&>(child).set_last_paint_generation_id(context.paint_generation_id());
  165. auto parent_paintable = child.paintable().parent();
  166. if (parent_paintable)
  167. parent_paintable->before_children_paint(context, PaintPhase::Foreground);
  168. child.paint(context);
  169. if (parent_paintable)
  170. parent_paintable->after_children_paint(context, PaintPhase::Foreground);
  171. }
  172. void StackingContext::paint_internal(PaintContext& context) const
  173. {
  174. // For a more elaborate description of the algorithm, see CSS 2.1 Appendix E
  175. // Draw the background and borders for the context root (steps 1, 2)
  176. paint_node(paintable(), context, PaintPhase::Background);
  177. paint_node(paintable(), context, PaintPhase::Border);
  178. // Stacking contexts formed by positioned descendants with negative z-indices (excluding 0) in z-index order
  179. // (most negative first) then tree order. (step 3)
  180. // NOTE: This doesn't check if a descendant is positioned as modern CSS allows for alternative methods to establish stacking contexts.
  181. for (auto* child : m_children) {
  182. if (child->paintable().computed_values().z_index().has_value() && child->paintable().computed_values().z_index().value() < 0)
  183. paint_child(context, *child);
  184. }
  185. // Draw the background and borders for block-level children (step 4)
  186. paint_descendants(context, paintable(), StackingContextPaintPhase::BackgroundAndBorders);
  187. // Draw the non-positioned floats (step 5)
  188. paint_descendants(context, paintable(), StackingContextPaintPhase::Floats);
  189. // Draw inline content, replaced content, etc. (steps 6, 7)
  190. paint_descendants(context, paintable(), StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced);
  191. paint_node(paintable(), context, PaintPhase::Foreground);
  192. paint_descendants(context, paintable(), StackingContextPaintPhase::Foreground);
  193. // Draw positioned descendants with z-index `0` or `auto` in tree order. (step 8)
  194. // FIXME: There's more to this step that we have yet to understand and implement.
  195. for (auto const& paintable : m_positioned_descendants_with_stack_level_0_and_stacking_contexts) {
  196. if (!paintable->is_positioned())
  197. continue;
  198. // At this point, `paintable_box` is a positioned descendant with z-index: auto.
  199. // FIXME: This is basically duplicating logic found elsewhere in this same function. Find a way to make this more elegant.
  200. auto* parent_paintable = paintable->parent();
  201. if (parent_paintable)
  202. parent_paintable->before_children_paint(context, PaintPhase::Foreground);
  203. if (auto* child = paintable->stacking_context()) {
  204. paint_child(context, *child);
  205. } else {
  206. paint_node_as_stacking_context(paintable, context);
  207. }
  208. if (parent_paintable)
  209. parent_paintable->after_children_paint(context, PaintPhase::Foreground);
  210. };
  211. // Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1 in z-index order
  212. // (smallest first) then tree order. (Step 9)
  213. // NOTE: This doesn't check if a descendant is positioned as modern CSS allows for alternative methods to establish stacking contexts.
  214. for (auto* child : m_children) {
  215. if (child->paintable().computed_values().z_index().has_value() && child->paintable().computed_values().z_index().value() >= 1)
  216. paint_child(context, *child);
  217. }
  218. paint_node(paintable(), context, PaintPhase::Outline);
  219. if (context.should_paint_overlay()) {
  220. paint_node(paintable(), context, PaintPhase::Overlay);
  221. paint_descendants(context, paintable(), StackingContextPaintPhase::FocusAndOverlay);
  222. }
  223. }
  224. // FIXME: This extracts the affine 2D part of the full transformation matrix.
  225. // Use the whole matrix when we get better transformation support in LibGfx or use LibGL for drawing the bitmap
  226. Gfx::AffineTransform StackingContext::affine_transform_matrix() const
  227. {
  228. if (paintable().is_paintable_box())
  229. return Gfx::extract_2d_affine_transform(paintable_box().transform());
  230. return Gfx::AffineTransform {};
  231. }
  232. static Gfx::FloatMatrix4x4 matrix_with_scaled_translation(Gfx::FloatMatrix4x4 matrix, float scale)
  233. {
  234. auto* m = matrix.elements();
  235. m[0][3] *= scale;
  236. m[1][3] *= scale;
  237. m[2][3] *= scale;
  238. return matrix;
  239. }
  240. void StackingContext::paint(PaintContext& context) const
  241. {
  242. auto opacity = paintable().computed_values().opacity();
  243. if (opacity == 0.0f)
  244. return;
  245. RecordingPainterStateSaver saver(context.recording_painter());
  246. auto to_device_pixels_scale = float(context.device_pixels_per_css_pixel());
  247. Gfx::IntRect source_paintable_rect;
  248. if (paintable().is_paintable_box()) {
  249. source_paintable_rect = context.enclosing_device_rect(paintable_box().absolute_paint_rect()).to_type<int>();
  250. } else if (paintable().is_inline()) {
  251. source_paintable_rect = context.enclosing_device_rect(inline_paintable().bounding_rect()).to_type<int>();
  252. } else {
  253. VERIFY_NOT_REACHED();
  254. }
  255. auto transform_matrix = Gfx::FloatMatrix4x4::identity();
  256. Gfx::FloatPoint transform_origin;
  257. if (paintable().is_paintable_box()) {
  258. transform_matrix = paintable_box().transform();
  259. transform_origin = paintable_box().transform_origin().to_type<float>();
  260. }
  261. RecordingPainter::PushStackingContextParams push_stacking_context_params {
  262. .opacity = opacity,
  263. .is_fixed_position = paintable().is_fixed_position(),
  264. .source_paintable_rect = source_paintable_rect,
  265. .image_rendering = paintable().computed_values().image_rendering(),
  266. .transform = {
  267. .origin = transform_origin.scaled(to_device_pixels_scale),
  268. .matrix = matrix_with_scaled_translation(transform_matrix, to_device_pixels_scale),
  269. },
  270. };
  271. if (paintable().is_paintable_box()) {
  272. if (auto masking_area = paintable_box().get_masking_area(); masking_area.has_value()) {
  273. if (masking_area->is_empty())
  274. return;
  275. auto mask_bitmap = paintable_box().calculate_mask(context, *masking_area);
  276. if (mask_bitmap) {
  277. auto source_paintable_rect = context.enclosing_device_rect(*masking_area).to_type<int>();
  278. push_stacking_context_params.source_paintable_rect = source_paintable_rect;
  279. push_stacking_context_params.mask = StackingContextMask {
  280. .mask_bitmap = mask_bitmap.release_nonnull(),
  281. .mask_kind = *paintable_box().get_mask_type()
  282. };
  283. }
  284. }
  285. }
  286. context.recording_painter().save();
  287. if (paintable().is_paintable_box() && paintable_box().scroll_frame_id().has_value())
  288. context.recording_painter().set_scroll_frame_id(*paintable_box().scroll_frame_id());
  289. context.recording_painter().push_stacking_context(push_stacking_context_params);
  290. paint_internal(context);
  291. context.recording_painter().pop_stacking_context();
  292. context.recording_painter().restore();
  293. }
  294. TraversalDecision StackingContext::hit_test(CSSPixelPoint position, HitTestType type, Function<TraversalDecision(HitTestResult)> const& callback) const
  295. {
  296. if (!paintable().is_visible())
  297. return TraversalDecision::Continue;
  298. CSSPixelPoint transform_origin { 0, 0 };
  299. if (paintable().is_paintable_box())
  300. transform_origin = paintable_box().transform_origin();
  301. // NOTE: This CSSPixels -> Float -> CSSPixels conversion is because we can't AffineTransform::map() a CSSPixelPoint.
  302. Gfx::FloatPoint offset_position {
  303. (position.x() - transform_origin.x()).to_float(),
  304. (position.y() - transform_origin.y()).to_float()
  305. };
  306. auto transformed_position = affine_transform_matrix().inverse().value_or({}).map(offset_position).to_type<CSSPixels>() + transform_origin;
  307. if (paintable().is_fixed_position()) {
  308. auto scroll_offset = paintable().document().navigable()->viewport_scroll_offset();
  309. transformed_position.translate_by(-scroll_offset);
  310. }
  311. // NOTE: Hit testing basically happens in reverse painting order.
  312. // https://www.w3.org/TR/CSS22/visuren.html#z-index
  313. // 7. the child stacking contexts with positive stack levels (least positive first).
  314. // NOTE: Hit testing follows reverse painting order, that's why the conditions here are reversed.
  315. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  316. auto const& child = *m_children[i];
  317. if (child.paintable().computed_values().z_index().value_or(0) <= 0)
  318. break;
  319. if (child.hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  320. return TraversalDecision::Break;
  321. }
  322. // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  323. for (auto const& paintable : m_positioned_descendants_with_stack_level_0_and_stacking_contexts.in_reverse()) {
  324. if (paintable->stacking_context()) {
  325. if (paintable->stacking_context()->hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  326. return TraversalDecision::Break;
  327. } else {
  328. if (paintable->hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  329. return TraversalDecision::Break;
  330. }
  331. }
  332. // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  333. if (paintable().layout_node().children_are_inline() && is<Layout::BlockContainer>(paintable().layout_node())) {
  334. for (auto const* child = paintable().last_child(); child; child = child->previous_sibling()) {
  335. if (child->is_inline() && !child->is_absolutely_positioned() && !child->stacking_context()) {
  336. if (child->hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  337. return TraversalDecision::Break;
  338. }
  339. }
  340. }
  341. // 4. the non-positioned floats.
  342. for (auto const& paintable : m_non_positioned_floating_descendants.in_reverse()) {
  343. if (paintable->hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  344. return TraversalDecision::Break;
  345. }
  346. // 3. the in-flow, non-inline-level, non-positioned descendants.
  347. if (!paintable().layout_node().children_are_inline()) {
  348. for (auto const* child = paintable().last_child(); child; child = child->previous_sibling()) {
  349. if (!child->is_paintable_box())
  350. continue;
  351. auto const& paintable_box = verify_cast<PaintableBox>(*child);
  352. if (!paintable_box.is_absolutely_positioned() && !paintable_box.is_floating() && !paintable_box.stacking_context()) {
  353. if (paintable_box.hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  354. return TraversalDecision::Break;
  355. }
  356. }
  357. }
  358. // 2. the child stacking contexts with negative stack levels (most negative first).
  359. // NOTE: Hit testing follows reverse painting order, that's why the conditions here are reversed.
  360. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  361. auto const& child = *m_children[i];
  362. if (child.paintable().computed_values().z_index().value_or(0) >= 0)
  363. break;
  364. if (child.hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  365. return TraversalDecision::Break;
  366. }
  367. // 1. the background and borders of the element forming the stacking context.
  368. if (paintable().is_paintable_box()) {
  369. if (paintable_box().absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y())) {
  370. auto hit_test_result = HitTestResult { .paintable = const_cast<PaintableBox&>(paintable_box()) };
  371. if (callback(hit_test_result) == TraversalDecision::Break)
  372. return TraversalDecision::Break;
  373. }
  374. }
  375. return TraversalDecision::Continue;
  376. }
  377. void StackingContext::dump(int indent) const
  378. {
  379. StringBuilder builder;
  380. for (int i = 0; i < indent; ++i)
  381. builder.append(' ');
  382. CSSPixelRect rect;
  383. if (paintable().is_paintable_box()) {
  384. rect = paintable_box().absolute_rect();
  385. } else if (paintable().is_inline_paintable()) {
  386. rect = inline_paintable().bounding_rect();
  387. } else {
  388. VERIFY_NOT_REACHED();
  389. }
  390. builder.appendff("SC for {} {} [children: {}] (z-index: ", paintable().layout_node().debug_description(), rect, m_children.size());
  391. if (paintable().computed_values().z_index().has_value())
  392. builder.appendff("{}", paintable().computed_values().z_index().value());
  393. else
  394. builder.append("auto"sv);
  395. builder.append(')');
  396. auto affine_transform = affine_transform_matrix();
  397. if (!affine_transform.is_identity()) {
  398. builder.appendff(", transform: {}", affine_transform);
  399. }
  400. dbgln("{}", builder.string_view());
  401. for (auto& child : m_children)
  402. child->dump(indent + 1);
  403. }
  404. }