StackingContext.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 IterationDecision::Continue;
  104. }
  105. if (stacking_context && z_index.value_or(0) != 0)
  106. return IterationDecision::Continue;
  107. if (child.is_positioned() && z_index.value_or(0) == 0)
  108. return IterationDecision::Continue;
  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 IterationDecision::Continue;
  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. return IterationDecision::Continue;
  160. });
  161. paintable.after_children_paint(context, to_paint_phase(phase));
  162. }
  163. void StackingContext::paint_child(PaintContext& context, StackingContext const& child)
  164. {
  165. const_cast<StackingContext&>(child).set_last_paint_generation_id(context.paint_generation_id());
  166. auto parent_paintable = child.paintable().parent();
  167. if (parent_paintable)
  168. parent_paintable->before_children_paint(context, PaintPhase::Foreground);
  169. child.paint(context);
  170. if (parent_paintable)
  171. parent_paintable->after_children_paint(context, PaintPhase::Foreground);
  172. }
  173. void StackingContext::paint_internal(PaintContext& context) const
  174. {
  175. // For a more elaborate description of the algorithm, see CSS 2.1 Appendix E
  176. // Draw the background and borders for the context root (steps 1, 2)
  177. paint_node(paintable(), context, PaintPhase::Background);
  178. paint_node(paintable(), context, PaintPhase::Border);
  179. // Stacking contexts formed by positioned descendants with negative z-indices (excluding 0) in z-index order
  180. // (most negative first) then tree order. (step 3)
  181. // NOTE: This doesn't check if a descendant is positioned as modern CSS allows for alternative methods to establish stacking contexts.
  182. for (auto* child : m_children) {
  183. if (child->paintable().computed_values().z_index().has_value() && child->paintable().computed_values().z_index().value() < 0)
  184. paint_child(context, *child);
  185. }
  186. // Draw the background and borders for block-level children (step 4)
  187. paint_descendants(context, paintable(), StackingContextPaintPhase::BackgroundAndBorders);
  188. // Draw the non-positioned floats (step 5)
  189. paint_descendants(context, paintable(), StackingContextPaintPhase::Floats);
  190. // Draw inline content, replaced content, etc. (steps 6, 7)
  191. paint_descendants(context, paintable(), StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced);
  192. paint_node(paintable(), context, PaintPhase::Foreground);
  193. paint_descendants(context, paintable(), StackingContextPaintPhase::Foreground);
  194. // Draw positioned descendants with z-index `0` or `auto` in tree order. (step 8)
  195. // FIXME: There's more to this step that we have yet to understand and implement.
  196. for (auto const& paintable : m_positioned_descendants_with_stack_level_0_and_stacking_contexts) {
  197. if (!paintable->is_positioned())
  198. continue;
  199. // At this point, `paintable_box` is a positioned descendant with z-index: auto.
  200. // FIXME: This is basically duplicating logic found elsewhere in this same function. Find a way to make this more elegant.
  201. auto* parent_paintable = paintable->parent();
  202. if (parent_paintable)
  203. parent_paintable->before_children_paint(context, PaintPhase::Foreground);
  204. if (auto* child = paintable->stacking_context()) {
  205. paint_child(context, *child);
  206. } else {
  207. paint_node_as_stacking_context(paintable, context);
  208. }
  209. if (parent_paintable)
  210. parent_paintable->after_children_paint(context, PaintPhase::Foreground);
  211. };
  212. // Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1 in z-index order
  213. // (smallest first) then tree order. (Step 9)
  214. // NOTE: This doesn't check if a descendant is positioned as modern CSS allows for alternative methods to establish stacking contexts.
  215. for (auto* child : m_children) {
  216. if (child->paintable().computed_values().z_index().has_value() && child->paintable().computed_values().z_index().value() >= 1)
  217. paint_child(context, *child);
  218. }
  219. paint_node(paintable(), context, PaintPhase::Outline);
  220. if (context.should_paint_overlay()) {
  221. paint_node(paintable(), context, PaintPhase::Overlay);
  222. paint_descendants(context, paintable(), StackingContextPaintPhase::FocusAndOverlay);
  223. }
  224. }
  225. // FIXME: This extracts the affine 2D part of the full transformation matrix.
  226. // Use the whole matrix when we get better transformation support in LibGfx or use LibGL for drawing the bitmap
  227. Gfx::AffineTransform StackingContext::affine_transform_matrix() const
  228. {
  229. if (paintable().is_paintable_box())
  230. return Gfx::extract_2d_affine_transform(paintable_box().transform());
  231. return Gfx::AffineTransform {};
  232. }
  233. static Gfx::FloatMatrix4x4 matrix_with_scaled_translation(Gfx::FloatMatrix4x4 matrix, float scale)
  234. {
  235. auto* m = matrix.elements();
  236. m[0][3] *= scale;
  237. m[1][3] *= scale;
  238. m[2][3] *= scale;
  239. return matrix;
  240. }
  241. void StackingContext::paint(PaintContext& context) const
  242. {
  243. auto opacity = paintable().computed_values().opacity();
  244. if (opacity == 0.0f)
  245. return;
  246. DisplayListRecorderStateSaver saver(context.display_list_recorder());
  247. auto to_device_pixels_scale = float(context.device_pixels_per_css_pixel());
  248. Gfx::IntRect source_paintable_rect;
  249. if (paintable().is_paintable_box()) {
  250. source_paintable_rect = context.enclosing_device_rect(paintable_box().absolute_paint_rect()).to_type<int>();
  251. } else if (paintable().is_inline()) {
  252. source_paintable_rect = context.enclosing_device_rect(inline_paintable().bounding_rect()).to_type<int>();
  253. } else {
  254. VERIFY_NOT_REACHED();
  255. }
  256. auto transform_matrix = Gfx::FloatMatrix4x4::identity();
  257. Gfx::FloatPoint transform_origin;
  258. if (paintable().is_paintable_box()) {
  259. transform_matrix = paintable_box().transform();
  260. transform_origin = paintable_box().transform_origin().to_type<float>();
  261. }
  262. DisplayListRecorder::PushStackingContextParams push_stacking_context_params {
  263. .opacity = opacity,
  264. .is_fixed_position = paintable().is_fixed_position(),
  265. .source_paintable_rect = source_paintable_rect,
  266. .image_rendering = paintable().computed_values().image_rendering(),
  267. .transform = {
  268. .origin = transform_origin.scaled(to_device_pixels_scale),
  269. .matrix = matrix_with_scaled_translation(transform_matrix, to_device_pixels_scale),
  270. },
  271. };
  272. if (paintable().is_paintable_box()) {
  273. if (auto masking_area = paintable_box().get_masking_area(); masking_area.has_value()) {
  274. if (masking_area->is_empty())
  275. return;
  276. auto mask_bitmap = paintable_box().calculate_mask(context, *masking_area);
  277. if (mask_bitmap) {
  278. auto source_paintable_rect = context.enclosing_device_rect(*masking_area).to_type<int>();
  279. push_stacking_context_params.source_paintable_rect = source_paintable_rect;
  280. push_stacking_context_params.mask = StackingContextMask {
  281. .mask_bitmap = mask_bitmap.release_nonnull(),
  282. .mask_kind = *paintable_box().get_mask_type()
  283. };
  284. }
  285. }
  286. }
  287. context.display_list_recorder().save();
  288. if (paintable().is_paintable_box() && paintable_box().scroll_frame_id().has_value())
  289. context.display_list_recorder().set_scroll_frame_id(*paintable_box().scroll_frame_id());
  290. context.display_list_recorder().push_stacking_context(push_stacking_context_params);
  291. paint_internal(context);
  292. context.display_list_recorder().pop_stacking_context();
  293. context.display_list_recorder().restore();
  294. }
  295. TraversalDecision StackingContext::hit_test(CSSPixelPoint position, HitTestType type, Function<TraversalDecision(HitTestResult)> const& callback) const
  296. {
  297. if (!paintable().is_visible())
  298. return TraversalDecision::Continue;
  299. CSSPixelPoint transform_origin { 0, 0 };
  300. if (paintable().is_paintable_box())
  301. transform_origin = paintable_box().transform_origin();
  302. // NOTE: This CSSPixels -> Float -> CSSPixels conversion is because we can't AffineTransform::map() a CSSPixelPoint.
  303. Gfx::FloatPoint offset_position {
  304. (position.x() - transform_origin.x()).to_float(),
  305. (position.y() - transform_origin.y()).to_float()
  306. };
  307. auto transformed_position = affine_transform_matrix().inverse().value_or({}).map(offset_position).to_type<CSSPixels>() + transform_origin;
  308. if (paintable().is_fixed_position()) {
  309. auto scroll_offset = paintable().document().navigable()->viewport_scroll_offset();
  310. transformed_position.translate_by(-scroll_offset);
  311. }
  312. // NOTE: Hit testing basically happens in reverse painting order.
  313. // https://www.w3.org/TR/CSS22/visuren.html#z-index
  314. // 7. the child stacking contexts with positive stack levels (least positive first).
  315. // NOTE: Hit testing follows reverse painting order, that's why the conditions here are reversed.
  316. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  317. auto const& child = *m_children[i];
  318. if (child.paintable().computed_values().z_index().value_or(0) <= 0)
  319. break;
  320. if (child.hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  321. return TraversalDecision::Break;
  322. }
  323. // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  324. for (auto const& paintable : m_positioned_descendants_with_stack_level_0_and_stacking_contexts.in_reverse()) {
  325. if (paintable->stacking_context()) {
  326. if (paintable->stacking_context()->hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  327. return TraversalDecision::Break;
  328. } else {
  329. if (paintable->hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  330. return TraversalDecision::Break;
  331. }
  332. }
  333. // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  334. if (paintable().layout_node().children_are_inline() && is<Layout::BlockContainer>(paintable().layout_node())) {
  335. for (auto const* child = paintable().last_child(); child; child = child->previous_sibling()) {
  336. if (child->is_inline() && !child->is_absolutely_positioned() && !child->stacking_context()) {
  337. if (child->hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  338. return TraversalDecision::Break;
  339. }
  340. }
  341. }
  342. // 4. the non-positioned floats.
  343. for (auto const& paintable : m_non_positioned_floating_descendants.in_reverse()) {
  344. if (paintable->hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  345. return TraversalDecision::Break;
  346. }
  347. // 3. the in-flow, non-inline-level, non-positioned descendants.
  348. if (!paintable().layout_node().children_are_inline()) {
  349. for (auto const* child = paintable().last_child(); child; child = child->previous_sibling()) {
  350. if (!child->is_paintable_box())
  351. continue;
  352. auto const& paintable_box = verify_cast<PaintableBox>(*child);
  353. if (!paintable_box.is_absolutely_positioned() && !paintable_box.is_floating() && !paintable_box.stacking_context()) {
  354. if (paintable_box.hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  355. return TraversalDecision::Break;
  356. }
  357. }
  358. }
  359. // 2. the child stacking contexts with negative stack levels (most negative first).
  360. // NOTE: Hit testing follows reverse painting order, that's why the conditions here are reversed.
  361. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  362. auto const& child = *m_children[i];
  363. if (child.paintable().computed_values().z_index().value_or(0) >= 0)
  364. break;
  365. if (child.hit_test(transformed_position, type, callback) == TraversalDecision::Break)
  366. return TraversalDecision::Break;
  367. }
  368. // 1. the background and borders of the element forming the stacking context.
  369. if (paintable().is_paintable_box()) {
  370. if (paintable_box().absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y())) {
  371. auto hit_test_result = HitTestResult { .paintable = const_cast<PaintableBox&>(paintable_box()) };
  372. if (callback(hit_test_result) == TraversalDecision::Break)
  373. return TraversalDecision::Break;
  374. }
  375. }
  376. return TraversalDecision::Continue;
  377. }
  378. void StackingContext::dump(int indent) const
  379. {
  380. StringBuilder builder;
  381. for (int i = 0; i < indent; ++i)
  382. builder.append(' ');
  383. CSSPixelRect rect;
  384. if (paintable().is_paintable_box()) {
  385. rect = paintable_box().absolute_rect();
  386. } else if (paintable().is_inline_paintable()) {
  387. rect = inline_paintable().bounding_rect();
  388. } else {
  389. VERIFY_NOT_REACHED();
  390. }
  391. builder.appendff("SC for {} {} [children: {}] (z-index: ", paintable().layout_node().debug_description(), rect, m_children.size());
  392. if (paintable().computed_values().z_index().has_value())
  393. builder.appendff("{}", paintable().computed_values().z_index().value());
  394. else
  395. builder.append("auto"sv);
  396. builder.append(')');
  397. auto affine_transform = affine_transform_matrix();
  398. if (!affine_transform.is_identity()) {
  399. builder.appendff(", transform: {}", affine_transform);
  400. }
  401. dbgln("{}", builder.string_view());
  402. for (auto& child : m_children)
  403. child->dump(indent + 1);
  404. }
  405. }