BackgroundPainting.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibGfx/AntiAliasingPainter.h>
  9. #include <LibGfx/Font/ScaledFont.h>
  10. #include <LibWeb/Layout/Node.h>
  11. #include <LibWeb/Layout/Viewport.h>
  12. #include <LibWeb/Painting/BackgroundPainting.h>
  13. #include <LibWeb/Painting/InlinePaintable.h>
  14. #include <LibWeb/Painting/PaintableBox.h>
  15. namespace Web::Painting {
  16. // https://drafts.csswg.org/css-images/#default-sizing
  17. static CSSPixelSize run_default_sizing_algorithm(
  18. Optional<CSSPixels> specified_width, Optional<CSSPixels> specified_height,
  19. Optional<CSSPixels> natural_width, Optional<CSSPixels> natural_height,
  20. Optional<CSSPixelFraction> natural_aspect_ratio,
  21. CSSPixelSize default_size)
  22. {
  23. // If the specified size is a definite width and height, the concrete object size is given that width and height.
  24. if (specified_width.has_value() && specified_height.has_value())
  25. return CSSPixelSize { specified_width.value(), specified_height.value() };
  26. // If the specified size is only a width or height (but not both) then the concrete object size is given that specified width or height.
  27. // The other dimension is calculated as follows:
  28. if (specified_width.has_value() || specified_height.has_value()) {
  29. // 1. If the object has a natural aspect ratio,
  30. // the missing dimension of the concrete object size is calculated using that aspect ratio and the present dimension.
  31. if (natural_aspect_ratio.has_value() && !natural_aspect_ratio->might_be_saturated()) {
  32. if (specified_width.has_value())
  33. return CSSPixelSize { specified_width.value(), (CSSPixels(1) / natural_aspect_ratio.value()) * specified_width.value() };
  34. if (specified_height.has_value())
  35. return CSSPixelSize { specified_height.value() * natural_aspect_ratio.value(), specified_height.value() };
  36. }
  37. // 2. Otherwise, if the missing dimension is present in the object’s natural dimensions,
  38. // the missing dimension is taken from the object’s natural dimensions.
  39. if (specified_height.has_value() && natural_width.has_value())
  40. return CSSPixelSize { natural_width.value(), specified_height.value() };
  41. if (specified_width.has_value() && natural_height.has_value())
  42. return CSSPixelSize { specified_width.value(), natural_height.value() };
  43. // 3. Otherwise, the missing dimension of the concrete object size is taken from the default object size.
  44. if (specified_height.has_value())
  45. return CSSPixelSize { default_size.width(), specified_height.value() };
  46. if (specified_width.has_value())
  47. return CSSPixelSize { specified_width.value(), default_size.height() };
  48. VERIFY_NOT_REACHED();
  49. }
  50. // If the specified size has no constraints:
  51. // 1. If the object has a natural height or width, its size is resolved as if its natural dimensions were given as the specified size.
  52. if (natural_width.has_value() || natural_height.has_value())
  53. return run_default_sizing_algorithm(natural_width, natural_height, natural_width, natural_height, natural_aspect_ratio, default_size);
  54. // FIXME: 2. Otherwise, its size is resolved as a contain constraint against the default object size.
  55. return default_size;
  56. }
  57. static Vector<Gfx::Path> compute_text_clip_paths(PaintContext& context, Paintable const& paintable)
  58. {
  59. Vector<Gfx::Path> text_clip_paths;
  60. auto add_text_clip_path = [&](PaintableFragment const& fragment) {
  61. // Scale to the device pixels.
  62. Gfx::Path glyph_run_path;
  63. for (auto glyph : fragment.glyph_run().glyphs()) {
  64. glyph.visit([&](auto& glyph) {
  65. glyph.font = glyph.font->with_size(glyph.font->point_size() * static_cast<float>(context.device_pixels_per_css_pixel()));
  66. glyph.position = glyph.position.scaled(context.device_pixels_per_css_pixel());
  67. });
  68. if (glyph.has<Gfx::DrawGlyph>()) {
  69. auto const& draw_glyph = glyph.get<Gfx::DrawGlyph>();
  70. // Get the path for the glyph.
  71. Gfx::Path glyph_path;
  72. auto const& scaled_font = static_cast<Gfx::ScaledFont const&>(*draw_glyph.font);
  73. auto glyph_id = scaled_font.glyph_id_for_code_point(draw_glyph.code_point);
  74. scaled_font.append_glyph_path_to(glyph_path, glyph_id);
  75. // Transform the path to the fragment's position.
  76. // FIXME: Record glyphs and use Painter::draw_glyphs() instead to avoid this duplicated code.
  77. auto top_left = draw_glyph.position + Gfx::FloatPoint(scaled_font.glyph_left_bearing(draw_glyph.code_point), 0);
  78. auto glyph_position = Gfx::GlyphRasterPosition::get_nearest_fit_for(top_left);
  79. auto transform = Gfx::AffineTransform {}.translate(glyph_position.blit_position.to_type<float>());
  80. glyph_run_path.append_path(glyph_path.copy_transformed(transform));
  81. }
  82. }
  83. // Calculate the baseline start position.
  84. auto fragment_absolute_rect = fragment.absolute_rect();
  85. auto fragment_absolute_device_rect = context.enclosing_device_rect(fragment_absolute_rect);
  86. DevicePixelPoint baseline_start { fragment_absolute_device_rect.x(), fragment_absolute_device_rect.y() + context.rounded_device_pixels(fragment.baseline()) };
  87. // Add the path to text_clip_paths.
  88. auto transform = Gfx::AffineTransform {}.translate(baseline_start.to_type<int>().to_type<float>());
  89. text_clip_paths.append(glyph_run_path.copy_transformed(transform));
  90. };
  91. paintable.for_each_in_inclusive_subtree([&](auto& paintable) {
  92. if (is<PaintableWithLines>(paintable)) {
  93. auto const& paintable_lines = static_cast<PaintableWithLines const&>(paintable);
  94. for (auto const& fragment : paintable_lines.fragments()) {
  95. if (is<Layout::TextNode>(fragment.layout_node()))
  96. add_text_clip_path(fragment);
  97. }
  98. } else if (is<InlinePaintable>(paintable)) {
  99. auto const& inline_paintable = static_cast<InlinePaintable const&>(paintable);
  100. for (auto const& fragment : inline_paintable.fragments()) {
  101. if (is<Layout::TextNode>(fragment.layout_node()))
  102. add_text_clip_path(fragment);
  103. }
  104. }
  105. return TraversalDecision::Continue;
  106. });
  107. return text_clip_paths;
  108. }
  109. // https://www.w3.org/TR/css-backgrounds-3/#backgrounds
  110. void paint_background(PaintContext& context, Layout::NodeWithStyleAndBoxModelMetrics const& layout_node, CSSPixelRect const& border_rect, Color background_color, CSS::ImageRendering image_rendering, Vector<CSS::BackgroundLayerData> const* background_layers, BorderRadiiData const& border_radii)
  111. {
  112. Vector<Gfx::Path> clip_paths {};
  113. if (background_layers && !background_layers->is_empty() && background_layers->last().clip == CSS::BackgroundBox::Text) {
  114. clip_paths = compute_text_clip_paths(context, *layout_node.paintable());
  115. }
  116. auto& painter = context.recording_painter();
  117. struct BackgroundBox {
  118. CSSPixelRect rect;
  119. BorderRadiiData radii;
  120. inline void shrink(CSSPixels top, CSSPixels right, CSSPixels bottom, CSSPixels left)
  121. {
  122. rect.shrink(top, right, bottom, left);
  123. radii.shrink(top, right, bottom, left);
  124. }
  125. };
  126. BackgroundBox border_box {
  127. border_rect,
  128. border_radii
  129. };
  130. auto get_box = [&](CSS::BackgroundBox box_clip) {
  131. auto box = border_box;
  132. switch (box_clip) {
  133. case CSS::BackgroundBox::ContentBox: {
  134. auto& padding = layout_node.box_model().padding;
  135. box.shrink(padding.top, padding.right, padding.bottom, padding.left);
  136. [[fallthrough]];
  137. }
  138. case CSS::BackgroundBox::PaddingBox: {
  139. auto& border = layout_node.box_model().border;
  140. box.shrink(border.top, border.right, border.bottom, border.left);
  141. [[fallthrough]];
  142. }
  143. case CSS::BackgroundBox::BorderBox:
  144. default:
  145. return box;
  146. }
  147. };
  148. auto color_box = border_box;
  149. if (background_layers && !background_layers->is_empty())
  150. color_box = get_box(background_layers->last().clip);
  151. auto layer_is_paintable = [&](auto& layer) {
  152. return layer.background_image && layer.background_image->is_paintable();
  153. };
  154. bool has_paintable_layers = false;
  155. if (background_layers) {
  156. for (auto& layer : *background_layers) {
  157. if (layer_is_paintable(layer)) {
  158. has_paintable_layers = true;
  159. break;
  160. }
  161. }
  162. }
  163. painter.fill_rect_with_rounded_corners(
  164. context.rounded_device_rect(color_box.rect).to_type<int>(),
  165. background_color,
  166. color_box.radii.top_left.as_corner(context),
  167. color_box.radii.top_right.as_corner(context),
  168. color_box.radii.bottom_right.as_corner(context),
  169. color_box.radii.bottom_left.as_corner(context),
  170. clip_paths);
  171. if (!has_paintable_layers)
  172. return;
  173. struct {
  174. DevicePixels top { 0 };
  175. DevicePixels bottom { 0 };
  176. DevicePixels left { 0 };
  177. DevicePixels right { 0 };
  178. } clip_shrink;
  179. auto border_top = layout_node.computed_values().border_top();
  180. auto border_bottom = layout_node.computed_values().border_bottom();
  181. auto border_left = layout_node.computed_values().border_left();
  182. auto border_right = layout_node.computed_values().border_right();
  183. if (border_top.color.alpha() == 255 && border_bottom.color.alpha() == 255
  184. && border_left.color.alpha() == 255 && border_right.color.alpha() == 255) {
  185. clip_shrink.top = context.rounded_device_pixels(border_top.width);
  186. clip_shrink.bottom = context.rounded_device_pixels(border_bottom.width);
  187. clip_shrink.left = context.rounded_device_pixels(border_left.width);
  188. clip_shrink.right = context.rounded_device_pixels(border_right.width);
  189. }
  190. // Note: Background layers are ordered front-to-back, so we paint them in reverse
  191. for (auto& layer : background_layers->in_reverse()) {
  192. if (!layer_is_paintable(layer))
  193. continue;
  194. RecordingPainterStateSaver state { painter };
  195. // Clip
  196. auto clip_box = get_box(layer.clip);
  197. CSSPixelRect const& css_clip_rect = clip_box.rect;
  198. auto clip_rect = context.rounded_device_rect(css_clip_rect);
  199. painter.add_clip_rect(clip_rect.to_type<int>());
  200. ScopedCornerRadiusClip corner_clip { context, clip_rect, clip_box.radii };
  201. if (layer.clip == CSS::BackgroundBox::BorderBox) {
  202. // Shrink the effective clip rect if to account for the bits the borders will definitely paint over
  203. // (if they all have alpha == 255).
  204. clip_rect.shrink(clip_shrink.top, clip_shrink.right, clip_shrink.bottom, clip_shrink.left);
  205. }
  206. auto& image = *layer.background_image;
  207. CSSPixelRect background_positioning_area;
  208. // Attachment and Origin
  209. switch (layer.attachment) {
  210. case CSS::BackgroundAttachment::Fixed:
  211. background_positioning_area = layout_node.root().navigable()->viewport_rect();
  212. break;
  213. case CSS::BackgroundAttachment::Local:
  214. background_positioning_area = get_box(layer.origin).rect;
  215. if (is<Layout::Box>(layout_node)) {
  216. auto* paintable_box = static_cast<Layout::Box const&>(layout_node).paintable_box();
  217. if (paintable_box) {
  218. auto scroll_offset = paintable_box->scroll_offset();
  219. background_positioning_area.translate_by(-scroll_offset.x(), -scroll_offset.y());
  220. }
  221. }
  222. break;
  223. case CSS::BackgroundAttachment::Scroll:
  224. background_positioning_area = get_box(layer.origin).rect;
  225. break;
  226. }
  227. Optional<CSSPixels> specified_width {};
  228. Optional<CSSPixels> specified_height {};
  229. if (layer.size_type == CSS::BackgroundSize::LengthPercentage) {
  230. if (!layer.size_x.is_auto())
  231. specified_width = layer.size_x.to_px(layout_node, background_positioning_area.width());
  232. if (!layer.size_y.is_auto())
  233. specified_height = layer.size_y.to_px(layout_node, background_positioning_area.height());
  234. }
  235. auto concrete_image_size = run_default_sizing_algorithm(
  236. specified_width, specified_height,
  237. image.natural_width(), image.natural_height(), image.natural_aspect_ratio(),
  238. background_positioning_area.size());
  239. // If any of these are zero, the NaNs will pop up in the painting code.
  240. if (background_positioning_area.is_empty() || concrete_image_size.is_empty())
  241. continue;
  242. // Size
  243. CSSPixelRect image_rect;
  244. switch (layer.size_type) {
  245. case CSS::BackgroundSize::Contain: {
  246. double max_width_ratio = (background_positioning_area.width() / concrete_image_size.width()).to_double();
  247. double max_height_ratio = (background_positioning_area.height() / concrete_image_size.height()).to_double();
  248. double ratio = min(max_width_ratio, max_height_ratio);
  249. image_rect.set_size(concrete_image_size.width().scaled(ratio), concrete_image_size.height().scaled(ratio));
  250. break;
  251. }
  252. case CSS::BackgroundSize::Cover: {
  253. double max_width_ratio = background_positioning_area.width().to_double() / concrete_image_size.width().to_double();
  254. double max_height_ratio = background_positioning_area.height().to_double() / concrete_image_size.height().to_double();
  255. double ratio = max(max_width_ratio, max_height_ratio);
  256. image_rect.set_size(concrete_image_size.width().scaled(ratio), concrete_image_size.height().scaled(ratio));
  257. break;
  258. }
  259. case CSS::BackgroundSize::LengthPercentage:
  260. image_rect.set_size(concrete_image_size);
  261. break;
  262. }
  263. // If after sizing we have a 0px image, we're done. Attempting to paint this would be an infinite loop.
  264. if (image_rect.is_empty())
  265. continue;
  266. // If background-repeat is round for one (or both) dimensions, there is a second step.
  267. // The UA must scale the image in that dimension (or both dimensions) so that it fits a
  268. // whole number of times in the background positioning area.
  269. if (layer.repeat_x == CSS::Repeat::Round || layer.repeat_y == CSS::Repeat::Round) {
  270. // If X ≠ 0 is the width of the image after step one and W is the width of the
  271. // background positioning area, then the rounded width X' = W / round(W / X)
  272. // where round() is a function that returns the nearest natural number
  273. // (integer greater than zero).
  274. if (layer.repeat_x == CSS::Repeat::Round) {
  275. image_rect.set_width(background_positioning_area.width() / round(background_positioning_area.width() / image_rect.width()));
  276. }
  277. if (layer.repeat_y == CSS::Repeat::Round) {
  278. image_rect.set_height(background_positioning_area.height() / round(background_positioning_area.height() / image_rect.height()));
  279. }
  280. // If background-repeat is round for one dimension only and if background-size is auto
  281. // for the other dimension, then there is a third step: that other dimension is scaled
  282. // so that the original aspect ratio is restored.
  283. if (layer.repeat_x != layer.repeat_y) {
  284. if (layer.size_x.is_auto()) {
  285. image_rect.set_width(image_rect.height() * (concrete_image_size.width() / concrete_image_size.height()));
  286. }
  287. if (layer.size_y.is_auto()) {
  288. image_rect.set_height(image_rect.width() * (concrete_image_size.height() / concrete_image_size.width()));
  289. }
  290. }
  291. }
  292. CSSPixels space_x = background_positioning_area.width() - image_rect.width();
  293. CSSPixels space_y = background_positioning_area.height() - image_rect.height();
  294. // Position
  295. CSSPixels offset_x = layer.position_offset_x.to_px(layout_node, space_x);
  296. if (layer.position_edge_x == CSS::PositionEdge::Right) {
  297. image_rect.set_right_without_resize(background_positioning_area.right() - offset_x);
  298. } else {
  299. image_rect.set_left(background_positioning_area.left() + offset_x);
  300. }
  301. CSSPixels offset_y = layer.position_offset_y.to_px(layout_node, space_y);
  302. if (layer.position_edge_y == CSS::PositionEdge::Bottom) {
  303. image_rect.set_bottom_without_resize(background_positioning_area.bottom() - offset_y);
  304. } else {
  305. image_rect.set_top(background_positioning_area.top() + offset_y);
  306. }
  307. // Repetition
  308. bool repeat_x = false;
  309. bool repeat_y = false;
  310. CSSPixels x_step = 0;
  311. CSSPixels y_step = 0;
  312. switch (layer.repeat_x) {
  313. case CSS::Repeat::Round:
  314. x_step = image_rect.width();
  315. repeat_x = true;
  316. break;
  317. case CSS::Repeat::Space: {
  318. int whole_images = (background_positioning_area.width() / image_rect.width()).to_int();
  319. if (whole_images <= 1) {
  320. x_step = image_rect.width();
  321. repeat_x = false;
  322. } else {
  323. auto space = fmod(background_positioning_area.width().to_double(), image_rect.width().to_double());
  324. x_step = image_rect.width() + CSSPixels::nearest_value_for(space / static_cast<double>(whole_images - 1));
  325. repeat_x = true;
  326. }
  327. break;
  328. }
  329. case CSS::Repeat::Repeat:
  330. x_step = image_rect.width();
  331. repeat_x = true;
  332. break;
  333. case CSS::Repeat::NoRepeat:
  334. repeat_x = false;
  335. break;
  336. }
  337. // Move image_rect to the left-most tile position that is still visible
  338. if (repeat_x && image_rect.x() > css_clip_rect.x()) {
  339. auto x_delta = floor(x_step * ceil((image_rect.x() - css_clip_rect.x()) / x_step));
  340. image_rect.set_x(image_rect.x() - x_delta);
  341. }
  342. switch (layer.repeat_y) {
  343. case CSS::Repeat::Round:
  344. y_step = image_rect.height();
  345. repeat_y = true;
  346. break;
  347. case CSS::Repeat::Space: {
  348. int whole_images = (background_positioning_area.height() / image_rect.height()).to_int();
  349. if (whole_images <= 1) {
  350. y_step = image_rect.height();
  351. repeat_y = false;
  352. } else {
  353. auto space = fmod(background_positioning_area.height().to_float(), image_rect.height().to_float());
  354. y_step = image_rect.height() + CSSPixels::nearest_value_for(static_cast<double>(space) / static_cast<double>(whole_images - 1));
  355. repeat_y = true;
  356. }
  357. break;
  358. }
  359. case CSS::Repeat::Repeat:
  360. y_step = image_rect.height();
  361. repeat_y = true;
  362. break;
  363. case CSS::Repeat::NoRepeat:
  364. repeat_y = false;
  365. break;
  366. }
  367. // Move image_rect to the top-most tile position that is still visible
  368. if (repeat_y && image_rect.y() > css_clip_rect.y()) {
  369. auto y_delta = floor(y_step * ceil((image_rect.y() - css_clip_rect.y()) / y_step));
  370. image_rect.set_y(image_rect.y() - y_delta);
  371. }
  372. CSSPixels initial_image_x = image_rect.x();
  373. CSSPixels image_y = image_rect.y();
  374. Optional<DevicePixelRect> last_image_device_rect;
  375. image.resolve_for_size(layout_node, image_rect.size());
  376. auto for_each_image_device_rect = [&](auto callback) {
  377. while (image_y < css_clip_rect.bottom()) {
  378. image_rect.set_y(image_y);
  379. auto image_x = initial_image_x;
  380. while (image_x < css_clip_rect.right()) {
  381. image_rect.set_x(image_x);
  382. auto image_device_rect = context.rounded_device_rect(image_rect);
  383. callback(image_device_rect);
  384. if (!repeat_x)
  385. break;
  386. image_x += x_step;
  387. }
  388. if (!repeat_y)
  389. break;
  390. image_y += y_step;
  391. }
  392. };
  393. if (auto color = image.color_if_single_pixel_bitmap(); color.has_value()) {
  394. // OPTIMIZATION: If the image is a single pixel, we can just fill the whole area with it.
  395. // However, we must first figure out the real coverage area, taking repeat etc into account.
  396. // FIXME: This could be written in a far more efficient way.
  397. auto fill_rect = Optional<DevicePixelRect> {};
  398. for_each_image_device_rect([&](auto const& image_device_rect) {
  399. if (!fill_rect.has_value()) {
  400. fill_rect = image_device_rect;
  401. } else {
  402. fill_rect = fill_rect->united(image_device_rect);
  403. }
  404. });
  405. painter.fill_rect(fill_rect->to_type<int>(), color.value(), clip_paths);
  406. } else {
  407. for_each_image_device_rect([&](auto const& image_device_rect) {
  408. image.paint(context, image_device_rect, image_rendering, clip_paths);
  409. });
  410. }
  411. }
  412. }
  413. }