StackingContext.cpp 29 KB

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