StackingContext.cpp 29 KB

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