StackingContext.cpp 19 KB

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