StackingContext.cpp 18 KB

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