StackingContext.cpp 29 KB

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