StackingContext.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/QuickSort.h>
  8. #include <AK/StringBuilder.h>
  9. #include <LibGfx/AffineTransform.h>
  10. #include <LibGfx/Matrix4x4.h>
  11. #include <LibGfx/Painter.h>
  12. #include <LibGfx/Rect.h>
  13. #include <LibWeb/Layout/Box.h>
  14. #include <LibWeb/Layout/InitialContainingBlock.h>
  15. #include <LibWeb/Layout/ReplacedBox.h>
  16. #include <LibWeb/Painting/PaintableBox.h>
  17. #include <LibWeb/Painting/StackingContext.h>
  18. namespace Web::Painting {
  19. static void paint_node(Layout::Node const& layout_node, PaintContext& context, PaintPhase phase)
  20. {
  21. if (auto const* paintable = layout_node.paintable())
  22. paintable->paint(context, phase);
  23. }
  24. StackingContext::StackingContext(Layout::Box& box, StackingContext* parent)
  25. : m_box(box)
  26. , m_parent(parent)
  27. {
  28. VERIFY(m_parent != this);
  29. if (m_parent)
  30. m_parent->m_children.append(this);
  31. }
  32. void StackingContext::sort()
  33. {
  34. quick_sort(m_children, [](auto& a, auto& b) {
  35. auto a_z_index = a->m_box.computed_values().z_index().value_or(0);
  36. auto b_z_index = b->m_box.computed_values().z_index().value_or(0);
  37. if (a_z_index == b_z_index)
  38. return a->m_box.is_before(b->m_box);
  39. return a_z_index < b_z_index;
  40. });
  41. for (auto* child : m_children)
  42. child->sort();
  43. }
  44. void StackingContext::paint_descendants(PaintContext& context, Layout::Node& box, StackingContextPaintPhase phase) const
  45. {
  46. if (phase == StackingContextPaintPhase::Foreground) {
  47. if (auto* paintable = box.paintable())
  48. paintable->before_children_paint(context, PaintPhase::Foreground);
  49. }
  50. box.for_each_child([&](auto& child) {
  51. // If `child` establishes its own stacking context, skip over it.
  52. if (is<Layout::Box>(child) && child.paintable() && static_cast<Layout::Box const&>(child).paint_box()->stacking_context())
  53. return;
  54. bool child_is_inline_or_replaced = child.is_inline() || is<Layout::ReplacedBox>(child);
  55. switch (phase) {
  56. case StackingContextPaintPhase::BackgroundAndBorders:
  57. if (!child_is_inline_or_replaced && !child.is_floating() && !child.is_positioned()) {
  58. paint_node(child, context, PaintPhase::Background);
  59. paint_node(child, context, PaintPhase::Border);
  60. paint_descendants(context, child, phase);
  61. }
  62. break;
  63. case StackingContextPaintPhase::Floats:
  64. if (!child.is_positioned()) {
  65. if (child.is_floating()) {
  66. paint_node(child, context, PaintPhase::Background);
  67. paint_node(child, context, PaintPhase::Border);
  68. paint_descendants(context, child, StackingContextPaintPhase::BackgroundAndBorders);
  69. }
  70. paint_descendants(context, child, phase);
  71. }
  72. break;
  73. case StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced:
  74. if (!child.is_positioned()) {
  75. if (child_is_inline_or_replaced) {
  76. paint_node(child, context, PaintPhase::Background);
  77. paint_node(child, context, PaintPhase::Border);
  78. paint_descendants(context, child, StackingContextPaintPhase::BackgroundAndBorders);
  79. }
  80. paint_descendants(context, child, phase);
  81. }
  82. break;
  83. case StackingContextPaintPhase::Foreground:
  84. if (!child.is_positioned()) {
  85. paint_node(child, context, PaintPhase::Foreground);
  86. paint_descendants(context, child, phase);
  87. }
  88. break;
  89. case StackingContextPaintPhase::FocusAndOverlay:
  90. if (context.has_focus()) {
  91. paint_node(child, context, PaintPhase::FocusOutline);
  92. }
  93. paint_node(child, context, PaintPhase::Overlay);
  94. paint_descendants(context, child, phase);
  95. break;
  96. }
  97. });
  98. if (phase == StackingContextPaintPhase::Foreground) {
  99. if (auto* paintable = box.paintable())
  100. paintable->after_children_paint(context, PaintPhase::Foreground);
  101. }
  102. }
  103. void StackingContext::paint_internal(PaintContext& context) const
  104. {
  105. // For a more elaborate description of the algorithm, see CSS 2.1 Appendix E
  106. // Draw the background and borders for the context root (steps 1, 2)
  107. paint_node(m_box, context, PaintPhase::Background);
  108. paint_node(m_box, context, PaintPhase::Border);
  109. // Draw positioned descendants with negative z-indices (step 3)
  110. for (auto* child : m_children) {
  111. if (child->m_box.computed_values().z_index().has_value() && child->m_box.computed_values().z_index().value() < 0)
  112. child->paint(context);
  113. }
  114. // Draw the background and borders for block-level children (step 4)
  115. paint_descendants(context, m_box, StackingContextPaintPhase::BackgroundAndBorders);
  116. // Draw the non-positioned floats (step 5)
  117. paint_descendants(context, m_box, StackingContextPaintPhase::Floats);
  118. // Draw inline content, replaced content, etc. (steps 6, 7)
  119. paint_descendants(context, m_box, StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced);
  120. paint_node(m_box, context, PaintPhase::Foreground);
  121. paint_descendants(context, m_box, StackingContextPaintPhase::Foreground);
  122. // Draw other positioned descendants (steps 8, 9)
  123. for (auto* child : m_children) {
  124. if (child->m_box.computed_values().z_index().has_value() && child->m_box.computed_values().z_index().value() < 0)
  125. continue;
  126. child->paint(context);
  127. }
  128. paint_node(m_box, context, PaintPhase::FocusOutline);
  129. paint_node(m_box, context, PaintPhase::Overlay);
  130. paint_descendants(context, m_box, StackingContextPaintPhase::FocusAndOverlay);
  131. }
  132. Gfx::FloatMatrix4x4 StackingContext::get_transformation_matrix(CSS::Transformation const& transformation) const
  133. {
  134. Vector<float> float_values;
  135. for (auto const& value : transformation.values) {
  136. value.visit(
  137. [&](CSS::Length const& value) {
  138. float_values.append(value.to_px(m_box));
  139. },
  140. [&](float value) {
  141. float_values.append(value);
  142. });
  143. }
  144. switch (transformation.function) {
  145. case CSS::TransformFunction::Matrix:
  146. if (float_values.size() == 6)
  147. return Gfx::FloatMatrix4x4(float_values[0], float_values[2], 0, float_values[4],
  148. float_values[1], float_values[3], 0, float_values[5],
  149. 0, 0, 1, 0,
  150. 0, 0, 0, 1);
  151. break;
  152. case CSS::TransformFunction::Translate:
  153. if (float_values.size() == 1)
  154. return Gfx::FloatMatrix4x4(1, 0, 0, float_values[0],
  155. 0, 1, 0, 0,
  156. 0, 0, 1, 0,
  157. 0, 0, 0, 1);
  158. if (float_values.size() == 2)
  159. return Gfx::FloatMatrix4x4(1, 0, 0, float_values[0],
  160. 0, 1, 0, float_values[1],
  161. 0, 0, 1, 0,
  162. 0, 0, 0, 1);
  163. break;
  164. case CSS::TransformFunction::TranslateX:
  165. if (float_values.size() == 1)
  166. return Gfx::FloatMatrix4x4(1, 0, 0, float_values[0],
  167. 0, 1, 0, 0,
  168. 0, 0, 1, 0,
  169. 0, 0, 0, 1);
  170. break;
  171. case CSS::TransformFunction::TranslateY:
  172. if (float_values.size() == 1)
  173. return Gfx::FloatMatrix4x4(1, 0, 0, 0,
  174. 0, 1, 0, float_values[0],
  175. 0, 0, 1, 0,
  176. 0, 0, 0, 1);
  177. break;
  178. case CSS::TransformFunction::Scale:
  179. if (float_values.size() == 1)
  180. return Gfx::FloatMatrix4x4(float_values[0], 0, 0, 0,
  181. 0, float_values[0], 0, 0,
  182. 0, 0, 1, 0,
  183. 0, 0, 0, 1);
  184. if (float_values.size() == 2)
  185. return Gfx::FloatMatrix4x4(float_values[0], 0, 0, 0,
  186. 0, float_values[1], 0, 0,
  187. 0, 0, 1, 0,
  188. 0, 0, 0, 1);
  189. break;
  190. case CSS::TransformFunction::ScaleX:
  191. if (float_values.size() == 1)
  192. return Gfx::FloatMatrix4x4(float_values[0], 0, 0, 0,
  193. 0, 1, 0, 0,
  194. 0, 0, 1, 0,
  195. 0, 0, 0, 1);
  196. break;
  197. case CSS::TransformFunction::ScaleY:
  198. if (float_values.size() == 1)
  199. return Gfx::FloatMatrix4x4(1, 0, 0, 0,
  200. 0, float_values[0], 0, 0,
  201. 0, 0, 1, 0,
  202. 0, 0, 0, 1);
  203. break;
  204. default:
  205. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Unhandled transformation function {}", CSS::TransformationStyleValue::create(transformation.function, {})->to_string());
  206. }
  207. return Gfx::FloatMatrix4x4::identity();
  208. }
  209. Gfx::FloatMatrix4x4 StackingContext::combine_transformations(Vector<CSS::Transformation> const& transformations) const
  210. {
  211. auto matrix = Gfx::FloatMatrix4x4::identity();
  212. for (auto const& transform : transformations)
  213. matrix = matrix * get_transformation_matrix(transform);
  214. return matrix;
  215. }
  216. // FIXME: This extracts the affine 2D part of the full transformation matrix.
  217. // Use the whole matrix when we get better transformation support in LibGfx or use LibGL for drawing the bitmap
  218. Gfx::AffineTransform StackingContext::combine_transformations_2d(Vector<CSS::Transformation> const& transformations) const
  219. {
  220. auto matrix = combine_transformations(transformations);
  221. auto* m = matrix.elements();
  222. return Gfx::AffineTransform(m[0][0], m[1][0], m[0][1], m[1][1], m[0][3], m[1][3]);
  223. }
  224. void StackingContext::paint(PaintContext& context) const
  225. {
  226. Gfx::PainterStateSaver saver(context.painter());
  227. if (m_box.is_fixed_position()) {
  228. context.painter().translate(context.scroll_offset());
  229. }
  230. auto opacity = m_box.computed_values().opacity();
  231. if (opacity == 0.0f)
  232. return;
  233. auto affine_transform = combine_transformations_2d(m_box.computed_values().transformations());
  234. if (opacity < 1.0f || !affine_transform.is_identity()) {
  235. auto bitmap_or_error = Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, context.painter().target()->size());
  236. if (bitmap_or_error.is_error())
  237. return;
  238. auto bitmap = bitmap_or_error.release_value_but_fixme_should_propagate_errors();
  239. Gfx::Painter painter(bitmap);
  240. PaintContext paint_context(painter, context.palette(), context.scroll_offset());
  241. paint_internal(paint_context);
  242. // FIXME: Use the transform origin specified in CSS or SVG
  243. auto transform_origin = m_box.paint_box()->absolute_position();
  244. auto source_rect = m_box.paint_box()->absolute_rect().translated(-transform_origin);
  245. auto transformed_destination_rect = affine_transform.map(source_rect).translated(transform_origin);
  246. source_rect.translate_by(transform_origin);
  247. context.painter().draw_scaled_bitmap(Gfx::rounded_int_rect(transformed_destination_rect), *bitmap, source_rect, opacity, Gfx::Painter::ScalingMode::BilinearBlend);
  248. } else {
  249. paint_internal(context);
  250. }
  251. }
  252. HitTestResult StackingContext::hit_test(Gfx::FloatPoint const& position, HitTestType type) const
  253. {
  254. // FIXME: Use the transform origin specified in CSS or SVG
  255. auto transform_origin = m_box.paint_box()->absolute_position();
  256. auto affine_transform = combine_transformations_2d(m_box.computed_values().transformations());
  257. auto transformed_position = affine_transform.inverse().value_or({}).map(position - transform_origin) + transform_origin;
  258. // NOTE: Hit testing basically happens in reverse painting order.
  259. // https://www.w3.org/TR/CSS22/visuren.html#z-index
  260. // 7. the child stacking contexts with positive stack levels (least positive first).
  261. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  262. auto const& child = *m_children[i];
  263. if (child.m_box.computed_values().z_index().value_or(0) < 0)
  264. break;
  265. auto result = child.hit_test(transformed_position, type);
  266. if (result.paintable)
  267. return result;
  268. }
  269. HitTestResult result;
  270. // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  271. m_box.for_each_in_subtree_of_type<Layout::Box>([&](Layout::Box const& box) {
  272. if (box.is_positioned() && !box.paint_box()->stacking_context()) {
  273. result = box.paint_box()->hit_test(transformed_position, type);
  274. if (result.paintable)
  275. return IterationDecision::Break;
  276. }
  277. return IterationDecision::Continue;
  278. });
  279. if (result.paintable)
  280. return result;
  281. // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  282. if (m_box.children_are_inline() && is<Layout::BlockContainer>(m_box)) {
  283. auto result = m_box.paint_box()->hit_test(transformed_position, type);
  284. if (result.paintable)
  285. return result;
  286. }
  287. // 4. the non-positioned floats.
  288. m_box.for_each_in_subtree_of_type<Layout::Box>([&](Layout::Box const& box) {
  289. if (box.is_floating()) {
  290. result = box.paint_box()->hit_test(transformed_position, type);
  291. if (result.paintable)
  292. return IterationDecision::Break;
  293. }
  294. return IterationDecision::Continue;
  295. });
  296. // 3. the in-flow, non-inline-level, non-positioned descendants.
  297. if (!m_box.children_are_inline()) {
  298. m_box.for_each_in_subtree_of_type<Layout::Box>([&](Layout::Box const& box) {
  299. if (!box.is_absolutely_positioned() && !box.is_floating()) {
  300. result = box.paint_box()->hit_test(transformed_position, type);
  301. if (result.paintable)
  302. return IterationDecision::Break;
  303. }
  304. return IterationDecision::Continue;
  305. });
  306. if (result.paintable)
  307. return result;
  308. }
  309. // 2. the child stacking contexts with negative stack levels (most negative first).
  310. for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
  311. auto const& child = *m_children[i];
  312. if (child.m_box.computed_values().z_index().value_or(0) < 0)
  313. break;
  314. auto result = child.hit_test(transformed_position, type);
  315. if (result.paintable)
  316. return result;
  317. }
  318. // 1. the background and borders of the element forming the stacking context.
  319. if (m_box.paint_box()->absolute_border_box_rect().contains(transformed_position)) {
  320. return HitTestResult {
  321. .paintable = m_box.paintable(),
  322. };
  323. }
  324. return {};
  325. }
  326. void StackingContext::dump(int indent) const
  327. {
  328. StringBuilder builder;
  329. for (int i = 0; i < indent; ++i)
  330. builder.append(' ');
  331. builder.appendff("SC for {} {} [children: {}] (z-index: ", m_box.debug_description(), m_box.paint_box()->absolute_rect(), m_children.size());
  332. if (m_box.computed_values().z_index().has_value())
  333. builder.appendff("{}", m_box.computed_values().z_index().value());
  334. else
  335. builder.append("auto");
  336. builder.append(')');
  337. auto affine_transform = combine_transformations_2d(m_box.computed_values().transformations());
  338. if (!affine_transform.is_identity()) {
  339. builder.appendff(", transform: {}", affine_transform);
  340. }
  341. dbgln("{}", builder.string_view());
  342. for (auto& child : m_children)
  343. child->dump(indent + 1);
  344. }
  345. }