StackingContext.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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/ExtraMathConstants.h>
  9. #include <AK/QuickSort.h>
  10. #include <AK/StringBuilder.h>
  11. #include <LibGfx/AffineTransform.h>
  12. #include <LibGfx/Matrix4x4.h>
  13. #include <LibGfx/Painter.h>
  14. #include <LibGfx/Rect.h>
  15. #include <LibWeb/CSS/ComputedValues.h>
  16. #include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
  17. #include <LibWeb/Layout/Box.h>
  18. #include <LibWeb/Layout/ReplacedBox.h>
  19. #include <LibWeb/Layout/Viewport.h>
  20. #include <LibWeb/Painting/PaintableBox.h>
  21. #include <LibWeb/Painting/StackingContext.h>
  22. #include <LibWeb/Painting/TableBordersPainting.h>
  23. namespace Web::Painting {
  24. static void paint_node(Layout::Node const& layout_node, PaintContext& context, PaintPhase phase)
  25. {
  26. if (auto const* paintable = layout_node.paintable()) {
  27. if (paintable->containing_block() && paintable->containing_block()->is_scrollable()) {
  28. Gfx::PainterStateSaver saver(context.painter());
  29. auto scroll_offset = -paintable->containing_block()->paintable_box()->scroll_offset();
  30. context.painter().translate({ context.enclosing_device_pixels(scroll_offset.x()), context.enclosing_device_pixels(scroll_offset.y()) });
  31. paintable->paint(context, phase);
  32. } else {
  33. paintable->paint(context, phase);
  34. }
  35. }
  36. }
  37. StackingContext::StackingContext(Layout::Box& box, StackingContext* parent, size_t index_in_tree_order)
  38. : m_box(box)
  39. , m_transform(combine_transformations(m_box->computed_values().transformations()))
  40. , m_transform_origin(compute_transform_origin())
  41. , m_parent(parent)
  42. , m_index_in_tree_order(index_in_tree_order)
  43. {
  44. VERIFY(m_parent != this);
  45. if (m_parent)
  46. m_parent->m_children.append(this);
  47. }
  48. void StackingContext::sort()
  49. {
  50. quick_sort(m_children, [](auto& a, auto& b) {
  51. auto a_z_index = a->m_box->computed_values().z_index().value_or(0);
  52. auto b_z_index = b->m_box->computed_values().z_index().value_or(0);
  53. if (a_z_index == b_z_index)
  54. return a->m_index_in_tree_order < b->m_index_in_tree_order;
  55. return a_z_index < b_z_index;
  56. });
  57. for (auto* child : m_children)
  58. child->sort();
  59. }
  60. static PaintPhase to_paint_phase(StackingContext::StackingContextPaintPhase phase)
  61. {
  62. // There are not a fully correct mapping since some stacking context phases are combined.
  63. switch (phase) {
  64. case StackingContext::StackingContextPaintPhase::Floats:
  65. case StackingContext::StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced:
  66. case StackingContext::StackingContextPaintPhase::BackgroundAndBorders:
  67. return PaintPhase::Background;
  68. case StackingContext::StackingContextPaintPhase::Foreground:
  69. return PaintPhase::Foreground;
  70. case StackingContext::StackingContextPaintPhase::FocusAndOverlay:
  71. return PaintPhase::Overlay;
  72. default:
  73. VERIFY_NOT_REACHED();
  74. }
  75. }
  76. void StackingContext::paint_descendants(PaintContext& context, Layout::Node const& box, StackingContextPaintPhase phase) const
  77. {
  78. if (auto* paintable = box.paintable()) {
  79. paintable->before_children_paint(context, to_paint_phase(phase));
  80. paintable->apply_clip_overflow_rect(context, to_paint_phase(phase));
  81. }
  82. box.for_each_child([&](auto& child) {
  83. // If `child` establishes its own stacking context, skip over it.
  84. if (is<Layout::Box>(child) && child.paintable() && static_cast<Layout::Box const&>(child).paintable_box()->stacking_context())
  85. return;
  86. // If `child` is positioned with a z-index of `0` or `auto`, skip over it.
  87. if (child.is_positioned()) {
  88. auto const& z_index = child.computed_values().z_index();
  89. if (!z_index.has_value() || z_index.value() == 0)
  90. return;
  91. }
  92. bool child_is_inline_or_replaced = child.is_inline() || is<Layout::ReplacedBox>(child);
  93. switch (phase) {
  94. case StackingContextPaintPhase::BackgroundAndBorders:
  95. if (!child_is_inline_or_replaced && !child.is_floating()) {
  96. paint_node(child, context, PaintPhase::Background);
  97. bool is_table_with_collapsed_borders = child.display().is_table_inside() && child.computed_values().border_collapse() == CSS::BorderCollapse::Collapse;
  98. if (!child.display().is_table_cell() && !is_table_with_collapsed_borders)
  99. paint_node(child, context, PaintPhase::Border);
  100. paint_descendants(context, child, phase);
  101. if (child.display().is_table_inside() || child.computed_values().border_collapse() == CSS::BorderCollapse::Collapse) {
  102. paint_table_borders(context, child);
  103. }
  104. }
  105. break;
  106. case StackingContextPaintPhase::Floats:
  107. if (child.is_floating()) {
  108. paint_node(child, context, PaintPhase::Background);
  109. paint_node(child, context, PaintPhase::Border);
  110. paint_descendants(context, child, StackingContextPaintPhase::BackgroundAndBorders);
  111. }
  112. paint_descendants(context, child, phase);
  113. break;
  114. case StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced:
  115. if (child_is_inline_or_replaced) {
  116. paint_node(child, context, PaintPhase::Background);
  117. paint_node(child, context, PaintPhase::Border);
  118. paint_descendants(context, child, StackingContextPaintPhase::BackgroundAndBorders);
  119. }
  120. paint_descendants(context, child, phase);
  121. break;
  122. case StackingContextPaintPhase::Foreground:
  123. paint_node(child, context, PaintPhase::Foreground);
  124. paint_descendants(context, child, phase);
  125. break;
  126. case StackingContextPaintPhase::FocusAndOverlay:
  127. paint_node(child, context, PaintPhase::Outline);
  128. paint_node(child, context, PaintPhase::Overlay);
  129. paint_descendants(context, child, phase);
  130. break;
  131. }
  132. });
  133. if (auto* paintable = box.paintable()) {
  134. paintable->clear_clip_overflow_rect(context, to_paint_phase(phase));
  135. paintable->after_children_paint(context, to_paint_phase(phase));
  136. }
  137. }
  138. void StackingContext::paint_internal(PaintContext& context) const
  139. {
  140. // For a more elaborate description of the algorithm, see CSS 2.1 Appendix E
  141. // Draw the background and borders for the context root (steps 1, 2)
  142. paint_node(m_box, context, PaintPhase::Background);
  143. paint_node(m_box, context, PaintPhase::Border);
  144. auto paint_child = [&](auto* child) {
  145. auto parent = child->m_box->parent();
  146. auto* parent_paintable = parent ? parent->paintable() : nullptr;
  147. if (parent_paintable)
  148. parent_paintable->before_children_paint(context, PaintPhase::Foreground);
  149. auto containing_block = child->m_box->containing_block();
  150. auto* containing_block_paintable = containing_block ? containing_block->paintable() : nullptr;
  151. if (containing_block_paintable)
  152. containing_block_paintable->apply_clip_overflow_rect(context, PaintPhase::Foreground);
  153. child->paint(context);
  154. if (parent_paintable)
  155. parent_paintable->after_children_paint(context, PaintPhase::Foreground);
  156. if (containing_block_paintable)
  157. containing_block_paintable->clear_clip_overflow_rect(context, PaintPhase::Foreground);
  158. };
  159. // Draw positioned descendants with negative z-indices (step 3)
  160. for (auto* child : m_children) {
  161. if (child->m_box->computed_values().z_index().has_value() && child->m_box->computed_values().z_index().value() < 0)
  162. paint_child(child);
  163. }
  164. // Draw the background and borders for block-level children (step 4)
  165. paint_descendants(context, m_box, StackingContextPaintPhase::BackgroundAndBorders);
  166. // Draw the non-positioned floats (step 5)
  167. paint_descendants(context, m_box, StackingContextPaintPhase::Floats);
  168. // Draw inline content, replaced content, etc. (steps 6, 7)
  169. paint_descendants(context, m_box, StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced);
  170. paint_node(m_box, context, PaintPhase::Foreground);
  171. paint_descendants(context, m_box, StackingContextPaintPhase::Foreground);
  172. // Draw positioned descendants with z-index `0` or `auto` in tree order. (step 8)
  173. // NOTE: Non-positioned descendants that establish stacking contexts with z-index `0` or `auto` are also painted here.
  174. // FIXME: There's more to this step that we have yet to understand and implement.
  175. m_box->paintable_box()->for_each_in_subtree([&](Paintable const& paintable) {
  176. auto const& layout_node = paintable.layout_node();
  177. auto const& z_index = paintable.computed_values().z_index();
  178. if (auto const* child = paintable.stacking_context_rooted_here()) {
  179. if (!z_index.has_value() || z_index.value() == 0)
  180. paint_child(child);
  181. return TraversalDecision::SkipChildrenAndContinue;
  182. }
  183. if (z_index.has_value() && z_index.value() != 0)
  184. return TraversalDecision::Continue;
  185. if (!layout_node.is_positioned())
  186. return TraversalDecision::Continue;
  187. // At this point, `paintable_box` is a positioned descendant with z-index: auto
  188. // but no stacking context of its own.
  189. // FIXME: This is basically duplicating logic found elsewhere in this same function. Find a way to make this more elegant.
  190. auto parent = layout_node.parent();
  191. auto* parent_paintable = parent ? parent->paintable() : nullptr;
  192. if (parent_paintable)
  193. parent_paintable->before_children_paint(context, PaintPhase::Foreground);
  194. auto containing_block = layout_node.containing_block();
  195. auto* containing_block_paintable = containing_block ? containing_block->paintable() : nullptr;
  196. if (containing_block_paintable)
  197. containing_block_paintable->apply_clip_overflow_rect(context, PaintPhase::Foreground);
  198. paint_node(layout_node, context, PaintPhase::Background);
  199. paint_node(layout_node, context, PaintPhase::Border);
  200. paint_descendants(context, layout_node, StackingContextPaintPhase::BackgroundAndBorders);
  201. paint_descendants(context, layout_node, StackingContextPaintPhase::Floats);
  202. paint_descendants(context, layout_node, StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced);
  203. paint_node(layout_node, context, PaintPhase::Foreground);
  204. paint_descendants(context, layout_node, StackingContextPaintPhase::Foreground);
  205. paint_node(layout_node, context, PaintPhase::Outline);
  206. paint_node(layout_node, context, PaintPhase::Overlay);
  207. paint_descendants(context, layout_node, StackingContextPaintPhase::FocusAndOverlay);
  208. if (parent_paintable)
  209. parent_paintable->after_children_paint(context, PaintPhase::Foreground);
  210. if (containing_block_paintable)
  211. containing_block_paintable->clear_clip_overflow_rect(context, PaintPhase::Foreground);
  212. return TraversalDecision::Continue;
  213. });
  214. // Draw other positioned descendants (step 9)
  215. for (auto* child : m_children) {
  216. if (child->m_box->computed_values().z_index().has_value() && child->m_box->computed_values().z_index().value() >= 1)
  217. paint_child(child);
  218. }
  219. paint_node(m_box, context, PaintPhase::Outline);
  220. paint_node(m_box, context, PaintPhase::Overlay);
  221. paint_descendants(context, m_box, StackingContextPaintPhase::FocusAndOverlay);
  222. }
  223. Gfx::FloatMatrix4x4 StackingContext::get_transformation_matrix(CSS::Transformation const& transformation) const
  224. {
  225. auto count = transformation.values.size();
  226. auto value = [this, transformation](size_t index, CSS::Length const& reference_length = CSS::Length::make_px(0)) -> float {
  227. return transformation.values[index].visit(
  228. [this, reference_length](CSS::LengthPercentage const& value) -> double {
  229. return value.resolved(m_box, reference_length).to_px(m_box).to_float();
  230. },
  231. [this](CSS::AngleOrCalculated const& value) {
  232. return value.resolved(m_box).to_degrees() * M_DEG2RAD;
  233. },
  234. [](double value) {
  235. return value;
  236. });
  237. };
  238. auto reference_box = paintable_box().absolute_rect();
  239. auto width = CSS::Length::make_px(reference_box.width());
  240. auto height = CSS::Length::make_px(reference_box.height());
  241. switch (transformation.function) {
  242. case CSS::TransformFunction::Matrix:
  243. if (count == 6)
  244. return Gfx::FloatMatrix4x4(value(0), value(2), 0, value(4),
  245. value(1), value(3), 0, value(5),
  246. 0, 0, 1, 0,
  247. 0, 0, 0, 1);
  248. break;
  249. case CSS::TransformFunction::Matrix3d:
  250. if (count == 16)
  251. return Gfx::FloatMatrix4x4(value(0), value(4), value(8), value(12),
  252. value(1), value(5), value(9), value(13),
  253. value(2), value(6), value(10), value(14),
  254. value(3), value(7), value(11), value(15));
  255. break;
  256. case CSS::TransformFunction::Translate:
  257. if (count == 1)
  258. return Gfx::FloatMatrix4x4(1, 0, 0, value(0, width),
  259. 0, 1, 0, 0,
  260. 0, 0, 1, 0,
  261. 0, 0, 0, 1);
  262. if (count == 2)
  263. return Gfx::FloatMatrix4x4(1, 0, 0, value(0, width),
  264. 0, 1, 0, value(1, height),
  265. 0, 0, 1, 0,
  266. 0, 0, 0, 1);
  267. break;
  268. case CSS::TransformFunction::Translate3d:
  269. return Gfx::FloatMatrix4x4(1, 0, 0, value(0, width),
  270. 0, 1, 0, value(1, height),
  271. 0, 0, 1, value(2),
  272. 0, 0, 0, 1);
  273. break;
  274. case CSS::TransformFunction::TranslateX:
  275. if (count == 1)
  276. return Gfx::FloatMatrix4x4(1, 0, 0, value(0, width),
  277. 0, 1, 0, 0,
  278. 0, 0, 1, 0,
  279. 0, 0, 0, 1);
  280. break;
  281. case CSS::TransformFunction::TranslateY:
  282. if (count == 1)
  283. return Gfx::FloatMatrix4x4(1, 0, 0, 0,
  284. 0, 1, 0, value(0, height),
  285. 0, 0, 1, 0,
  286. 0, 0, 0, 1);
  287. break;
  288. case CSS::TransformFunction::Scale:
  289. if (count == 1)
  290. return Gfx::FloatMatrix4x4(value(0), 0, 0, 0,
  291. 0, value(0), 0, 0,
  292. 0, 0, 1, 0,
  293. 0, 0, 0, 1);
  294. if (count == 2)
  295. return Gfx::FloatMatrix4x4(value(0), 0, 0, 0,
  296. 0, value(1), 0, 0,
  297. 0, 0, 1, 0,
  298. 0, 0, 0, 1);
  299. break;
  300. case CSS::TransformFunction::ScaleX:
  301. if (count == 1)
  302. return Gfx::FloatMatrix4x4(value(0), 0, 0, 0,
  303. 0, 1, 0, 0,
  304. 0, 0, 1, 0,
  305. 0, 0, 0, 1);
  306. break;
  307. case CSS::TransformFunction::ScaleY:
  308. if (count == 1)
  309. return Gfx::FloatMatrix4x4(1, 0, 0, 0,
  310. 0, value(0), 0, 0,
  311. 0, 0, 1, 0,
  312. 0, 0, 0, 1);
  313. break;
  314. case CSS::TransformFunction::RotateX:
  315. if (count == 1)
  316. return Gfx::rotation_matrix({ 1.0f, 0.0f, 0.0f }, value(0));
  317. break;
  318. case CSS::TransformFunction::RotateY:
  319. if (count == 1)
  320. return Gfx::rotation_matrix({ 0.0f, 1.0f, 0.0f }, value(0));
  321. break;
  322. case CSS::TransformFunction::Rotate:
  323. case CSS::TransformFunction::RotateZ:
  324. if (count == 1)
  325. return Gfx::rotation_matrix({ 0.0f, 0.0f, 1.0f }, value(0));
  326. break;
  327. default:
  328. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Unhandled transformation function {}", MUST(CSS::TransformationStyleValue::create(transformation.function, {}))->to_string());
  329. }
  330. return Gfx::FloatMatrix4x4::identity();
  331. }
  332. Gfx::FloatMatrix4x4 StackingContext::combine_transformations(Vector<CSS::Transformation> const& transformations) const
  333. {
  334. auto matrix = Gfx::FloatMatrix4x4::identity();
  335. for (auto const& transform : transformations)
  336. matrix = matrix * get_transformation_matrix(transform);
  337. return matrix;
  338. }
  339. // FIXME: This extracts the affine 2D part of the full transformation matrix.
  340. // Use the whole matrix when we get better transformation support in LibGfx or use LibGL for drawing the bitmap
  341. Gfx::AffineTransform StackingContext::affine_transform_matrix() const
  342. {
  343. auto* m = m_transform.elements();
  344. return Gfx::AffineTransform(m[0][0], m[1][0], m[0][1], m[1][1], m[0][3], m[1][3]);
  345. }
  346. void StackingContext::paint(PaintContext& context) const
  347. {
  348. Gfx::PainterStateSaver saver(context.painter());
  349. if (m_box->is_fixed_position()) {
  350. context.painter().translate(-context.painter().translation());
  351. }
  352. auto opacity = m_box->computed_values().opacity();
  353. if (opacity == 0.0f)
  354. return;
  355. auto affine_transform = affine_transform_matrix();
  356. auto translation = context.rounded_device_point(affine_transform.translation().to_type<CSSPixels>()).to_type<int>().to_type<float>();
  357. affine_transform.set_translation(translation);
  358. if (opacity < 1.0f || !affine_transform.is_identity_or_translation()) {
  359. auto transform_origin = this->transform_origin();
  360. auto source_rect = context.enclosing_device_rect(paintable_box().absolute_paint_rect()).to_type<int>().to_type<float>().translated(-transform_origin);
  361. auto transformed_destination_rect = affine_transform.map(source_rect).translated(transform_origin);
  362. auto destination_rect = transformed_destination_rect.to_rounded<int>();
  363. // FIXME: We should find a way to scale the paintable, rather than paint into a separate bitmap,
  364. // then scale it. This snippet now copies the background at the destination, then scales it down/up
  365. // to the size of the source (which could add some artefacts, though just scaling the bitmap already does that).
  366. // We need to copy the background at the destination because a bunch of our rendering effects now rely on
  367. // being able to sample the painter (see border radii, shadows, filters, etc).
  368. CSSPixelPoint destination_clipped_fixup {};
  369. auto try_get_scaled_destination_bitmap = [&]() -> ErrorOr<NonnullRefPtr<Gfx::Bitmap>> {
  370. Gfx::IntRect actual_destination_rect;
  371. auto bitmap = TRY(context.painter().get_region_bitmap(destination_rect, Gfx::BitmapFormat::BGRA8888, actual_destination_rect));
  372. // get_region_bitmap() may clip to a smaller region if the requested rect goes outside the painter, so we need to account for that.
  373. destination_clipped_fixup = CSSPixelPoint { destination_rect.location() - actual_destination_rect.location() };
  374. destination_rect = actual_destination_rect;
  375. if (source_rect.size() != transformed_destination_rect.size()) {
  376. auto sx = static_cast<float>(source_rect.width()) / transformed_destination_rect.width();
  377. auto sy = static_cast<float>(source_rect.height()) / transformed_destination_rect.height();
  378. bitmap = TRY(bitmap->scaled(sx, sy));
  379. destination_clipped_fixup.scale_by(sx, sy);
  380. }
  381. return bitmap;
  382. };
  383. auto bitmap_or_error = try_get_scaled_destination_bitmap();
  384. if (bitmap_or_error.is_error())
  385. return;
  386. auto bitmap = bitmap_or_error.release_value_but_fixme_should_propagate_errors();
  387. Gfx::Painter painter(bitmap);
  388. painter.translate(context.rounded_device_point(-paintable_box().absolute_paint_rect().location() + destination_clipped_fixup).to_type<int>());
  389. auto paint_context = context.clone(painter);
  390. paint_internal(paint_context);
  391. if (destination_rect.size() == bitmap->size()) {
  392. context.painter().blit(destination_rect.location(), *bitmap, bitmap->rect(), opacity);
  393. } else {
  394. auto scaling_mode = CSS::to_gfx_scaling_mode(m_box->computed_values().image_rendering(), bitmap->rect(), destination_rect);
  395. context.painter().draw_scaled_bitmap(destination_rect, *bitmap, bitmap->rect(), opacity, scaling_mode);
  396. }
  397. } else {
  398. Gfx::PainterStateSaver saver(context.painter());
  399. context.painter().translate(affine_transform.translation().to_rounded<int>());
  400. paint_internal(context);
  401. }
  402. }
  403. Gfx::FloatPoint StackingContext::compute_transform_origin() const
  404. {
  405. auto style_value = m_box->computed_values().transform_origin();
  406. // FIXME: respect transform-box property
  407. auto reference_box = paintable_box().absolute_border_box_rect();
  408. auto x = reference_box.left() + style_value.x.to_px(m_box, reference_box.width());
  409. auto y = reference_box.top() + style_value.y.to_px(m_box, reference_box.height());
  410. return { x.to_float(), y.to_float() };
  411. }
  412. template<typename U, typename Callback>
  413. static TraversalDecision for_each_in_inclusive_subtree_of_type_within_same_stacking_context_in_reverse(Paintable const& paintable, Callback callback)
  414. {
  415. if (paintable.stacking_context_rooted_here()) {
  416. // Note: Include the stacking context (so we can hit test it), but don't recurse into it.
  417. if (auto decision = callback(static_cast<U const&>(paintable)); decision != TraversalDecision::Continue)
  418. return decision;
  419. return TraversalDecision::SkipChildrenAndContinue;
  420. }
  421. for (auto* child = paintable.last_child(); child; child = child->previous_sibling()) {
  422. if (for_each_in_inclusive_subtree_of_type_within_same_stacking_context_in_reverse<U>(*child, callback) == TraversalDecision::Break)
  423. return TraversalDecision::Break;
  424. }
  425. if (is<U>(paintable)) {
  426. if (auto decision = callback(static_cast<U const&>(paintable)); decision != TraversalDecision::Continue)
  427. return decision;
  428. }
  429. return TraversalDecision::Continue;
  430. }
  431. template<typename U, typename Callback>
  432. static TraversalDecision for_each_in_subtree_of_type_within_same_stacking_context_in_reverse(Paintable const& paintable, Callback callback)
  433. {
  434. for (auto* child = paintable.last_child(); child; child = child->previous_sibling()) {
  435. if (for_each_in_inclusive_subtree_of_type_within_same_stacking_context_in_reverse<U>(*child, callback) == TraversalDecision::Break)
  436. return TraversalDecision::Break;
  437. }
  438. return TraversalDecision::Continue;
  439. }
  440. Optional<HitTestResult> StackingContext::hit_test(CSSPixelPoint position, HitTestType type) const
  441. {
  442. if (!m_box->is_visible())
  443. return {};
  444. auto transform_origin = this->transform_origin().to_type<CSSPixels>();
  445. // NOTE: This CSSPixels -> Float -> CSSPixels conversion is because we can't AffineTransform::map() a CSSPixelPoint.
  446. Gfx::FloatPoint offset_position {
  447. (position.x() - transform_origin.x()).to_float(),
  448. (position.y() - transform_origin.y()).to_float()
  449. };
  450. auto transformed_position = affine_transform_matrix().inverse().value_or({}).map(offset_position).to_type<CSSPixels>() + transform_origin;
  451. if (paintable_box().layout_box().is_fixed_position()) {
  452. auto scroll_offset = paintable_box().document().browsing_context()->viewport_scroll_offset();
  453. transformed_position.translate_by(-scroll_offset);
  454. }
  455. // FIXME: Support more overflow variations.
  456. if (paintable_box().computed_values().overflow_x() == CSS::Overflow::Hidden && paintable_box().computed_values().overflow_y() == CSS::Overflow::Hidden) {
  457. if (!paintable_box().absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
  458. return {};
  459. }
  460. // NOTE: Hit testing basically happens in reverse painting order.
  461. // https://www.w3.org/TR/CSS22/visuren.html#z-index
  462. // 7. the child stacking contexts with positive stack levels (least positive first).
  463. // NOTE: Hit testing follows reverse painting order, that's why the conditions here are reversed.
  464. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  465. auto const& child = *m_children[i];
  466. if (child.m_box->computed_values().z_index().value_or(0) <= 0)
  467. break;
  468. auto result = child.hit_test(transformed_position, type);
  469. if (result.has_value() && result->paintable->visible_for_hit_testing())
  470. return result;
  471. }
  472. // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  473. Optional<HitTestResult> result;
  474. for_each_in_subtree_of_type_within_same_stacking_context_in_reverse<PaintableBox>(paintable_box(), [&](PaintableBox const& paintable_box) {
  475. // FIXME: Support more overflow variations.
  476. if (paintable_box.computed_values().overflow_x() == CSS::Overflow::Hidden && paintable_box.computed_values().overflow_y() == CSS::Overflow::Hidden) {
  477. if (!paintable_box.absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
  478. return TraversalDecision::SkipChildrenAndContinue;
  479. }
  480. auto const& z_index = paintable_box.computed_values().z_index();
  481. auto& layout_box = paintable_box.layout_box();
  482. if (z_index.value_or(0) == 0 && layout_box.is_positioned() && !paintable_box.stacking_context()) {
  483. auto candidate = paintable_box.hit_test(transformed_position, type);
  484. if (candidate.has_value() && candidate->paintable->visible_for_hit_testing()) {
  485. result = move(candidate);
  486. return TraversalDecision::Break;
  487. }
  488. }
  489. if (paintable_box.stacking_context()) {
  490. if (z_index.value_or(0) == 0) {
  491. auto candidate = paintable_box.stacking_context()->hit_test(transformed_position, type);
  492. if (candidate.has_value() && candidate->paintable->visible_for_hit_testing()) {
  493. result = move(candidate);
  494. return TraversalDecision::Break;
  495. }
  496. }
  497. }
  498. return TraversalDecision::Continue;
  499. });
  500. if (result.has_value())
  501. return result;
  502. // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  503. if (m_box->children_are_inline() && is<Layout::BlockContainer>(*m_box)) {
  504. auto result = paintable_box().hit_test(transformed_position, type);
  505. if (result.has_value() && result->paintable->visible_for_hit_testing())
  506. return result;
  507. }
  508. // 4. the non-positioned floats.
  509. for_each_in_subtree_of_type_within_same_stacking_context_in_reverse<PaintableBox>(paintable_box(), [&](PaintableBox const& paintable_box) {
  510. // FIXME: Support more overflow variations.
  511. if (paintable_box.computed_values().overflow_x() == CSS::Overflow::Hidden && paintable_box.computed_values().overflow_y() == CSS::Overflow::Hidden) {
  512. if (!paintable_box.absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
  513. return TraversalDecision::SkipChildrenAndContinue;
  514. }
  515. auto& layout_box = paintable_box.layout_box();
  516. if (layout_box.is_floating()) {
  517. if (auto candidate = paintable_box.hit_test(transformed_position, type); candidate.has_value()) {
  518. result = move(candidate);
  519. return TraversalDecision::Break;
  520. }
  521. }
  522. return TraversalDecision::Continue;
  523. });
  524. if (result.has_value() && result->paintable->visible_for_hit_testing())
  525. return result;
  526. // 3. the in-flow, non-inline-level, non-positioned descendants.
  527. if (!m_box->children_are_inline()) {
  528. for_each_in_subtree_of_type_within_same_stacking_context_in_reverse<PaintableBox>(paintable_box(), [&](PaintableBox const& paintable_box) {
  529. // FIXME: Support more overflow variations.
  530. if (paintable_box.computed_values().overflow_x() == CSS::Overflow::Hidden && paintable_box.computed_values().overflow_y() == CSS::Overflow::Hidden) {
  531. if (!paintable_box.absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
  532. return TraversalDecision::SkipChildrenAndContinue;
  533. }
  534. auto& layout_box = paintable_box.layout_box();
  535. if (!layout_box.is_absolutely_positioned() && !layout_box.is_floating()) {
  536. if (auto candidate = paintable_box.hit_test(transformed_position, type); candidate.has_value()) {
  537. result = move(candidate);
  538. return TraversalDecision::Break;
  539. }
  540. }
  541. return TraversalDecision::Continue;
  542. });
  543. if (result.has_value() && result->paintable->visible_for_hit_testing())
  544. return result;
  545. }
  546. // 2. the child stacking contexts with negative stack levels (most negative first).
  547. // NOTE: Hit testing follows reverse painting order, that's why the conditions here are reversed.
  548. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  549. auto const& child = *m_children[i];
  550. if (child.m_box->computed_values().z_index().value_or(0) >= 0)
  551. break;
  552. auto result = child.hit_test(transformed_position, type);
  553. if (result.has_value() && result->paintable->visible_for_hit_testing())
  554. return result;
  555. }
  556. // 1. the background and borders of the element forming the stacking context.
  557. if (paintable_box().absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y())) {
  558. return HitTestResult {
  559. .paintable = const_cast<PaintableBox&>(paintable_box()),
  560. };
  561. }
  562. return {};
  563. }
  564. void StackingContext::dump(int indent) const
  565. {
  566. StringBuilder builder;
  567. for (int i = 0; i < indent; ++i)
  568. builder.append(' ');
  569. builder.appendff("SC for {} {} [children: {}] (z-index: ", m_box->debug_description(), paintable_box().absolute_rect(), m_children.size());
  570. if (m_box->computed_values().z_index().has_value())
  571. builder.appendff("{}", m_box->computed_values().z_index().value());
  572. else
  573. builder.append("auto"sv);
  574. builder.append(')');
  575. auto affine_transform = affine_transform_matrix();
  576. if (!affine_transform.is_identity()) {
  577. builder.appendff(", transform: {}", affine_transform);
  578. }
  579. dbgln("{}", builder.string_view());
  580. for (auto& child : m_children)
  581. child->dump(indent + 1);
  582. }
  583. }