StackingContext.cpp 29 KB

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