StackingContext.cpp 32 KB

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