StackingContext.cpp 32 KB

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