StackingContext.cpp 21 KB

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