StackingContext.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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::Rotate:
  237. if (count == 1)
  238. return Gfx::rotation_matrix({ 0.0f, 0.0f, 1.0f }, value(0));
  239. break;
  240. default:
  241. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Unhandled transformation function {}", CSS::TransformationStyleValue::create(transformation.function, {})->to_string());
  242. }
  243. return Gfx::FloatMatrix4x4::identity();
  244. }
  245. Gfx::FloatMatrix4x4 StackingContext::combine_transformations(Vector<CSS::Transformation> const& transformations) const
  246. {
  247. auto matrix = Gfx::FloatMatrix4x4::identity();
  248. for (auto const& transform : transformations)
  249. matrix = matrix * get_transformation_matrix(transform);
  250. return matrix;
  251. }
  252. // FIXME: This extracts the affine 2D part of the full transformation matrix.
  253. // Use the whole matrix when we get better transformation support in LibGfx or use LibGL for drawing the bitmap
  254. Gfx::AffineTransform StackingContext::affine_transform_matrix() const
  255. {
  256. auto* m = m_transform.elements();
  257. return Gfx::AffineTransform(m[0][0], m[1][0], m[0][1], m[1][1], m[0][3], m[1][3]);
  258. }
  259. void StackingContext::paint(PaintContext& context) const
  260. {
  261. Gfx::PainterStateSaver saver(context.painter());
  262. if (m_box.is_fixed_position()) {
  263. context.painter().translate(context.scroll_offset());
  264. }
  265. auto opacity = m_box.computed_values().opacity();
  266. if (opacity == 0.0f)
  267. return;
  268. auto affine_transform = affine_transform_matrix();
  269. if (opacity < 1.0f || !affine_transform.is_identity_or_translation()) {
  270. auto transform_origin = this->transform_origin();
  271. auto source_rect = paintable().absolute_paint_rect().translated(-transform_origin);
  272. auto transformed_destination_rect = affine_transform.map(source_rect).translated(transform_origin);
  273. auto destination_rect = transformed_destination_rect.to_rounded<int>();
  274. // FIXME: We should find a way to scale the paintable, rather than paint into a separate bitmap,
  275. // then scale it. This snippet now copies the background at the destination, then scales it down/up
  276. // to the size of the source (which could add some artefacts, though just scaling the bitmap already does that).
  277. // We need to copy the background at the destination because a bunch of our rendering effects now rely on
  278. // being able to sample the painter (see border radii, shadows, filters, etc).
  279. Gfx::FloatPoint destination_clipped_fixup {};
  280. auto try_get_scaled_destination_bitmap = [&]() -> ErrorOr<NonnullRefPtr<Gfx::Bitmap>> {
  281. Gfx::IntRect actual_destination_rect;
  282. auto bitmap = TRY(context.painter().get_region_bitmap(destination_rect, Gfx::BitmapFormat::BGRA8888, actual_destination_rect));
  283. // get_region_bitmap() may clip to a smaller region if the requested rect goes outside the painter, so we need to account for that.
  284. destination_clipped_fixup = Gfx::FloatPoint { destination_rect.location() - actual_destination_rect.location() };
  285. destination_rect = actual_destination_rect;
  286. if (source_rect.size() != transformed_destination_rect.size()) {
  287. auto sx = static_cast<float>(source_rect.width()) / transformed_destination_rect.width();
  288. auto sy = static_cast<float>(source_rect.height()) / transformed_destination_rect.height();
  289. bitmap = TRY(bitmap->scaled(sx, sy));
  290. destination_clipped_fixup.scale_by(sx, sy);
  291. }
  292. return bitmap;
  293. };
  294. auto bitmap_or_error = try_get_scaled_destination_bitmap();
  295. if (bitmap_or_error.is_error())
  296. return;
  297. auto bitmap = bitmap_or_error.release_value_but_fixme_should_propagate_errors();
  298. Gfx::Painter painter(bitmap);
  299. painter.translate((-paintable().absolute_paint_rect().location() + destination_clipped_fixup).to_rounded<int>());
  300. auto paint_context = context.clone(painter);
  301. paint_internal(paint_context);
  302. if (destination_rect.size() == bitmap->size())
  303. context.painter().blit(destination_rect.location(), *bitmap, bitmap->rect(), opacity);
  304. else
  305. context.painter().draw_scaled_bitmap(destination_rect, *bitmap, bitmap->rect(), opacity, Gfx::Painter::ScalingMode::BilinearBlend);
  306. } else {
  307. Gfx::PainterStateSaver saver(context.painter());
  308. context.painter().translate(affine_transform.translation().to_rounded<int>());
  309. paint_internal(context);
  310. }
  311. }
  312. Gfx::FloatPoint StackingContext::compute_transform_origin() const
  313. {
  314. auto style_value = m_box.computed_values().transform_origin();
  315. // FIXME: respect transform-box property
  316. auto reference_box = paintable().absolute_border_box_rect();
  317. auto x = reference_box.left() + style_value.x.resolved(m_box, CSS::Length::make_px(reference_box.width())).to_px(m_box);
  318. auto y = reference_box.top() + style_value.y.resolved(m_box, CSS::Length::make_px(reference_box.height())).to_px(m_box);
  319. return { x, y };
  320. }
  321. Optional<HitTestResult> StackingContext::hit_test(Gfx::FloatPoint const& position, HitTestType type) const
  322. {
  323. if (!m_box.is_visible())
  324. return {};
  325. if (m_box.computed_values().z_index().value_or(0) < 0)
  326. return {};
  327. auto transform_origin = this->transform_origin();
  328. auto transformed_position = affine_transform_matrix().inverse().value_or({}).map(position - transform_origin) + transform_origin;
  329. // FIXME: Support more overflow variations.
  330. if (paintable().computed_values().overflow_x() == CSS::Overflow::Hidden && paintable().computed_values().overflow_y() == CSS::Overflow::Hidden) {
  331. if (!paintable().absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
  332. return {};
  333. }
  334. // NOTE: Hit testing basically happens in reverse painting order.
  335. // https://www.w3.org/TR/CSS22/visuren.html#z-index
  336. // 7. the child stacking contexts with positive stack levels (least positive first).
  337. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  338. auto const& child = *m_children[i];
  339. auto result = child.hit_test(transformed_position, type);
  340. if (result.has_value())
  341. return result;
  342. }
  343. Optional<HitTestResult> result;
  344. // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  345. paintable().for_each_in_subtree_of_type<PaintableBox>([&](auto& paint_box) {
  346. // FIXME: Support more overflow variations.
  347. if (paint_box.computed_values().overflow_x() == CSS::Overflow::Hidden && paint_box.computed_values().overflow_y() == CSS::Overflow::Hidden) {
  348. if (!paint_box.absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
  349. return TraversalDecision::SkipChildrenAndContinue;
  350. }
  351. auto& layout_box = paint_box.layout_box();
  352. if (layout_box.is_positioned() && !paint_box.stacking_context()) {
  353. if (auto candidate = paint_box.hit_test(transformed_position, type); candidate.has_value())
  354. result = move(candidate);
  355. }
  356. return TraversalDecision::Continue;
  357. });
  358. if (result.has_value())
  359. return result;
  360. // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  361. if (m_box.children_are_inline() && is<Layout::BlockContainer>(m_box)) {
  362. auto result = paintable().hit_test(transformed_position, type);
  363. if (result.has_value())
  364. return result;
  365. }
  366. // 4. the non-positioned floats.
  367. paintable().for_each_in_subtree_of_type<PaintableBox>([&](auto const& paint_box) {
  368. // FIXME: Support more overflow variations.
  369. if (paint_box.computed_values().overflow_x() == CSS::Overflow::Hidden && paint_box.computed_values().overflow_y() == CSS::Overflow::Hidden) {
  370. if (!paint_box.absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
  371. return TraversalDecision::SkipChildrenAndContinue;
  372. }
  373. auto& layout_box = paint_box.layout_box();
  374. if (layout_box.is_floating()) {
  375. if (auto candidate = paint_box.hit_test(transformed_position, type); candidate.has_value())
  376. result = move(candidate);
  377. }
  378. return TraversalDecision::Continue;
  379. });
  380. if (result.has_value())
  381. return result;
  382. // 3. the in-flow, non-inline-level, non-positioned descendants.
  383. if (!m_box.children_are_inline()) {
  384. paintable().for_each_in_subtree_of_type<PaintableBox>([&](auto const& paint_box) {
  385. // FIXME: Support more overflow variations.
  386. if (paint_box.computed_values().overflow_x() == CSS::Overflow::Hidden && paint_box.computed_values().overflow_y() == CSS::Overflow::Hidden) {
  387. if (!paint_box.absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
  388. return TraversalDecision::SkipChildrenAndContinue;
  389. }
  390. auto& layout_box = paint_box.layout_box();
  391. if (!layout_box.is_absolutely_positioned() && !layout_box.is_floating()) {
  392. if (auto candidate = paint_box.hit_test(transformed_position, type); candidate.has_value())
  393. result = move(candidate);
  394. }
  395. return TraversalDecision::Continue;
  396. });
  397. if (result.has_value())
  398. return result;
  399. }
  400. // 2. the child stacking contexts with negative stack levels (most negative first).
  401. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  402. auto const& child = *m_children[i];
  403. auto result = child.hit_test(transformed_position, type);
  404. if (result.has_value())
  405. return result;
  406. }
  407. // 1. the background and borders of the element forming the stacking context.
  408. if (paintable().absolute_border_box_rect().contains(transformed_position)) {
  409. return HitTestResult {
  410. .paintable = paintable(),
  411. };
  412. }
  413. return {};
  414. }
  415. void StackingContext::dump(int indent) const
  416. {
  417. StringBuilder builder;
  418. for (int i = 0; i < indent; ++i)
  419. builder.append(' ');
  420. builder.appendff("SC for {} {} [children: {}] (z-index: ", m_box.debug_description(), paintable().absolute_rect(), m_children.size());
  421. if (m_box.computed_values().z_index().has_value())
  422. builder.appendff("{}", m_box.computed_values().z_index().value());
  423. else
  424. builder.append("auto"sv);
  425. builder.append(')');
  426. auto affine_transform = affine_transform_matrix();
  427. if (!affine_transform.is_identity()) {
  428. builder.appendff(", transform: {}", affine_transform);
  429. }
  430. dbgln("{}", builder.string_view());
  431. for (auto& child : m_children)
  432. child->dump(indent + 1);
  433. }
  434. }