StackingContext.cpp 20 KB

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