StackingContext.cpp 22 KB

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