StackingContext.cpp 33 KB

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